Skip to content

Commit 30797a7

Browse files
voltcrashclaude
andcommitted
feat(threads): choose a checkout when forking a response
Rework fork destinations for the current launch service, MCP transfer tool, retained chat overlays, and mobile workspace navigation. Gate sends and side chats until fork setup is ready, while preserving async setup and replay. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5fe18d7 commit 30797a7

36 files changed

Lines changed: 1489 additions & 95 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,7 @@ export function NewTaskDraftScreen(props: {
897897
return (
898898
<>
899899
<ThreadScreenBinding
900+
isGitRepo={flow.isGitRepo}
900901
environmentId={selectedProject.environmentId}
901902
header={
902903
<DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ export interface ThreadDetailScreenProps {
263263
readonly environmentId: EnvironmentId;
264264
readonly projectWorkspaceRoot: string | null;
265265
readonly threadCwd: string | null;
266+
readonly isGitRepo: boolean;
266267
readonly selectedThreadQueueCount: number;
267268
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
268269
readonly dispatchingMessageId: MessageId | null;
@@ -1382,6 +1383,7 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
13821383
threadId={props.selectedThread.id}
13831384
detailRef={props.selectedThreadDetailRef}
13841385
workspaceRoot={props.threadCwd}
1386+
isGitRepo={props.isGitRepo}
13851387
feed={props.selectedThreadFeed}
13861388
pendingHandoff={props.pendingHandoff}
13871389
worktreeSetup={props.worktreeSetup}

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

Lines changed: 94 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,13 @@ import {
3636
resolveUserMessageFileCards,
3737
resolveUserMessagePresentation,
3838
} from "@t3tools/client-runtime/user-message";
39-
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
39+
import {
40+
canForkProjectedAssistantItem,
41+
threadForkWorkspaceChoices,
42+
} from "@t3tools/client-runtime/state/thread-workflows";
4043
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
4144
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
45+
import { forkWorkspacePreparingAtom } from "@t3tools/client-runtime/worktree-setup";
4246
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
4347
import {
4448
AuthFilesystemReadScope,
@@ -51,6 +55,7 @@ import {
5155
type EnvironmentId,
5256
type MessageId,
5357
type OrchestrationV2ProjectedTurnItem,
58+
type OrchestrationV2ThreadLaunchWorkspaceStrategy,
5459
type RunId,
5560
type ScheduledTaskId,
5661
type ScopedThreadRef,
@@ -347,6 +352,7 @@ export interface ThreadFeedProps {
347352
readonly detailRef: ScopedThreadRef | null;
348353
readonly threadTitle: string;
349354
readonly workspaceRoot?: string | null;
355+
readonly isGitRepo?: boolean;
350356
readonly feed: ReadonlyArray<ThreadFeedEntry>;
351357
readonly pendingHandoff?: HandoffEndpoints | null;
352358
readonly contentPresentation: ThreadContentPresentation;
@@ -420,6 +426,8 @@ function UserMessageCopyButton(props: {
420426

421427
function AssistantForkButton(props: {
422428
readonly environmentId: EnvironmentId;
429+
readonly threadId: ThreadId;
430+
readonly isGitRepo: boolean;
423431
readonly iconColor: ColorValue;
424432
readonly buttonSize: number;
425433
readonly iconSize: number;
@@ -433,6 +441,7 @@ function AssistantForkButton(props: {
433441
});
434442
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
435443
const selectDetail = useSelectWorkspaceDetail();
444+
const navigation = useNavigation();
436445
const [busy, setBusy] = useState(false);
437446
const canFork = canForkProjectedAssistantItem({
438447
projectedItem: props.projectedItem,
@@ -442,41 +451,93 @@ function AssistantForkButton(props: {
442451

443452
if (!canFork || runId === null) return null;
444453

454+
const fork = async (workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy) => {
455+
const targetThreadId = ThreadId.make(uuidv4());
456+
const preparingAtom = forkWorkspacePreparingAtom(
457+
scopedThreadKey(props.environmentId, targetThreadId),
458+
);
459+
const preparesWorktree = workspaceStrategy.type === "worktree";
460+
const stillShowing = (threadId: ThreadId) => {
461+
const state = navigation.getState();
462+
const route = state?.routes[state.index];
463+
const params = route?.params;
464+
return (
465+
route?.name === "Thread" && params && "threadId" in params && params.threadId === threadId
466+
);
467+
};
468+
const openFork = () =>
469+
selectDetail({
470+
name: "Thread",
471+
params: { environmentId: props.environmentId, threadId: targetThreadId },
472+
});
473+
if (preparesWorktree) appAtomRegistry.set(preparingAtom, true);
474+
const pendingResult = forkFromRun({
475+
environmentId: props.environmentId,
476+
input: {
477+
sourceThreadId: props.projectedItem.sourceThreadId,
478+
targetThreadId,
479+
runId,
480+
title: `${props.sourceTitle} fork`,
481+
creationSource: "mobile",
482+
workspaceStrategy,
483+
},
484+
}).finally(() => appAtomRegistry.set(preparingAtom, false));
485+
// The request settles once a new worktree is ready. Open the fork as soon as
486+
// its thread exists so it shows setup progress meanwhile.
487+
const openedEarly =
488+
preparesWorktree &&
489+
(await Promise.race([
490+
waitForThreadShell(props.environmentId, targetThreadId),
491+
pendingResult.then(() => false),
492+
]));
493+
const navigatedEarly = openedEarly && stillShowing(props.threadId);
494+
if (navigatedEarly) openFork();
495+
const result = await pendingResult;
496+
if (result._tag !== "Success") {
497+
if (navigatedEarly && stillShowing(targetThreadId))
498+
selectDetail({
499+
name: "Thread",
500+
params: { environmentId: props.environmentId, threadId: props.threadId },
501+
});
502+
return;
503+
}
504+
if (navigatedEarly || !stillShowing(props.threadId)) return;
505+
const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
506+
if (!stillShowing(props.threadId)) return;
507+
if (!targetThreadReady) {
508+
Dialog.alert(
509+
"Fork created",
510+
"Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
511+
);
512+
return;
513+
}
514+
openFork();
515+
};
516+
445517
return (
446518
<Pressable
447519
accessibilityRole="button"
448520
accessibilityLabel="Fork from this response"
449521
disabled={busy}
450522
onPress={() => {
451-
const targetThreadId = ThreadId.make(uuidv4());
452-
setBusy(true);
523+
const thread = appAtomRegistry.get(
524+
environmentThreadShells.threadShellAtom(
525+
scopeThreadRef(props.environmentId, props.threadId),
526+
),
527+
);
528+
if (!thread) return;
453529
void Haptics.selectionAsync();
454-
void forkFromRun({
455-
environmentId: props.environmentId,
456-
input: {
457-
sourceThreadId: props.projectedItem.sourceThreadId,
458-
targetThreadId,
459-
runId,
460-
title: `${props.sourceTitle} fork`,
461-
creationSource: "mobile",
462-
},
463-
})
464-
.then(async (result) => {
465-
if (result._tag !== "Success") return;
466-
const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
467-
if (!targetThreadReady) {
468-
Dialog.alert(
469-
"Fork created",
470-
"Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
471-
);
472-
return;
473-
}
474-
selectDetail({
475-
name: "Thread",
476-
params: { environmentId: props.environmentId, threadId: targetThreadId },
477-
});
478-
})
479-
.finally(() => setBusy(false));
530+
const choices = threadForkWorkspaceChoices({ ...thread, isGitRepo: props.isGitRepo });
531+
Dialog.alert("Fork thread from here", "Choose where to continue from this response.", [
532+
...choices.map((choice) => ({
533+
text: choice.label,
534+
onPress: () => {
535+
setBusy(true);
536+
void fork(choice.workspaceStrategy).finally(() => setBusy(false));
537+
},
538+
})),
539+
{ text: "Cancel", style: "cancel" },
540+
]);
480541
}}
481542
className="h-7 w-7 items-center justify-center disabled:opacity-40"
482543
style={
@@ -1584,6 +1645,7 @@ function renderFeedEntry(
15841645
| "onEditPendingMessage"
15851646
| "threadId"
15861647
| "workspaceRoot"
1648+
| "isGitRepo"
15871649
> & {
15881650
readonly copiedRowId: string | null;
15891651
readonly expandedWorkRows: Record<string, boolean>;
@@ -2210,6 +2272,8 @@ function renderFeedEntry(
22102272
{message.projectedItem ? (
22112273
<AssistantForkButton
22122274
environmentId={props.environmentId}
2275+
threadId={props.threadId}
2276+
isGitRepo={props.isGitRepo ?? false}
22132277
iconColor={iconSubtleColor}
22142278
buttonSize={props.replyActionSize.button}
22152279
iconSize={props.replyActionSize.icon}
@@ -3554,6 +3618,7 @@ export const ThreadFeed = memo(function ThreadFeed({
35543618
threadTitle: props.threadTitle,
35553619
skills: props.skills,
35563620
workspaceRoot: props.workspaceRoot,
3621+
isGitRepo: props.isGitRepo,
35573622
workflowOpening,
35583623
})}
35593624
{props.worktreeSetup && info.index === setupAnchorIndex ? (

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
import { useAtomValue } from "@effect/atom-react";
12
import * as Dialog from "../../components/ui/Dialog";
23
import { useRememberThreadProject } from "./useRememberThreadProject";
34
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
45
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
56
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
67
import { useWorktreeSetup } from "./use-worktree-setup";
7-
import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
8+
import {
9+
forkWorkspacePreparingAtom,
10+
worktreeSetupReadyForMessages,
11+
} from "@t3tools/client-runtime/worktree-setup";
812
import { AppBar } from "../../components/ui/AppBar";
913
import {
1014
StackActions,
@@ -846,10 +850,16 @@ function ThreadRouteContent(
846850
);
847851
};
848852
const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
853+
const forkWorkspacePreparing = useAtomValue(
854+
forkWorkspacePreparingAtom(
855+
selectedThread ? scopedThreadKey(selectedThread.environmentId, selectedThread.id) : "",
856+
),
857+
);
849858
const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
850859
environmentId: selectedThread?.environmentId ?? null,
851860
threadId: selectedThread?.id ?? null,
852861
preparing:
862+
forkWorkspacePreparing ||
853863
composer.selectedThreadActivityRun?.status === "preparing" ||
854864
selectedThread?.runtime?.status === "preparing" ||
855865
selectedThread?.worktreePath != null ||
@@ -865,8 +875,9 @@ function ThreadRouteContent(
865875
});
866876
const awaitingBootstrapTurn =
867877
worktreeSetup !== null
868-
? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
869-
: (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
878+
? worktreeSetup.phase === "running" && !worktreeSetupReadyForMessages(worktreeSetup)
879+
: forkWorkspacePreparing ||
880+
(selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
870881
const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
871882
const handleCancelWorktreeSetup = () => {
872883
if (!selectedThread) return;
@@ -1053,6 +1064,7 @@ function ThreadRouteContent(
10531064
environmentId={selectedThread.environmentId}
10541065
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
10551066
threadCwd={selectedThreadCwd}
1067+
isGitRepo={gitStatus.data?.isRepo === true}
10561068
selectedThreadQueueCount={composer.selectedThreadQueueCount}
10571069
queuedMessages={
10581070
selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"

‎apps/mobile/src/features/threads/worktree-setup-state.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,17 @@ const running: WorktreeSetupSnapshot = {
1414
baseRef: "main",
1515
worktreePath: null,
1616
setupScript: null,
17-
stages: [],
17+
stages: [
18+
{
19+
id: "agent",
20+
status: "pending",
21+
startedAt: null,
22+
endedAt: null,
23+
percent: null,
24+
detail: null,
25+
tail: [],
26+
},
27+
],
1828
error: null,
1929
};
2030

@@ -40,6 +50,15 @@ describe("mobile worktree setup handoff", () => {
4050
}),
4151
).toBeNull();
4252
expect(resolveWorktreeSetupSnapshot(threadId, undefined, held)).toBe(done);
53+
const idleFork = { ...done, stages: [] };
54+
expect(
55+
resolveVisibleWorktreeSetup({
56+
live: idleFork,
57+
recorded: null,
58+
turnStarted: false,
59+
followUpSent: false,
60+
}),
61+
).toBeNull();
4362
});
4463

4564
it.each(["failed", "cancelled"] as const)(

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
224224
expect(second.capabilities.threadPullRequestLinking).toBe(true);
225225
expect(second.capabilities.serverResolvedCommandContext).toBe(true);
226226
expect(second.capabilities.projectProviderInstanceOverrides).toBe(true);
227+
expect(second.capabilities.threadForkWorkspaceSelection).toBe(true);
227228
expect(second.capabilities.agentActivityPublishing).toBe(false);
228229
}),
229230
);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ export const make = Effect.gen(function* () {
262262
serverResolvedCommandContext: true,
263263
threadStop: true,
264264
...(hostPlatform === "win32" ? {} : { localServerStop: true }),
265+
threadForkWorkspaceSelection: true,
265266
environmentIcon: true,
266267
projectCloneTracking: true,
267268
projectOrganization: true,

‎apps/server/src/mcp/toolkits/core.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput);
7474
const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult);
7575

7676
const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
77+
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
7778
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
7879
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
7980
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),

‎apps/server/src/mcp/toolkits/thread/handlers.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
readThread,
2020
unavailable,
2121
} from "../../threadAccess.ts";
22+
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
2223
import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
2324
import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
2425
import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
@@ -175,19 +176,30 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
175176
return { sequence: result.sequence, targetThreadId };
176177
}
177178
const targetThreadId = ThreadId.make(`${commandId}:fork`);
178-
const result = yield* threads
179-
.dispatch({
180-
type: "thread.fork",
179+
const launches = yield* ThreadLaunch.ThreadLaunchService;
180+
return yield* launches
181+
.fork({
181182
commandId,
182183
sourceThreadId: projection.thread.id,
183184
targetThreadId,
184185
sourcePoint,
186+
...(input.workspaceStrategy === undefined
187+
? {}
188+
: { workspaceStrategy: input.workspaceStrategy }),
185189
...(input.title === undefined ? {} : { title: input.title }),
186190
createdBy: "agent",
187191
creationSource: "mcp",
188192
})
189-
.pipe(Effect.mapError(dispatchFailure));
190-
return { sequence: result.sequence, targetThreadId };
193+
.pipe(
194+
Effect.mapError((error) =>
195+
error._tag === "ThreadLaunchError"
196+
? new OrchestratorMcpFailure({
197+
code: "orchestration_error",
198+
message: error.message,
199+
})
200+
: dispatchFailure(error),
201+
),
202+
);
191203
}),
192204
),
193205
),

0 commit comments

Comments
 (0)