The best way to control Claude Code, Codex and more from any computer or phone
fix(web,mobile): triage follows the draft when you switch machines (#33782)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Ilkka Lappeteläinen committed
Nov 13, 2026 at 05:30 UTC
d7a0b5371fda4e5a3e4c02c3e6eceec3c594b5eb
11 files changed
+287
-33
apps/mobile/src/features/threads/new-task-flow-provider.test.tsx
+82
-2
@@ -4,6 +4,7 @@ import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
4
import { createEnvironmentSubscriptionAtomFamily } from "@t3tools/client-runtime/state/runtime";
5
import {
6
AuthFilesystemReadScope,
7
+ DEFAULT_SERVER_SETTINGS,
8
EnvironmentId,
9
ProjectId,
10
type VcsListRefsResult,
@@ -32,6 +33,9 @@ const mocks = vi.hoisted(() => ({
33
retargetDraft: vi.fn(),
34
writeSettings: vi.fn(),
35
writeText: vi.fn(),
36
+ serverConfig: vi.fn(),
37
+ openScratch: vi.fn(),
38
+ prepareTriage: vi.fn(),
39
}));
40
vi.mock("../../state/atom-registry", () => ({
41
appAtomRegistry: {
@@ -43,7 +47,7 @@ vi.mock("../../state/atom-registry", () => ({
47
vi.mock("../../state/entities", () => ({
48
useProjects: mocks.projects,
49
useThreadShells: () => [],
46
- useEnvironmentServerConfig: () => null,
50
+ useEnvironmentServerConfig: () => mocks.serverConfig() ?? null,
51
useServerConfigs: () => new Map(),
52
}));
53
vi.mock("../../state/vcs", () => ({
@@ -66,7 +70,8 @@ vi.mock("../../state/project-grouping", () => ({
70
useMobileProjectGroupingSettings: () => ({ sidebarProjectGroupingMode: "none" }),
71
}));
72
vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
69
-vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
73
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.openScratch }));
74
+vi.mock("../triage/usePrepareTriage", () => ({ usePrepareTriage: () => mocks.prepareTriage }));
75
vi.mock("../../state/use-remote-environment-registry", () => ({
76
useSavedRemoteConnections: () => ({ savedConnectionsById: {} }),
77
useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }),
@@ -362,3 +367,78 @@ it("uses cached repository capability and branch defaults while offline", async
367
expect(screen.current.draftKey).toBe(draftKey);
368
expect(screen.current.selectedBranchName).toBe("main");
369
});
370
+
371
+const playbookPrompt = (machine: string) =>
372
+ `Read [triage-playbook.md](/${machine}/triage-playbook.md) and follow it. `;
373
+
374
+/** A triage draft on machine one's No project home; machine two opens its own. */
375
+async function renderTriageDraft(screen: ReturnType<typeof setup>) {
376
+ mocks.serverConfig.mockReturnValue({
377
+ scratchWorkspaceRoot: "/a",
378
+ providers: [],
379
+ settings: DEFAULT_SERVER_SETTINGS,
380
+ });
381
+ mocks.openScratch.mockResolvedValue({ _tag: "Success", value: screen.projects[2] });
382
+ await screen.render(true);
383
+ act(() => screen.current.setPrompt(`${playbookPrompt("one")}It is slow.`));
384
+}
385
+
386
+it("takes a triage draft's session along when its machine changes", async () => {
387
+ using screen = setup();
388
+ await renderTriageDraft(screen);
389
+ mocks.prepareTriage.mockResolvedValue({
390
+ _tag: "Success",
391
+ value: { prompt: playbookPrompt("two") },
392
+ });
393
+
394
+ await act(async () => {
395
+ await screen.current.switchEnvironment(EnvironmentId.make("two"));
396
+ });
397
+
398
+ expect(screen.current.prompt).toBe(`${playbookPrompt("two")}It is slow.`);
399
+ expect(screen.current.selectedProject).toEqual(screen.projects[2]);
400
+});
401
+
402
+it.each([
403
+ [
404
+ "a project is picked",
405
+ 1,
406
+ (flow: ReturnType<typeof useNewTaskFlow>, picked: EnvironmentProject) =>
407
+ flow.setProject(picked),
408
+ ],
409
+ [
410
+ "a send starts and ends",
411
+ 0,
412
+ (flow: ReturnType<typeof useNewTaskFlow>) => {
413
+ flow.setSubmitting(true);
414
+ flow.setSubmitting(false);
415
+ },
416
+ ],
417
+] as const)(
418
+ "leaves a triage draft alone when %s while its new machine prepares",
419
+ async (_name, expectedProject, interrupt) => {
420
+ using screen = setup();
421
+ await renderTriageDraft(screen);
422
+ let finishPreparing!: (result: unknown) => void;
423
+ mocks.prepareTriage.mockReturnValue(
424
+ new Promise((resolve) => {
425
+ finishPreparing = resolve;
426
+ }),
427
+ );
428
+
429
+ let switching!: Promise<boolean>;
430
+ act(() => {
431
+ switching = screen.current.switchEnvironment(EnvironmentId.make("two"));
432
+ });
433
+ await act(async () => interrupt(screen.current, screen.projects[1]!));
434
+ let switched = true;
435
+ await act(async () => {
436
+ finishPreparing({ _tag: "Success", value: { prompt: playbookPrompt("two") } });
437
+ switched = await switching;
438
+ });
439
+
440
+ expect(switched).toBe(false);
441
+ expect(screen.current.prompt).toBe(`${playbookPrompt("one")}It is slow.`);
442
+ expect(screen.current.selectedProject).toEqual(screen.projects[expectedProject]);
443
+ },
444
+);
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+31
-3
@@ -19,6 +19,7 @@ import {
19
ThreadId,
20
} from "@t3tools/contracts";
21
import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
22
+import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt";
23
import * as Arr from "effect/Array";
24
import { pipe } from "effect/Function";
25
@@ -102,6 +103,7 @@ import {
103
stampedEnvironmentProjectsLoading,
104
updateNewTaskFlowState,
105
} from "./new-task-flow-state";
106
+import { usePrepareTriage } from "../triage/usePrepareTriage";
107
import { useEnvironmentShellReadiness } from "../../state/shell";
108
import { useConnectionsReady, useWorkspaceEnvironments } from "../../state/workspace";
109
@@ -589,6 +591,7 @@ export function NewTaskFlowProvider(
591
};
592
593
const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
594
+ const prepareTriage = usePrepareTriage();
595
const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
596
null,
597
);
@@ -606,11 +609,27 @@ export function NewTaskFlowProvider(
609
const request = {};
610
latestSwitchRef.current = request;
611
setSwitchingToEnvironmentId(environmentId);
609
- const result = await openScratch({ environmentId, input: {} });
612
+ // A triage draft takes its session along: the playbook and context files
613
+ // exist only on the machine that prepared them.
614
+ const { draftKey, projectKey } = readFlow();
615
+ const triage =
616
+ draftKey !== null && isTriagePrompt(getComposerDraftSnapshot(draftKey).text)
617
+ ? await prepareTriage(environmentId)
618
+ : null;
619
+ const result =
620
+ triage?._tag === "Failure" ? triage : await openScratch({ environmentId, input: {} });
621
if (latestSwitchRef.current !== request) return false;
622
latestSwitchRef.current = null;
623
setSwitchingToEnvironmentId(null);
624
+ // A project picked while this waited stands.
625
+ if (readFlow().projectKey !== projectKey) return false;
626
if (result._tag === "Success") {
627
+ if (triage?._tag === "Success" && draftKey !== null && readFlow().draftKey === draftKey) {
628
+ // Read now, so text typed while the machine prepared the session is kept.
629
+ const text = getComposerDraftSnapshot(draftKey).text;
630
+ const nextText = replaceTriagePlaybookLink(text, triage.value.prompt);
631
+ if (nextText !== text) setComposerDraftText(draftKey, nextText);
632
+ }
633
setProject(result.value);
634
return true;
635
}
@@ -620,7 +639,9 @@ export function NewTaskFlowProvider(
639
"Could not switch machine",
640
error instanceof Error
641
? error.message
623
- : "The folder for threads without a project could not be created.",
642
+ : triage?._tag === "Failure"
643
+ ? "The server could not prepare triage."
644
+ : "The folder for threads without a project could not be created.",
645
);
646
}
647
return false;
@@ -884,7 +905,14 @@ export function NewTaskFlowProvider(
905
appendAttachments,
906
removeAttachment,
907
clearAttachments,
887
- setSubmitting: (value: boolean) => updateFlow({ submitting: value }),
908
+ setSubmitting: (value: boolean) => {
909
+ // A send takes the draft as it is, so a machine switch still waiting is dropped.
910
+ if (value) {
911
+ latestSwitchRef.current = null;
912
+ setSwitchingToEnvironmentId(null);
913
+ }
914
+ updateFlow({ submitting: value });
915
+ },
916
loadBranches,
917
setRuntimeMode,
918
setSelectedModelOptions,
apps/mobile/src/features/triage/usePrepareTriage.ts
new
+19
@@ -0,0 +1,19 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import Constants from "expo-constants";
3
+
4
+import { authClientMetadata } from "../../lib/authClientMetadata";
5
+import { serverEnvironment } from "../../state/server";
6
+import { useAtomCommand } from "../../state/use-atom-command";
7
+
8
+/**
9
+ * Asks a machine to prepare a triage session. The result carries the prompt
10
+ * that links its playbook; the caller reports a failure.
11
+ */
12
+export function usePrepareTriage() {
13
+ const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
14
+ return (environmentId: EnvironmentId) =>
15
+ prepare({
16
+ environmentId,
17
+ input: { client: authClientMetadata(Constants.expoConfig?.version) },
18
+ });
19
+}
apps/mobile/src/features/triage/useStartTriage.ts
+3
-8
@@ -6,12 +6,9 @@ import {
6
import type { EnvironmentId } from "@t3tools/contracts";
7
import { useNavigation } from "@react-navigation/native";
8
import * as Clipboard from "expo-clipboard";
9
-import Constants from "expo-constants";
9
10
import * as Dialog from "../../components/ui/Dialog";
12
-import { authClientMetadata } from "../../lib/authClientMetadata";
11
import { projectEnvironment } from "../../state/projects";
14
-import { serverEnvironment } from "../../state/server";
12
import { useAtomCommand } from "../../state/use-atom-command";
13
import {
14
createNewTaskDraft,
@@ -19,6 +16,7 @@ import {
16
waitForComposerDraftsLoaded,
17
} from "../../state/use-composer-drafts";
18
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
19
+import { usePrepareTriage } from "./usePrepareTriage";
20
21
const CLI_COMMAND = "npx t3 triage";
22
@@ -29,7 +27,7 @@ const CLI_COMMAND = "npx t3 triage";
27
export function useStartTriage() {
28
const navigation = useNavigation();
29
const selectDetail = useSelectWorkspaceDetail();
32
- const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
30
+ const prepare = usePrepareTriage();
31
const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
32
33
const fail = (message: string) =>
@@ -77,10 +75,7 @@ export function useStartTriage() {
75
}
76
return;
77
}
80
- const prepared = await prepare({
81
- environmentId,
82
- input: { client: authClientMetadata(Constants.expoConfig?.version) },
83
- });
78
+ const prepared = await prepare(environmentId);
79
if (prepared._tag === "Failure") {
80
if (!isAtomCommandInterrupted(prepared)) {
81
pipe(
apps/web/src/components/chat/DraftHeroHeadline.tsx
+1
-1
@@ -14,7 +14,7 @@ import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
14
import { useOrderWhileOpen } from "~/hooks/useOrderWhileOpen";
15
import { useProjectPin } from "~/hooks/useProjectGroupUpdate";
16
import { useScratchProject } from "~/hooks/useScratchProject";
17
-import { isTriagePrompt } from "~/hooks/useStartTriage";
17
+import { isTriagePrompt } from "@t3tools/shared/triagePrompt";
18
import { useClientSettings } from "~/hooks/useSettings";
19
import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
20
import {
apps/web/src/components/chat/useDraftEnvironmentRouting.ts
+57
-14
@@ -14,16 +14,24 @@ import {
14
scopeProjectRef,
15
scopeThreadRef,
16
} from "@t3tools/client-runtime/environment";
17
+import {
18
+ isAtomCommandInterrupted,
19
+ squashAtomCommandFailure,
20
+} from "@t3tools/client-runtime/state/runtime";
21
+import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt";
22
import { useEffect, useLayoutEffect, useRef, useState } from "react";
23
import { flushSync } from "react-dom";
19
-import { toastManager } from "../ui/toast";
24
+import { stackedThreadToast, toastManager } from "../ui/toast";
25
import {
26
deriveLogicalProjectKeyFromSettings,
27
selectProjectGroupingSettings,
28
} from "@t3tools/client-runtime/state/project-grouping";
29
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
30
import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
31
+import { currentClientMetadata } from "../../connection/platform";
32
import { useProjects } from "../../state/entities";
33
+import { serverEnvironment } from "../../state/server";
34
+import { useAtomCommand } from "../../state/use-atom-command";
35
import type { DraftSessionState } from "../../composerDraftStore";
36
import { loadBalancingSendWarning } from "./composerSend.logic";
37
import { appAtomRegistry } from "../../rpc/atomRegistry";
@@ -53,7 +61,8 @@ interface DraftEnvironmentRoutingInput {
61
/**
62
* Which machine an unsent draft runs on: automatic load balancing across the
63
* project's machines, or a manual switch, which may first open a scratch
56
- * project on the target machine.
64
+ * project on the target machine. A triage draft takes its session along: the
65
+ * target machine prepares one, and the playbook link follows.
66
*/
67
export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) {
68
const {
@@ -76,6 +85,9 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
85
} = input;
86
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
87
const getDraftSession = useComposerDraftStore((store) => store.getDraftSession);
88
+ const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
89
+ const setPrompt = useComposerDraftStore((store) => store.setPrompt);
90
+ const prepareTriage = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
91
const setLogicalProjectDraftThreadId = useComposerDraftStore(
92
(store) => store.setLogicalProjectDraftThreadId,
93
);
@@ -284,7 +296,8 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
296
const request = { environmentId: target.environmentId, scope: environmentChangeScope };
297
environmentChangeRef.current = request;
298
setBusyEnvironmentChange(null);
287
- const retarget = (project: (typeof allProjects)[number]) => {
299
+ // `triagePrompt` is the prompt the target machine prepared for a triage draft.
300
+ const retarget = (project: (typeof allProjects)[number], triagePrompt?: string) => {
301
const currentDraft = getDraftSession(draftId);
302
if (
303
environmentChangeRef.current !== request ||
@@ -296,6 +309,12 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
309
currentDraft.projectId !== originalDraft.projectId
310
)
311
return;
312
+ if (triagePrompt !== undefined) {
313
+ // Read now, so text typed while the machine prepared the session is kept.
314
+ const prompt = getComposerDraft(draftId)?.prompt ?? "";
315
+ const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
316
+ if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
317
+ }
318
const projectRef = scopeProjectRef(target.environmentId, project.id);
319
if (activeProjectIsScratch) {
320
setLogicalProjectDraftThreadId(
@@ -316,21 +335,45 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
335
if (environmentChangeRef.current === request) environmentChangeRef.current = null;
336
setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
337
};
319
- if (target.projectId !== null) {
320
- const project = allProjects.find(
321
- (project) =>
322
- project.environmentId === target.environmentId && project.id === target.projectId,
323
- );
324
- if (project) retarget(project);
338
+ const knownProject = allProjects.find(
339
+ (project) =>
340
+ project.environmentId === target.environmentId && project.id === target.projectId,
341
+ );
342
+ // The playbook and context files exist only on the machine that prepared them.
343
+ const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? "");
344
+ if (target.projectId !== null && !(knownProject && followsTriage)) {
345
+ if (knownProject) retarget(knownProject);
346
finish();
347
return;
348
}
349
+ const prepareTriagePrompt = async () => {
350
+ const prepared = await prepareTriage({
351
+ environmentId: target.environmentId,
352
+ input: { client: currentClientMetadata() },
353
+ });
354
+ if (prepared._tag === "Success") return prepared.value.prompt;
355
+ if (!isAtomCommandInterrupted(prepared)) {
356
+ const error = squashAtomCommandFailure(prepared);
357
+ toastManager.add(
358
+ stackedThreadToast({
359
+ type: "error",
360
+ title: "Could not switch machine",
361
+ description: error instanceof Error ? error.message : "An error occurred.",
362
+ }),
363
+ );
364
+ }
365
+ return null;
366
+ };
367
+ const switchMachine = async () => {
368
+ const triagePrompt = followsTriage ? await prepareTriagePrompt() : undefined;
369
+ if (triagePrompt === null) return;
370
+ const project =
371
+ knownProject ??
372
+ (await openScratchProject(target.environmentId, "Could not switch machine"));
373
+ if (project) retarget(project, triagePrompt);
374
+ };
375
setBusyEnvironmentChange(request);
329
- void openScratchProject(target.environmentId, "Could not switch machine")
330
- .then((project) => {
331
- if (project) retarget(project);
332
- })
333
- .finally(finish);
376
+ void switchMachine().finally(finish);
377
};
378
const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
379
apps/web/src/hooks/useStartTriage.ts
+1
-4
@@ -4,7 +4,7 @@ import {
4
isAtomCommandInterrupted,
5
squashAtomCommandFailure,
6
} from "@t3tools/client-runtime/state/runtime";
7
-import { type EnvironmentId, TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
7
+import type { EnvironmentId } from "@t3tools/contracts";
8
import { useRouter } from "@tanstack/react-router";
9
10
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
@@ -26,9 +26,6 @@ const copyTriageCliCommand = () =>
26
}),
27
);
28
29
-/** A draft is a triage draft while its message still links the playbook file. */
30
-export const isTriagePrompt = (prompt: string) => prompt.includes(`[${TRIAGE_PROMPT_FILE_NAME}](`);
31
-
29
/**
30
* In-app `t3 triage`: the server writes the session files and starts cloning
31
* the matching source, then a No project draft opens with the playbook linked.
docs/user/triage.md
+2
-1
@@ -15,7 +15,8 @@ source for the server's version while you write.
15
Triage runs on the machine of the thread or draft that you have open. With
16
nothing open, it uses your primary machine if that supports triage, or else the
17
first connected machine that does. The new thread shows the machine name, and on
18
-mobile the palette row shows it before you start. The agent runs inside that T3
18
+mobile the palette row shows it before you start. If you change the machine
19
+before you send, triage moves to that machine. The agent runs inside that T3
20
Code server, so it gives you any restart steps and does not do them itself.
21
22
## In a terminal
packages/shared/package.json
+4
@@ -267,6 +267,10 @@
267
"types": "./src/composerTrigger.ts",
268
"import": "./src/composerTrigger.ts"
269
},
270
+ "./triagePrompt": {
271
+ "types": "./src/triagePrompt.ts",
272
+ "import": "./src/triagePrompt.ts"
273
+ },
274
"./pullRequestComposerTrigger": {
275
"types": "./src/pullRequestComposerTrigger.ts",
276
"import": "./src/pullRequestComposerTrigger.ts"
packages/shared/src/triagePrompt.test.ts
new
+54
@@ -0,0 +1,54 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { serializeComposerFileLink } from "./composerTrigger.ts";
4
+import { isTriagePrompt, replaceTriagePlaybookLink } from "./triagePrompt.ts";
5
+
6
+const appPrompt = (playbookPath: string) =>
7
+ `Read ${serializeComposerFileLink(playbookPath)} and follow it. `;
8
+
9
+const MACHINE_A = "/Users/a/.t3/triage/1/triage-playbook.md";
10
+const MACHINE_B = "/home/b/.t3/triage/2/triage-playbook.md";
11
+
12
+describe("replaceTriagePlaybookLink", () => {
13
+ it("replaces only the playbook link and keeps the text the user typed", () => {
14
+ const other = serializeComposerFileLink("/Users/a/notes (old)/log.md");
15
+ const prompt = `Before. ${appPrompt(MACHINE_A)}The app crashes, see ${other} (twice).`;
16
+
17
+ expect(replaceTriagePlaybookLink(prompt, appPrompt(MACHINE_B))).toBe(
18
+ `Before. ${appPrompt(MACHINE_B)}The app crashes, see ${other} (twice).`,
19
+ );
20
+ });
21
+
22
+ it.each([
23
+ ["spaces", "/Users/a b/My Data/triage-playbook.md"],
24
+ ["parentheses", "/Users/a/t3 (dev)/triage-playbook.md"],
25
+ ["hash and question mark", "/Users/a/#1/what?/triage-playbook.md"],
26
+ ["a Windows path", "C:\\Users\\a b\\t3 (dev)\\triage-playbook.md"],
27
+ ])("replaces a link whose path has %s", (_name, path) => {
28
+ expect(replaceTriagePlaybookLink(`${appPrompt(path)}It is slow.`, appPrompt(MACHINE_B))).toBe(
29
+ `${appPrompt(MACHINE_B)}It is slow.`,
30
+ );
31
+ expect(replaceTriagePlaybookLink(`${appPrompt(MACHINE_A)}It is slow.`, appPrompt(path))).toBe(
32
+ `${appPrompt(path)}It is slow.`,
33
+ );
34
+ });
35
+
36
+ it("replaces a link at the end of the prompt", () => {
37
+ const link = serializeComposerFileLink(MACHINE_A);
38
+ expect(replaceTriagePlaybookLink(`Follow ${link}`, appPrompt(MACHINE_B))).toBe(
39
+ `Follow ${serializeComposerFileLink(MACHINE_B)}`,
40
+ );
41
+ });
42
+
43
+ it("returns the prompt unchanged when it has no playbook link", () => {
44
+ const prompt = `The app crashes, see ${serializeComposerFileLink("/Users/a/log.md")} please.`;
45
+ expect(isTriagePrompt(prompt)).toBe(false);
46
+ expect(replaceTriagePlaybookLink(prompt, appPrompt(MACHINE_B))).toBe(prompt);
47
+ });
48
+
49
+ it("returns the prompt unchanged when the prepared prompt has no playbook link", () => {
50
+ expect(replaceTriagePlaybookLink(appPrompt(MACHINE_A), "Read the playbook.")).toBe(
51
+ appPrompt(MACHINE_A),
52
+ );
53
+ });
54
+});
packages/shared/src/triagePrompt.ts
new
+33
@@ -0,0 +1,33 @@
1
+import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
2
+
3
+const PLAYBOOK_LINK_START = `[${TRIAGE_PROMPT_FILE_NAME}](`;
4
+
5
+/** A draft is a triage draft while its message still links the playbook file. */
6
+export const isTriagePrompt = (prompt: string) => prompt.includes(PLAYBOOK_LINK_START);
7
+
8
+// `serializeComposerFileLink` encodes `)` and whitespace, so the first `)` closes the link.
9
+const playbookLinkEnd = (text: string, start: number) => {
10
+ const close = text.indexOf(")", start + PLAYBOOK_LINK_START.length);
11
+ return close === -1 ? null : close + 1;
12
+};
13
+
14
+/**
15
+ * Moves a triage draft to the session another machine prepared: each playbook
16
+ * link in `prompt` becomes the link in `preparedPrompt`, and the rest of the
17
+ * text stays. A prompt without the link comes back unchanged.
18
+ */
19
+export function replaceTriagePlaybookLink(prompt: string, preparedPrompt: string): string {
20
+ const preparedStart = preparedPrompt.indexOf(PLAYBOOK_LINK_START);
21
+ const preparedEnd = preparedStart === -1 ? null : playbookLinkEnd(preparedPrompt, preparedStart);
22
+ if (preparedEnd === null) return prompt;
23
+ const link = preparedPrompt.slice(preparedStart, preparedEnd);
24
+ let next = "";
25
+ let cursor = 0;
26
+ while (true) {
27
+ const start = prompt.indexOf(PLAYBOOK_LINK_START, cursor);
28
+ const end = start === -1 ? null : playbookLinkEnd(prompt, start);
29
+ if (end === null) return next + prompt.slice(cursor);
30
+ next += prompt.slice(cursor, start) + link;
31
+ cursor = end;
32
+ }
33
+}