Skip to content

Commit a699cfc

Browse files
Merge remote-tracking branch 'origin/main' into xreview/pr52
# Conflicts: # packages/contracts/src/rpc.ts
2 parents 85b51a9 + c5f3419 commit a699cfc

79 files changed

Lines changed: 4818 additions & 385 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/features/settings/ThreadSettingsSections.tsx‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export function SettingsLabsRouteScreen() {
4242
contentContainerClassName="gap-6 px-5 pt-4"
4343
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
4444
>
45+
<ThreadSplitSettingsSection />
4546
<BetaSettingsSection />
4647
<LegacySettingsSection />
4748
</ScrollView>
@@ -294,3 +295,47 @@ function LegacySettingsSection() {
294295
</View>
295296
);
296297
}
298+
299+
function ThreadSplitSettingsSection() {
300+
const { environments } = useEnvironments();
301+
const connected = environments.filter(
302+
(environment) => environment.connection.phase === "connected",
303+
);
304+
const writable = useEnvironmentsWithScope(connected, AuthSettingsWriteScope);
305+
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
306+
label: "thread split suggestions setting",
307+
reportFailure: true,
308+
});
309+
return (
310+
<SettingsSection title="Thread suggestions">
311+
{connected.map((environment) => {
312+
const policy = environment.serverConfig?.managedPolicy;
313+
const managed = isManagedSettingPath(policy, "threadSplitSuggestionsEnabled");
314+
return (
315+
<SettingsSwitchRow
316+
key={environment.environmentId}
317+
icon="square.and.pencil"
318+
label={environment.label}
319+
subtitle={
320+
environment.serverConfig?.settings.threadSplitModelEndpoint
321+
? "Suggest a fresh thread for an independent message. Nothing moves until you choose it."
322+
: "Configure the local decision model in Labs on web or desktop first."
323+
}
324+
value={environment.serverConfig?.settings.threadSplitSuggestionsEnabled === true}
325+
disabled={
326+
managed ||
327+
!writable.has(environment.environmentId) ||
328+
!environment.serverConfig?.settings.threadSplitModelEndpoint
329+
}
330+
onValueChange={(value) =>
331+
void updateSettings({
332+
environmentId: environment.environmentId,
333+
input: { patch: { threadSplitSuggestionsEnabled: value } },
334+
})
335+
}
336+
/>
337+
);
338+
})}
339+
</SettingsSection>
340+
);
341+
}

‎apps/mobile/src/features/threads/ThreadComposer.tsx‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ThreadSplitSuggestion } from "./ThreadSplitSuggestion";
12
import { ProjectKnowledgeEntry } from "../../components/ProjectKnowledgeEntry";
23
import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";
34
import { Button } from "../../components/ui/Button";
@@ -449,7 +450,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
449450
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
450451
const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
451452
const composerDraftKey = props.draftKey ?? composerOwnerKey;
452-
const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey);
453+
const {
454+
text: draftMessage,
455+
attachments: draftAttachments,
456+
context: draftContext,
457+
} = useComposerDraft(composerDraftKey);
453458
const queuedEdit = props.queuedEdit ?? null;
454459
const hasContent =
455460
draftMessage.trim().length > 0 ||
@@ -903,6 +908,28 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
903908
/>
904909
) : null}
905910

911+
<ThreadSplitSuggestion
912+
key={composerOwnerKey}
913+
environmentId={props.environmentId}
914+
threadId={props.selectedThread.id}
915+
projectId={props.selectedThread.projectId}
916+
draftKey={composerDraftKey}
917+
message={draftMessage}
918+
enabled={
919+
props.serverConfig?.settings.threadSplitSuggestionsEnabled === true &&
920+
Boolean(props.serverConfig.settings.threadSplitModelEndpoint) &&
921+
!props.isDraft &&
922+
!props.hidden &&
923+
!props.activeThreadBusy &&
924+
props.canOperateThread &&
925+
props.connectionState === "connected" &&
926+
props.queueCount === 0 &&
927+
queuedEdit === null &&
928+
draftAttachments.length === 0 &&
929+
!draftContext
930+
}
931+
/>
932+
906933
<ComposerSurface
907934
animateLayout={false}
908935
style={{
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import type { ReactNode } from "react";
2+
import { act } from "react";
3+
import { createRoot } from "react-dom/client";
4+
import { describe, expect, it, vi } from "vite-plus/test";
5+
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
6+
7+
const state = vi.hoisted(() => ({
8+
suggest: vi.fn(),
9+
}));
10+
11+
vi.mock("react-native", () => ({
12+
View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
13+
}));
14+
vi.mock("@react-navigation/native", () => ({
15+
StackActions: { push: (name: string, params: unknown) => ({ name, params }) },
16+
useIsFocused: () => true,
17+
useNavigation: () => ({ dispatch: vi.fn() }),
18+
}));
19+
vi.mock("../../components/ui/Button", () => ({
20+
Button: ({ label, onPress }: { label: string; onPress: () => void }) => (
21+
<button type="button" onClick={onPress}>
22+
{label}
23+
</button>
24+
),
25+
}));
26+
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => true }));
27+
vi.mock("../../state/threads", () => ({
28+
threadEnvironment: { suggestSplit: { permissionAtom: () => true } },
29+
}));
30+
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.suggest }));
31+
vi.mock("../../state/use-composer-drafts", () => ({
32+
createNewTaskDraft: () => "draft-new",
33+
getComposerDraftSnapshot: () => ({ text: "", attachments: [], context: undefined }),
34+
setComposerDraftText: vi.fn(),
35+
updateComposerDraftSettings: vi.fn(),
36+
}));
37+
38+
import { ThreadSplitSuggestion } from "./ThreadSplitSuggestion";
39+
40+
const environmentId = EnvironmentId.make("environment-test");
41+
const threadId = ThreadId.make("thread-test");
42+
const projectId = ProjectId.make("project-test");
43+
44+
function mount(key: string, message: string) {
45+
const container = document.createElement("div");
46+
const root = createRoot(container);
47+
act(() =>
48+
root.render(
49+
<ThreadSplitSuggestion
50+
key={key}
51+
environmentId={environmentId}
52+
threadId={threadId}
53+
projectId={projectId}
54+
draftKey="draft-test"
55+
message={message}
56+
enabled
57+
/>,
58+
),
59+
);
60+
return { container, root };
61+
}
62+
63+
describe("ThreadSplitSuggestion", () => {
64+
it("keeps a dismissed suggestion hidden across remounts until the draft is cleared", async () => {
65+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
66+
vi.useFakeTimers();
67+
try {
68+
state.suggest.mockResolvedValue({ _tag: "Success", value: { suggest: true } });
69+
const first = mount("a", "Write release notes");
70+
await act(async () => {
71+
await vi.advanceTimersByTimeAsync(1000);
72+
});
73+
expect(state.suggest).toHaveBeenCalledTimes(1);
74+
const dismiss = first.container.querySelector("button:last-of-type");
75+
expect(first.container.textContent).toContain("Start a new thread");
76+
act(() => dismiss?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
77+
expect(first.container.textContent).not.toContain("Start a new thread");
78+
act(() => first.root.unmount());
79+
80+
const second = mount("b", "Write release notes");
81+
await act(async () => {
82+
await vi.advanceTimersByTimeAsync(1000);
83+
});
84+
expect(state.suggest).toHaveBeenCalledTimes(1);
85+
expect(second.container.textContent).not.toContain("Start a new thread");
86+
act(() => second.root.unmount());
87+
88+
const cleared = mount("c", "");
89+
await act(async () => {
90+
await vi.advanceTimersByTimeAsync(1000);
91+
});
92+
act(() => cleared.root.unmount());
93+
94+
const fresh = mount("d", "A different draft");
95+
await act(async () => {
96+
await vi.advanceTimersByTimeAsync(1000);
97+
});
98+
expect(state.suggest).toHaveBeenCalledTimes(2);
99+
await act(async () => {
100+
await Promise.resolve();
101+
});
102+
expect(fresh.container.textContent).toContain("Start a new thread");
103+
act(() => fresh.root.unmount());
104+
} finally {
105+
vi.useRealTimers();
106+
}
107+
});
108+
});
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { useEffect, useEffectEvent, useState } from "react";
2+
import { StackActions, useIsFocused, useNavigation } from "@react-navigation/native";
3+
import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
4+
import { View } from "react-native";
5+
import { Button } from "../../components/ui/Button";
6+
import { threadEnvironment } from "../../state/threads";
7+
import { useAtomValue } from "@effect/atom-react";
8+
import { useAtomCommand } from "../../state/use-atom-command";
9+
import {
10+
createNewTaskDraft,
11+
getComposerDraftSnapshot,
12+
setComposerDraftText,
13+
updateComposerDraftSettings,
14+
} from "../../state/use-composer-drafts";
15+
import { scopedThreadKey } from "../../lib/scopedEntities";
16+
17+
const dismissedThreadKeys = new Set<string>();
18+
19+
type ThreadSplitSuggestionProps = {
20+
readonly environmentId: EnvironmentId;
21+
readonly threadId: ThreadId;
22+
readonly projectId: ProjectId;
23+
readonly draftKey: string;
24+
readonly message: string;
25+
readonly enabled: boolean;
26+
};
27+
28+
export function ThreadSplitSuggestion(props: ThreadSplitSuggestionProps) {
29+
const focused = useIsFocused();
30+
const canSuggest = useAtomValue(
31+
threadEnvironment.suggestSplit.permissionAtom(props.environmentId),
32+
);
33+
const threadKey = scopedThreadKey(props.environmentId, props.threadId);
34+
const [dismissed, setDismissed] = useState(() => dismissedThreadKeys.has(threadKey));
35+
const hasMessage = Boolean(props.message.trim());
36+
if (dismissed && !hasMessage) {
37+
dismissedThreadKeys.delete(threadKey);
38+
setDismissed(false);
39+
}
40+
if (!props.enabled || !focused || !canSuggest || !hasMessage || dismissed) return null;
41+
return (
42+
<ActiveThreadSplitSuggestion
43+
key={JSON.stringify([props.environmentId, props.threadId, props.message])}
44+
{...props}
45+
onDismiss={() => {
46+
dismissedThreadKeys.add(threadKey);
47+
setDismissed(true);
48+
}}
49+
/>
50+
);
51+
}
52+
53+
function ActiveThreadSplitSuggestion(
54+
props: ThreadSplitSuggestionProps & { readonly onDismiss: () => void },
55+
) {
56+
const navigation = useNavigation();
57+
const [suggestedMessage, setSuggestedMessage] = useState<string | null>(null);
58+
const suggest = useAtomCommand(threadEnvironment.suggestSplit, {
59+
reportFailure: false,
60+
reportDefect: false,
61+
});
62+
const request = useEffectEvent(suggest);
63+
const { environmentId, threadId, message } = props;
64+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce remote inference and discard responses after the draft or destination changes
65+
useEffect(() => {
66+
let cancelled = false;
67+
const timer = setTimeout(() => {
68+
void request({ environmentId, input: { threadId, message } }).then((result) => {
69+
if (!cancelled)
70+
setSuggestedMessage(result._tag === "Success" && result.value.suggest ? message : null);
71+
});
72+
}, 1_000);
73+
return () => {
74+
cancelled = true;
75+
clearTimeout(timer);
76+
};
77+
}, [environmentId, threadId, message]);
78+
79+
if (suggestedMessage !== message) return null;
80+
81+
return (
82+
<View className="flex-row items-center">
83+
<Button
84+
label="Start a new thread with this message"
85+
tone="text"
86+
onPress={() => {
87+
const draft = getComposerDraftSnapshot(props.draftKey);
88+
if (draft.text !== message || draft.attachments.length > 0 || draft.context) return;
89+
const draftId = createNewTaskDraft({ environmentId, projectId: props.projectId });
90+
setComposerDraftText(draftId, message);
91+
updateComposerDraftSettings(draftId, {
92+
modelSelection: draft.modelSelection,
93+
runtimeMode: draft.runtimeMode,
94+
interactionMode: draft.interactionMode,
95+
workspaceSelection: draft.workspaceSelection,
96+
});
97+
navigation.dispatch(
98+
StackActions.push("Thread", {
99+
draft: { draftId, environmentId, projectId: props.projectId },
100+
}),
101+
);
102+
setComposerDraftText(props.draftKey, "");
103+
}}
104+
/>
105+
<Button label="Dismiss thread suggestion" tone="text" onPress={props.onDismiss} />
106+
</View>
107+
);
108+
}

‎apps/mobile/src/lib/enrichedLinkPresentation.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,4 +149,16 @@ describe("Enriched link presentation", () => {
149149
]);
150150
expect(threadChipTargets(here, "No links here.")).toEqual([]);
151151
});
152+
153+
it("finds thread links with angle-bracketed destinations", () => {
154+
const here = "env-here" as EnvironmentId;
155+
expect(threadChipTargets(here, "See [A](<t3-thread://v2/env-here/thread_a>).")).toEqual([
156+
{
157+
href: "t3-thread://v2/env-here/thread_a",
158+
environmentId: here,
159+
threadId: "thread_a",
160+
link: true,
161+
},
162+
]);
163+
});
152164
});

‎apps/mobile/src/lib/enrichedLinkPresentation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export function threadChipTargets(
6262
): ReadonlyArray<ThreadChipTarget> {
6363
const targets = new Map<string, ThreadChipTarget>();
6464
if (hasThreadLinks(markdown)) {
65-
for (const [, href = ""] of markdown.matchAll(/\]\((t3-thread:\/\/v[12]\/[^\s)]+)\)/g)) {
65+
for (const [, href = ""] of markdown.matchAll(/\]\(<?(t3-thread:\/\/v[12]\/[^\s>)]+)>?\)/g)) {
6666
const link = parseThreadLinkHref(href);
6767
if (link) {
6868
targets.set(href, {

‎apps/mobile/src/state/entities.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useAtomValue } from "@effect/atom-react";
2+
import { useEffect } from "react";
23
import { deriveReportedModelSelection } from "@t3tools/client-runtime/state/thread-execution";
34

45
import { appAtomRegistry } from "./atom-registry";
@@ -34,7 +35,7 @@ import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIco
3435
import { projectFaviconUrlAtom } from "./assets";
3536
import { environmentProjects } from "./projects";
3637
import { environmentServerConfigsAtom, serverEnvironment } from "./server";
37-
import { environmentThreadDetails, environmentThreadShells } from "./threads";
38+
import { environmentThreadDetails, environmentThreadShells, threadFamilies } from "./threads";
3839

3940
const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
4041
Atom.withLabel("mobile-project:empty"),
@@ -208,11 +209,27 @@ export function useSideChats(ref: ScopedThreadRef) {
208209
}
209210

210211
export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
212+
const refs = hasThreadLinks(markdown) ? threadLinkRefs(markdown, environmentId) : [];
211213
const titles = useAtomValue(
212-
hasThreadLinks(markdown)
213-
? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey)))
214-
: EMPTY_THREAD_LINK_TITLES_ATOM,
214+
refs.length === 0
215+
? EMPTY_THREAD_LINK_TITLES_ATOM
216+
: threadLinkTitlesAtom(JSON.stringify(refs.map(threadKey))),
215217
);
218+
// Shells leave out idle subagent children and older settled threads, so a cited thread the
219+
// shell lacks is read with its family until it lands; only a settled empty read proves it gone.
220+
const missingKey = JSON.stringify(
221+
refs.filter((ref) => !titles.has(threadKey(ref))).map(threadKey),
222+
);
223+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts family reads for cited threads the shell omits while this message shows them
224+
useEffect(() => {
225+
const releases = (JSON.parse(missingKey) as ReadonlyArray<string>).map((key) => {
226+
const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
227+
return threadFamilies.mount(appAtomRegistry, ref.environmentId, ref.threadId);
228+
});
229+
return () => {
230+
for (const release of releases) release();
231+
};
232+
}, [missingKey]);
216233
return relabelThreadLinks(markdown, environmentId, (ref) => titles.get(threadKey(ref)));
217234
}
218235

0 commit comments

Comments
 (0)