@devries-cameron20 / t3code-1 / commits / 50c1c5dc53
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat: side chats beside the main thread (#26901)

Co-authored-by: cdxker <fdenzell@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 31, 2026 at 00:03 UTC 50c1c5dc536493826fc66e220598f38b831d5bde
102 files changed +4710 -987
apps/mobile/src/features/keyboard/CommandPalette.tsx
+2 -5
@@ -8,7 +8,7 @@ import {
8 type EnvironmentThreadSearchMatch,
9 type ShownOrder,
10 } from "@t3tools/client-runtime/state/thread-search";
11 -import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
11 +import { isListedThreadLineage, THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
12 import {
13 foldSearchQuery,
14 PALETTE_MESSAGE_LIMIT,
@@ -422,10 +422,7 @@ export function CommandPalette(props: {
422 }),
423 }));
424 const threadItems: CommandPaletteItem[] = threads
425 - .filter(
426 - (thread) =>
427 - thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",
428 - )
425 + .filter((thread) => thread.archivedAt === null && isListedThreadLineage(thread.lineage))
426 .map((thread) => {
427 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
428 const environment =
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+7
@@ -195,6 +195,7 @@ import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
195 import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
196 import { useThreadQueuedCount } from "./ThreadQueueControl";
197 import { ThreadGuestShareBar } from "./ThreadGuestShareBar";
198 +import { ThreadSideChatsRow } from "./ThreadSideChatsRow";
199 import type { ThreadContentPresentation } from "./threadContentPresentation";
200 import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
201 import { useOpenLinkedThread } from "./useOpenLinkedThread";
@@ -1531,6 +1532,12 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
1532 threadRef={props.selectedThreadDetailRef}
1533 canOperateThread={props.canOperateThread}
1534 />
1535 + {props.draftMode ? null : (
1536 + <ThreadSideChatsRow
1537 + environmentId={props.environmentId}
1538 + threadId={props.selectedThread.id}
1539 + />
1540 + )}
1541 {props.feedbackSubmissions.map((submission) => (
1542 <ComposerFeedback
1543 key={submission.id}
apps/mobile/src/features/threads/ThreadSideChatsRow.tsx new
+66
@@ -0,0 +1,66 @@
1 +import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { Pressable, ScrollView, View } from "react-native";
3 +
4 +import { AppText as Text } from "../../components/ui/AppText";
5 +import { SymbolView } from "../../components/ui/AppSymbol";
6 +import { cn } from "../../lib/cn";
7 +import { useSideChats } from "../../state/entities";
8 +import { useOpenLinkedThread } from "./useOpenLinkedThread";
9 +
10 +/**
11 + * The thread's side chats, started on web or desktop. Each opens as a normal thread, so its
12 + * approvals and questions can be answered from the phone.
13 + */
14 +export function ThreadSideChatsRow(props: {
15 + readonly environmentId: EnvironmentId;
16 + readonly threadId: ThreadId;
17 +}) {
18 + const sideChats = useSideChats({ environmentId: props.environmentId, threadId: props.threadId });
19 + const openLinkedThread = useOpenLinkedThread();
20 + if (sideChats.length === 0) return null;
21 + return (
22 + <View className="flex-row items-center gap-2 pb-2 pl-4">
23 + <SymbolView
24 + name="bubble.left.and.bubble.right"
25 + size={12}
26 + tintColorClassName="accent-foreground-muted"
27 + />
28 + <Text className="text-xs text-foreground-muted">Side chats</Text>
29 + <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-1">
30 + <View className="flex-row gap-1 pr-4">
31 + {sideChats.map((sideChat) => {
32 + const needs =
33 + sideChat.hasPendingApprovals || sideChat.pendingSubagentRequest === "approval"
34 + ? "approval"
35 + : sideChat.hasPendingUserInput || sideChat.pendingSubagentRequest
36 + ? "input"
37 + : null;
38 + return (
39 + <Pressable
40 + key={sideChat.id}
41 + accessibilityRole="button"
42 + accessibilityLabel={`Open side chat ${sideChat.title}${needs === null ? "" : `, needs ${needs}`}`}
43 + className="max-w-48 flex-row items-center gap-1.5 rounded-full bg-subtle px-2.5 py-1"
44 + onPress={() =>
45 + openLinkedThread({ environmentId: props.environmentId, threadId: sideChat.id })
46 + }
47 + >
48 + {needs === null ? null : (
49 + <View
50 + className={cn(
51 + "h-1.5 w-1.5 shrink-0 rounded-full",
52 + needs === "approval" ? "bg-warning-foreground" : "bg-adaptive-indigo-600-300",
53 + )}
54 + />
55 + )}
56 + <Text className="shrink text-xs text-foreground" numberOfLines={1}>
57 + {sideChat.title}
58 + </Text>
59 + </Pressable>
60 + );
61 + })}
62 + </View>
63 + </ScrollView>
64 + </View>
65 + );
66 +}
apps/mobile/src/features/threads/threadListV2.ts
+3 -4
@@ -28,7 +28,7 @@ import {
28 sortPinnedThreadsByOrderKey,
29 sortSettledThreads,
30 } from "@t3tools/client-runtime/state/thread-sort";
31 -import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
31 +import { isListedThreadLineage, type EnvironmentId, type ProjectId } from "@t3tools/contracts";
32 import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
33
34 import type { ThreadListProvider } from "../../state/thread-list-environments";
@@ -265,8 +265,7 @@ export function getThreadListV2OrderedSection(input: {
265 }): EnvironmentThreadShell[] {
266 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
267 const threads = input.threads.filter((thread) => {
268 - if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
269 - return false;
268 + if (thread.archivedAt !== null || !isListedThreadLineage(thread.lineage)) return false;
269 if (
270 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
271 thread.settledOverride === "settled" &&
@@ -647,7 +646,7 @@ export function buildThreadListV2Items(input: {
646 const listedThreads = input.threads.filter(
647 (thread) =>
648 thread.archivedAt === null &&
650 - thread.lineage.relationshipToParent !== "subagent" &&
649 + isListedThreadLineage(thread.lineage) &&
650 (input.environmentId === null || thread.environmentId === input.environmentId) &&
651 (projectKeys === null || projectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
652 );
apps/mobile/src/state/entities.ts
+4
@@ -198,6 +198,10 @@ export function useChildThreadInputs(ref: ScopedThreadRef) {
198 return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));
199 }
200
201 +export function useSideChats(ref: ScopedThreadRef) {
202 + return useAtomValue(environmentThreadShells.sideChatsAtom(ref));
203 +}
204 +
205 export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
206 const titles = useAtomValue(
207 hasThreadLinks(markdown)
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -224,6 +224,7 @@ export const make = Effect.gen(function* () {
224 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
225 pullRequests: true,
226 pullRequestChecks: true,
227 + sideChats: true,
228 inlineMessageContext: true,
229 requiredWorktreeBootstrap: true,
230 threadSettlement: true,
apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts
+186
@@ -719,4 +719,190 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
719 assert.deepEqual([...projected.readyCheckpointOrdinals].toSorted(), [0, 1]);
720 }),
721 );
722 +
723 + it.effect("completes a side chat run with a missing checkpoint and never touches git", () =>
724 + Effect.gen(function* () {
725 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
726 + const now = yield* DateTime.now;
727 + const sideChatThreadId = ThreadId.make("thread:checkpoint-capture-side-chat");
728 + const sideChatRunId = RunId.make("run:checkpoint-capture-side-chat");
729 + const sideChatScopeId = CheckpointScopeId.make("scope:checkpoint-capture-side-chat");
730 + const sideChatRootNodeId = NodeId.make("node:checkpoint-capture-side-chat-root");
731 + const sideChatProviderThreadId = ProviderThreadId.make(
732 + "provider-thread:checkpoint-capture-side-chat",
733 + );
734 + const event = { threadId: sideChatThreadId, occurredAt: now };
735 + const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
736 + {
737 + ...event,
738 + id: EventId.make("event:checkpoint-capture-side-chat:thread"),
739 + type: "thread.created",
740 + payload: {
741 + createdBy: "user",
742 + creationSource: "web",
743 + id: sideChatThreadId,
744 + projectId,
745 + title: "Side chat",
746 + providerInstanceId,
747 + modelSelection,
748 + runtimeMode: "approval-required",
749 + interactionMode: "default",
750 + branch: null,
751 + worktreePath: "/repo",
752 + activeProviderThreadId: null,
753 + lineage: {
754 + parentThreadId: threadId,
755 + relationshipToParent: "fork",
756 + rootThreadId: threadId,
757 + sideChat: true,
758 + },
759 + forkedFrom: null,
760 + createdAt: now,
761 + updatedAt: now,
762 + archivedAt: null,
763 + settledOverride: null,
764 + settledAt: null,
765 + lastVisitedAt: null,
766 + deletedAt: null,
767 + },
768 + },
769 + {
770 + ...event,
771 + id: EventId.make("event:checkpoint-capture-side-chat:provider-thread"),
772 + type: "provider-thread.updated",
773 + driver,
774 + providerInstanceId,
775 + payload: {
776 + id: sideChatProviderThreadId,
777 + driver,
778 + providerInstanceId,
779 + providerSessionId: null,
780 + appThreadId: sideChatThreadId,
781 + ownerNodeId: null,
782 + nativeThreadRef: null,
783 + nativeConversationHeadRef: null,
784 + status: "idle",
785 + firstRunOrdinal: 1,
786 + lastRunOrdinal: 1,
787 + handoffIds: [],
788 + forkedFrom: null,
789 + createdAt: now,
790 + updatedAt: now,
791 + },
792 + },
793 + {
794 + ...event,
795 + id: EventId.make("event:checkpoint-capture-side-chat:run"),
796 + type: "run.updated",
797 + runId: sideChatRunId,
798 + payload: {
799 + id: sideChatRunId,
800 + threadId: sideChatThreadId,
801 + ordinal: 1,
802 + providerInstanceId,
803 + modelSelection,
804 + providerThreadId: sideChatProviderThreadId,
805 + userMessageId: MessageId.make("message:checkpoint-capture-side-chat"),
806 + rootNodeId: sideChatRootNodeId,
807 + activeAttemptId: null,
808 + status: "waiting",
809 + requestedAt: now,
810 + startedAt: now,
811 + completedAt: null,
812 + checkpointId: null,
813 + contextHandoffId: null,
814 + },
815 + },
816 + {
817 + ...event,
818 + id: EventId.make("event:checkpoint-capture-side-chat:node"),
819 + type: "node.updated",
820 + runId: sideChatRunId,
821 + nodeId: sideChatRootNodeId,
822 + payload: {
823 + id: sideChatRootNodeId,
824 + threadId: sideChatThreadId,
825 + runId: sideChatRunId,
826 + parentNodeId: null,
827 + rootNodeId: sideChatRootNodeId,
828 + kind: "root_turn",
829 + status: "waiting",
830 + countsForRun: true,
831 + providerThreadId: sideChatProviderThreadId,
832 + providerTurnId: null,
833 + nativeItemRef: null,
834 + runtimeRequestId: null,
835 + checkpointScopeId: sideChatScopeId,
836 + startedAt: now,
837 + completedAt: null,
838 + },
839 + },
840 + {
841 + ...event,
842 + id: EventId.make("event:checkpoint-capture-side-chat:scope"),
843 + type: "checkpoint-scope.created",
844 + runId: sideChatRunId,
845 + nodeId: sideChatRootNodeId,
846 + payload: {
847 + id: sideChatScopeId,
848 + threadId: sideChatThreadId,
849 + runId: sideChatRunId,
850 + nodeId: sideChatRootNodeId,
851 + parentScopeId: null,
852 + providerThreadId: sideChatProviderThreadId,
853 + kind: "root_run",
854 + ordinalWithinParent: 0,
855 + advancesAppRunCount: true,
856 + cwd: "/repo",
857 + createdAt: now,
858 + },
859 + },
860 + ];
861 + yield* Effect.forEach(events, (candidate) => projectionStore.apply(candidate));
862 + const gitUnavailable = () => Effect.die("side chats must not snapshot the shared worktree");
863 + const layerCapture = CheckpointCaptureService.layer.pipe(
864 + Layer.provide(
865 + Layer.mergeAll(
866 + IdAllocator.layer,
867 + CheckpointService.layer.pipe(
868 + Layer.provide(
869 + Layer.mergeAll(
870 + IdAllocator.layer,
871 + NodeCrypto.layer,
872 + Layer.mock(CheckpointStore.CheckpointStore)({
873 + isGitRepository: gitUnavailable,
874 + captureCheckpoint: gitUnavailable,
875 + hasCheckpointRef: gitUnavailable,
876 + }),
877 + ),
878 + ),
879 + ),
880 + Layer.mock(EventSink.EventSinkV2)({
881 + commitCommand: (input) =>
882 + Effect.forEach(input.events, (committed) => projectionStore.apply(committed)).pipe(
883 + Effect.as({ committed: true } as never),
884 + Effect.orDie,
885 + ),
886 + }),
887 + ),
888 + ),
889 + );
890 +
891 + yield* CheckpointCaptureService.CheckpointCaptureServiceV2.use((service) =>
892 + service.execute({
893 + threadId: sideChatThreadId,
894 + runId: sideChatRunId,
895 + scopeId: sideChatScopeId,
896 + }),
897 + ).pipe(Effect.provide(layerCapture));
898 +
899 + const { checkpoints, runs } = yield* projectionStore.getThreadRecords(sideChatThreadId, [
900 + "runs",
901 + "checkpoints",
902 + ]);
903 + assert.equal(runs[0]?.status, "completed");
904 + const checkpoint = checkpoints.find((candidate) => candidate.id === runs[0]?.checkpointId);
905 + assert.equal(checkpoint?.status, "missing");
906 + }),
907 + );
908 });
apps/server/src/orchestration-v2/CheckpointCaptureService.ts
+4 -1
@@ -65,7 +65,7 @@ export const layer: Layer.Layer<
65 readonly runId: RunId;
66 readonly scopeId: CheckpointScopeId;
67 }) {
68 - const { run, rootNode, scope, providerThread, readyCheckpointOrdinals } =
68 + const { run, rootNode, scope, providerThread, readyCheckpointOrdinals, sideChat } =
69 yield* projections.getCheckpointCaptureContext(input.threadId, input);
70 // Stopped runs remain terminal; their checkpoint is the next message's rollback point.
71 const stopped = run?.status === "interrupted" || run?.status === "cancelled";
@@ -109,12 +109,14 @@ export const layer: Layer.Layer<
109 : yield* checkpoints.materializeBaselineCheckpoint({
110 scope,
111 ordinalWithinScope: 0,
112 + forceMissing: sideChat,
113 });
114 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
115 ? null
116 : yield* checkpoints.materializeBaselineCheckpoint({
117 scope,
118 ordinalWithinScope: baselineOrdinalWithinScope,
119 + forceMissing: sideChat,
120 });
121 const checkpoint = yield* checkpoints.capture({
122 scope,
@@ -123,6 +125,7 @@ export const layer: Layer.Layer<
125 ordinalWithinScope: run.ordinal,
126 appRunOrdinal: run.ordinal,
127 capturedAt,
128 + forceMissing: sideChat,
129 });
130 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
131 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+50
@@ -64,6 +64,7 @@ it.effect.each([
64 id: otherId,
65 projectId,
66 deletedAt: null,
67 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: otherId },
68 worktreePath:
69 owner === "ancestor" || owner === "conversation"
70 ? parent
@@ -202,3 +203,52 @@ it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
203 assert.isTrue(isolated);
204 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
205 );
206 +
207 +it.effect.each([
208 + { sideChat: "answering questions", running: false, toolItems: 0, isolated: true },
209 + { sideChat: "running", running: true, toolItems: 0, isolated: false },
210 + { sideChat: "after running tools", running: false, toolItems: 1, isolated: false },
211 +] as const)(
212 + "a side chat $sideChat shares the parent's worktree: $isolated",
213 + ({ running, toolItems, isolated }) =>
214 + Effect.gen(function* () {
215 + const fileSystem = yield* FileSystem.FileSystem;
216 + const path = yield* Path.Path;
217 + const worktreePath = yield* fileSystem.makeTempDirectoryScoped({
218 + prefix: "t3-v2-restore-side-chat-",
219 + });
220 + const parentId = ThreadId.make("restore-side-chat-parent");
221 + const sideChat = {
222 + id: ThreadId.make("restore-side-chat"),
223 + projectId: ProjectId.make("restore-project"),
224 + deletedAt: null,
225 + worktreePath,
226 + activeRunId: running ? "side-chat-run" : null,
227 + lineage: {
228 + parentThreadId: parentId,
229 + relationshipToParent: "fork",
230 + rootThreadId: parentId,
231 + sideChat: true,
232 + },
233 + };
234 + const result = yield* isCheckpointRestoreIsolated(
235 + { id: parentId, worktreePath },
236 + { cwd: worktreePath },
237 + {
238 + fileSystem,
239 + path,
240 + projections: {
241 + getShellSnapshot: () => Effect.succeed({ threads: [sideChat], archivedThreads: [] }),
242 + getThreadRecords: () =>
243 + Effect.succeed({
244 + turnItems: Array.from({ length: toolItems }, () => ({ type: "command_execution" })),
245 + }),
246 + getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] }),
247 + getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
248 + } as never,
249 + projects: {} as never,
250 + },
251 + );
252 + assert.equal(result, isolated);
253 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
254 +);
apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts
+16 -1
@@ -7,7 +7,7 @@ import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
7 import type * as ProjectStore from "./ProjectStore.ts";
8
9 export const SHARED_WORKSPACE_RESTORE_MESSAGE =
10 - "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.";
10 + "File restore requires an isolated worktree. This workspace may contain changes from another thread or a side chat. Rewind the conversation without restoring files instead, or delete side chats you no longer need.";
11
12 // Check isolation at admission and rollback; checkpoints restore whole checkouts, which may become shared.
13 export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(
@@ -48,6 +48,21 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
48 const checkedPaths = new Set<string>();
49 for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
50 if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
51 + // An idle side chat that only answered questions never touched the shared worktree.
52 + if (
53 + otherThread.lineage.sideChat === true &&
54 + otherThread.activeRunId === null &&
55 + otherThread.worktreePath === worktreePath
56 + ) {
57 + const { turnItems } = yield* projections.getThreadRecords(
58 + otherThread.id,
59 + ["turnItems"],
60 + {
61 + turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],
62 + },
63 + );
64 + if (turnItems.length === 0) continue;
65 + }
66 const other = yield* projections.getCheckpointContext(otherThread.id);
67 const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
68 const paths = [
apps/server/src/orchestration-v2/CheckpointService.ts
+6 -2
@@ -118,6 +118,8 @@ export interface CheckpointServiceV2Shape {
118 readonly materializeBaselineCheckpoint: (input: {
119 readonly scope: OrchestrationV2CheckpointScope;
120 readonly ordinalWithinScope: number;
121 + /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */
122 + readonly forceMissing?: boolean;
123 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
124 readonly capture: (input: {
125 readonly scope: OrchestrationV2CheckpointScope;
@@ -126,6 +128,7 @@ export interface CheckpointServiceV2Shape {
128 readonly ordinalWithinScope: number;
129 readonly appRunOrdinal: number | null;
130 readonly capturedAt: DateTime.Utc;
131 + readonly forceMissing?: boolean;
132 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
133 readonly restore: (input: {
134 readonly scope: OrchestrationV2CheckpointScope;
@@ -299,7 +302,8 @@ export const layer: Layer.Layer<
302 scopeId: input.scope.id,
303 ordinalWithinScope: input.ordinalWithinScope,
304 });
302 - const checkpointable = yield* isGitCheckpointable(input.scope.cwd);
305 + const checkpointable =
306 + input.forceMissing !== true && (yield* isGitCheckpointable(input.scope.cwd));
307 const available = checkpointable
308 ? yield* checkpointStore
309 .hasCheckpointRef({
@@ -364,7 +368,7 @@ export const layer: Layer.Layer<
368 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
369 });
370
367 - if (!(yield* isGitCheckpointable(input.scope.cwd))) {
371 + if (input.forceMissing === true || !(yield* isGitCheckpointable(input.scope.cwd))) {
372 return makeCheckpoint({
373 id: checkpointId,
374 scope: input.scope,
apps/server/src/orchestration-v2/CommandPolicy.test.ts
+22
@@ -260,9 +260,31 @@ layer("CommandPolicyV2", (it) => {
260 hasStrongNativeSource: true,
261 sourceRunStatus: "completed",
262 fromSpecificTurn: true,
263 + sourceBusy: false,
264 });
265
266 assert.equal(result, "portable_context");
267 }),
268 );
269 +
270 + it.effect("forks a busy source through portable context", () =>
271 + Effect.gen(function* () {
272 + const policy = yield* CommandPolicy.CommandPolicyV2;
273 + const decide = (sourceBusy: boolean) =>
274 + policy.decideForkExecution({
275 + commandId,
276 + threadId,
277 + providerInstanceId: ProviderInstanceId.make("codex"),
278 + capabilities: CodexProviderCapabilitiesV2,
279 + sameProvider: true,
280 + hasStrongNativeSource: true,
281 + sourceRunStatus: "completed",
282 + fromSpecificTurn: true,
283 + sourceBusy,
284 + });
285 +
286 + assert.equal(yield* decide(false), "native_fork");
287 + assert.equal(yield* decide(true), "portable_context");
288 + }),
289 + );
290 });
apps/server/src/orchestration-v2/CommandPolicy.ts
+5 -1
@@ -115,7 +115,8 @@ export function resolveMessageDispatchIntent(
115 : mode;
116 }
117
118 -function isActiveRun(run: OrchestrationV2Run): boolean {
118 +/** A run that still owns the thread's provider turn. */
119 +export function isActiveRun(run: OrchestrationV2Run): boolean {
120 return (
121 run.status === "preparing" ||
122 run.status === "starting" ||
@@ -210,6 +211,8 @@ export interface CommandPolicyV2Shape {
211 readonly hasStrongNativeSource: boolean;
212 readonly sourceRunStatus: OrchestrationV2Run["status"];
213 readonly fromSpecificTurn: boolean;
214 + /** Later source runs are still active; providers cannot fork a thread mid-turn. */
215 + readonly sourceBusy: boolean;
216 },
217 ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
218 readonly ensureRollback: (
@@ -373,6 +376,7 @@ const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input)
376 (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&
377 input.sameProvider &&
378 input.hasStrongNativeSource &&
379 + !input.sourceBusy &&
380 input.capabilities.threads.canForkThread &&
381 (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
382 input.capabilities.identity.nativeThreadIds === "strong";
apps/server/src/orchestration-v2/ContextHandoffDelivery.ts
+4
@@ -12,6 +12,10 @@ import {
12 selectHistory,
13 } from "@t3tools/provider-core/server/handoffBudget";
14
15 +/** The provider prompt for a turn that carries inline context ahead of the user's text. */
16 +export const withInlineContext = (context: string, userText: string): string =>
17 + context === "" ? userText : `${context}\n\nUser message:\n${userText}`;
18 +
19 /** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */
20 export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
21 function* <InjectError = never, PersistError = never, BudgetError = never>(input: {
apps/server/src/orchestration-v2/ContextHandoffService.test.ts
+91
@@ -1,11 +1,13 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 MessageId,
4 + ProjectId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 RunId,
8 ThreadId,
9 TurnItemId,
10 + type OrchestrationV2AppThread,
11 type OrchestrationV2TurnItem,
12 } from "@t3tools/contracts";
13 import * as DateTime from "effect/DateTime";
@@ -14,6 +16,7 @@ import * as Layer from "effect/Layer";
16
17 import * as ContextHandoffService from "./ContextHandoffService.ts";
18 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19 +import { ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
20
21 const layerTest = ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer));
22
@@ -156,3 +159,91 @@ it.layer(layerTest)("ContextHandoffService legacy import", (it) => {
159 }),
160 );
161 });
162 +
163 +it("caps the side chat context block, keeping the newest parent items", () => {
164 + const parentThreadId = ThreadId.make("thread:side-chat-parent");
165 + const digest = Array.from({ length: 60 }, (_, index) =>
166 + ContextHandoffService.summarizeDeltaItem(
167 + importedItem({
168 + role: index % 2 === 0 ? "user" : "assistant",
169 + id: `parent-${index}`,
170 + text: `item-${index} ${"x".repeat(300)}`,
171 + ordinal: index,
172 + }),
173 + )!,
174 + );
175 + const context = ContextHandoffService.makeSideChatContext({ parentThreadId, digest });
176 +
177 + assert.include(context, "- Earlier items truncated.");
178 + assert.notInclude(context, "item-0 ");
179 + assert.include(context, "- Assistant: item-59 ");
180 + assert.isAtMost(context.length, 8_000);
181 + assert.isTrue(
182 + context.endsWith(
183 + `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`,
184 + ),
185 + );
186 +
187 + const framingOnly = ContextHandoffService.makeSideChatContext({ parentThreadId, digest: [] });
188 + assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread."));
189 + assert.notInclude(framingOnly, "Main thread activity");
190 +});
191 +
192 +it("covers the run range of a very long delta", () => {
193 + const runs = [
194 + { id: RunId.make("run:long-delta-early"), ordinal: 2 },
195 + { id: RunId.make("run:long-delta-late"), ordinal: 5 },
196 + ];
197 + const items = Array.from({ length: 150_000 }, (_, index) => ({
198 + runId: runs[index % 2]!.id,
199 + }));
200 +
201 + assert.deepEqual(
202 + ContextHandoffService.visibleDeltaRunOrdinals({ runs }, [...items, { runId: null }]),
203 + { from: 2, to: 5 },
204 + );
205 +});
206 +
207 +it.effect("inherited history stops at a missing fork ancestor", () =>
208 + Effect.gen(function* () {
209 + const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
210 + const threadId = ThreadId.make("thread:fork-of-missing");
211 + const thread: OrchestrationV2AppThread = {
212 + createdBy: "user",
213 + creationSource: "web",
214 + id: threadId,
215 + projectId: ProjectId.make("project:fork-of-missing"),
216 + title: "Fork of a missing thread",
217 + providerInstanceId: ProviderInstanceId.make("codex"),
218 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
219 + runtimeMode: "full-access",
220 + interactionMode: "default",
221 + branch: null,
222 + worktreePath: null,
223 + activeProviderThreadId: null,
224 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
225 + forkedFrom: {
226 + type: "run",
227 + threadId: ThreadId.make("thread:missing-ancestor"),
228 + runId: RunId.make("run:missing-ancestor"),
229 + },
230 + createdAt: now,
231 + updatedAt: now,
232 + archivedAt: null,
233 + settledOverride: null,
234 + settledAt: null,
235 + lastVisitedAt: null,
236 + snoozedUntil: null,
237 + snoozedAt: null,
238 + deletedAt: null,
239 + };
240 + const items = yield* ContextHandoffService.readInheritedHandoffItems(
241 + {
242 + getThreadRecords: (missing) =>
243 + Effect.fail(new ProjectionStoreThreadNotFoundError({ threadId: missing })),
244 + },
245 + thread,
246 + );
247 + assert.deepEqual(items, []);
248 + }),
249 +);
apps/server/src/orchestration-v2/ContextHandoffService.ts
+189 -1
@@ -1,7 +1,9 @@
1 import {
2 + type OrchestrationV2AppThread,
3 OrchestrationV2ContextHandoff,
4 type OrchestrationV2TurnItem,
5 type OrchestrationV2Run,
6 + type OrchestrationV2ThreadProjection,
7 ProviderInstanceId,
8 ProviderThreadId,
9 RunId,
@@ -22,6 +24,8 @@ import {
24 selectHistory,
25 } from "@t3tools/provider-core/server/handoffBudget";
26 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
27 +import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline";
28 +import type { ProjectionStoreV2Shape } from "./ProjectionStore.ts";
29
30 export class ContextHandoffPrepareError extends Schema.TaggedError<ContextHandoffPrepareError>()(
31 "ContextHandoffPrepareError",
@@ -80,6 +84,19 @@ export interface ContextHandoffServiceV2Shape {
84 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
85 readonly createdAt: DateTime.Utc;
86 }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
87 + /** Parent activity after the fork point, prepended to a side chat's first provider turn. */
88 + readonly prepareSideChatContext: (input: {
89 + readonly threadId: ThreadId;
90 + readonly parentThreadId: ThreadId;
91 + readonly targetRunId: RunId;
92 + readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
93 + readonly toProviderThreadId: ProviderThreadId;
94 + readonly fromProviderInstanceId: ProviderInstanceId;
95 + readonly toProviderInstanceId: ProviderInstanceId;
96 + readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
97 + readonly parentItems: ReadonlyArray<OrchestrationV2TurnItem>;
98 + readonly createdAt: DateTime.Utc;
99 + }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
100 }
101
102 export class ContextHandoffServiceV2 extends Context.Service<
@@ -95,7 +112,97 @@ function compactText(text: string, maxLength = 240): string {
112 return `${compacted.slice(0, maxLength - 3)}...`;
113 }
114
98 -function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {
115 +export function visibleDeltaRunOrdinals(
116 + projection: { readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "ordinal">> },
117 + items: ReadonlyArray<Pick<OrchestrationV2TurnItem, "runId">>,
118 +): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
119 + const ordinalByRunId = new Map(projection.runs.map((run) => [run.id, run.ordinal]));
120 + let from = Infinity;
121 + let to = -Infinity;
122 + for (const item of items) {
123 + const ordinal = item.runId === null ? undefined : ordinalByRunId.get(item.runId);
124 + if (ordinal === undefined) continue;
125 + from = Math.min(from, ordinal);
126 + to = Math.max(to, ordinal);
127 + }
128 + return from === Infinity ? { from: 1, to: 1 } : { from, to };
129 +}
130 +
131 +/** Drops rolled-back runs and cancelled queued messages, which are not part of the conversation. */
132 +export function visibleConversationItems(
133 + projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts">,
134 + items: ReadonlyArray<OrchestrationV2TurnItem>,
135 +): ReadonlyArray<OrchestrationV2TurnItem> {
136 + const visible = createOrchestrationV2TurnItemVisibility({
137 + runs: projection.runs,
138 + attempts: projection.attempts,
139 + items,
140 + });
141 + return items.filter(visible);
142 +}
143 +
144 +type ForkHistorySource = Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "attempts">;
145 +
146 +/** Visible rows of `source`'s own runs through `throughRun`, plus its v1 imported rows. */
147 +const readOwnHistoryItems = Effect.fn("orchestrationV2.contextHandoff.readOwnHistoryItems")(
148 + function* (
149 + projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
150 + source: ForkHistorySource,
151 + throughRun: Pick<OrchestrationV2Run, "ordinal">,
152 + ) {
153 + const { turnItems } = yield* projectionStore.getThreadRecords(source.thread.id, ["turnItems"], {
154 + turnItemRunIds: [
155 + ...source.runs.filter((run) => run.ordinal <= throughRun.ordinal).map((run) => run.id),
156 + ...(source.thread.historyOrigin === "v1_import" ? [null] : []),
157 + ],
158 + });
159 + return visibleConversationItems(source, turnItems);
160 + },
161 +);
162 +
163 +/** History `thread` shows from its fork ancestors, oldest first. Side chats inherit no rows. */
164 +export const readInheritedHandoffItems = Effect.fn(
165 + "orchestrationV2.contextHandoff.readInheritedHandoffItems",
166 +)(function* (
167 + projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
168 + thread: OrchestrationV2AppThread,
169 +) {
170 + const segments: Array<ReadonlyArray<OrchestrationV2TurnItem>> = [];
171 + const seen = new Set([thread.id]);
172 + let current = thread;
173 + while (
174 + current.forkedFrom?.type === "run" &&
175 + current.lineage.sideChat !== true &&
176 + !seen.has(current.forkedFrom.threadId)
177 + ) {
178 + const { threadId, runId } = current.forkedFrom;
179 + seen.add(threadId);
180 + const source = yield* projectionStore
181 + .getThreadRecords(threadId, ["runs", "attempts"])
182 + .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }));
183 + const forkRun = source?.runs.find((run) => run.id === runId);
184 + if (source === null || forkRun === undefined) break;
185 + segments.unshift(yield* readOwnHistoryItems(projectionStore, source, forkRun));
186 + current = source.thread;
187 + }
188 + return segments.flat();
189 +});
190 +
191 +/** What a portable fork from `throughRun` of `source` carries: inherited rows, then its own. */
192 +export const readForkHistoryItems = Effect.fn(
193 + "orchestrationV2.contextHandoff.readForkHistoryItems",
194 +)(function* (
195 + projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
196 + source: ForkHistorySource,
197 + throughRun: Pick<OrchestrationV2Run, "ordinal">,
198 +) {
199 + return [
200 + ...(yield* readInheritedHandoffItems(projectionStore, source.thread)),
201 + ...(yield* readOwnHistoryItems(projectionStore, source, throughRun)),
202 + ];
203 +});
204 +
205 +export function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {
206 switch (item.type) {
207 case "user_message":
208 return `- User: ${compactText(item.text)}`;
@@ -135,6 +242,41 @@ function makeForkDeltaSummary(input: {
242 ].join("\n");
243 }
244
245 +const SIDE_CHAT_CONTEXT_MAX_CHARS = 8_000;
246 +
247 +/** `digest` holds `summarizeDeltaItem` lines for parent items after the fork point, oldest first. */
248 +export function makeSideChatContext(input: {
249 + readonly parentThreadId: ThreadId;
250 + readonly digest: ReadonlyArray<string>;
251 +}): string {
252 + const framing =
253 + "You are in a side chat beside the main thread. The main thread may still be running in the same worktree. Answer the user's questions; do not continue or redo the main thread's task.";
254 + const header = "Main thread activity since this side chat's starting point:";
255 + const truncated = "- Earlier items truncated.";
256 + const footer = `Use t3_thread_read on thread ${input.parentThreadId} to see the main thread's live state.`;
257 + const kept: Array<string> = [];
258 + // The cap covers the whole block, so the fixed lines are reserved before any digest line.
259 + let remaining =
260 + SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length;
261 + for (const line of input.digest.toReversed()) {
262 + if (line.length + 1 > remaining) break;
263 + kept.unshift(line);
264 + remaining -= line.length + 1;
265 + }
266 + return [
267 + framing,
268 + ...(kept.length === 0
269 + ? []
270 + : ["", header, ...(kept.length < input.digest.length ? [truncated] : []), ...kept]),
271 + "",
272 + footer,
273 + ].join("\n");
274 +}
275 +
276 +/** Side chat context is prepended to the provider prompt, never replayed as budgeted history. */
277 +export const isSideChatContextHandoff = (handoff: OrchestrationV2ContextHandoff): boolean =>
278 + handoff.strategy === "manual_context" && handoff.transferId != null;
279 +
280 function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>): string {
281 const sections = items.flatMap((item) => {
282 switch (item.type) {
@@ -412,10 +554,56 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
554 } satisfies OrchestrationV2ContextHandoff;
555 });
556
557 + const prepareSideChatContext = Effect.fn(
558 + "orchestrationV2.contextHandoff.prepareSideChatContext",
559 + )(function* (input: Parameters<ContextHandoffServiceV2Shape["prepareSideChatContext"]>[0]) {
560 + const handoffId = yield* idAllocator.allocate
561 + .contextHandoff({
562 + threadId: input.threadId,
563 + fromProviderInstanceId: input.fromProviderInstanceId,
564 + toProviderInstanceId: input.toProviderInstanceId,
565 + })
566 + .pipe(
567 + Effect.mapError(
568 + (cause) =>
569 + new ContextHandoffPrepareError({
570 + threadId: input.threadId,
571 + targetRunId: input.targetRunId,
572 + fromProviderThreadIds: [],
573 + toProviderThreadId: input.toProviderThreadId,
574 + cause,
575 + }),
576 + ),
577 + );
578 + return {
579 + id: handoffId,
580 + transferId: input.transferId,
581 + threadId: input.threadId,
582 + targetRunId: input.targetRunId,
583 + fromProviderThreadIds: [],
584 + toProviderThreadId: input.toProviderThreadId,
585 + coveredRunOrdinals: input.coveredRunOrdinals,
586 + strategy: "manual_context",
587 + status: "ready",
588 + summaryMessageId: null,
589 + summaryText: makeSideChatContext({
590 + parentThreadId: input.parentThreadId,
591 + digest: input.parentItems.flatMap((item) => {
592 + const line = summarizeDeltaItem(item);
593 + return line === null ? [] : [line];
594 + }),
595 + }),
596 + createdByProviderInstanceId: null,
597 + createdAt: input.createdAt,
598 + updatedAt: input.createdAt,
599 + } satisfies OrchestrationV2ContextHandoff;
600 + });
601 +
602 return ContextHandoffServiceV2.of({
603 prepareLegacyImport,
604 prepareForkDelta,
605 prepareProviderHandoff,
606 + prepareSideChatContext,
607 });
608 },
609 );
apps/server/src/orchestration-v2/IdleCompaction.test.ts
+8 -1
@@ -148,7 +148,7 @@ function records(
148 }
149
150 describe("idleCompactionWindow", () => {
151 - it("skips small contexts, unknown expiry, other providers, switched threads, and compactions", () => {
151 + it("skips small contexts, unknown expiry, other providers, switched threads, compactions, and side chats", () => {
152 const cache = { cacheExpiresInMs: 60 * MINUTE_MS };
153 expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();
154 expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();
@@ -166,6 +166,13 @@ describe("idleCompactionWindow", () => {
166 const archived = records(cache);
167 archived.thread = { ...archived.thread, archivedAt: at() };
168 expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();
169 + const sideChat = records(cache);
170 + expect(idleCompactionWindow(sideChat, NOW_MS)).not.toBeNull();
171 + sideChat.thread = {
172 + ...sideChat.thread,
173 + lineage: { ...sideChat.thread.lineage, relationshipToParent: "fork", sideChat: true },
174 + };
175 + expect(idleCompactionWindow(sideChat, NOW_MS)).toBeNull();
176 });
177 });
178
apps/server/src/orchestration-v2/IdleCompaction.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
1 +import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2 import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction";
3 import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
4 import * as DateTime from "effect/DateTime";
@@ -50,7 +50,7 @@ export function idleCompactionWindow(
50 if (thread.settledAt !== null || thread.settledOverride === "settled") return null;
51 if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)
52 return null;
53 - if (thread.lineage.relationshipToParent === "subagent") return null;
53 + if (!isListedThreadLineage(thread.lineage)) return null;
54 const latestRun = runs.reduce<(typeof runs)[number] | null>(
55 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
56 null,
apps/server/src/orchestration-v2/Orchestrator.ts
+301 -100
@@ -59,6 +59,7 @@ import {
59 latestProviderTurnForAttempt,
60 parseGoalCommand,
61 orchestrationV2RunWorkStartedAt,
62 + orchestrationV2WorktreePending,
63 ProviderInstanceId,
64 ProviderInteractionMode,
65 resolveProviderInstanceEnabled,
@@ -99,11 +100,18 @@ import { CheckpointServiceV2 } from "./CheckpointService.ts";
100 import {
101 CommandPolicyV2,
102 goalCommandStopsActiveRun,
103 + isActiveRun,
104 isNativeMaintenanceCommand,
105 resolveMessageDispatchIntent,
106 } from "./CommandPolicy.ts";
107 import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
106 -import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
108 +import {
109 + ContextHandoffServiceV2,
110 + readForkHistoryItems,
111 + readInheritedHandoffItems,
112 + visibleConversationItems,
113 + visibleDeltaRunOrdinals,
114 +} from "./ContextHandoffService.ts";
115 import { notificationTurnItem } from "@t3tools/provider-core/server/notification";
116 import {
117 cancelledBeforeStart,
@@ -637,15 +645,6 @@ function mayStartSubagentFollowup(
645 return command.createdBy === "user" || command.creationSource === "mcp";
646 }
647
640 -function isBlockingRun(run: OrchestrationV2Run): boolean {
641 - return (
642 - run.status === "preparing" ||
643 - run.status === "starting" ||
644 - run.status === "running" ||
645 - run.status === "waiting"
646 - );
647 -}
648 -
648 /** Waiting runs only drain post-terminal output; their agent turn is over and still needs a wake. */
649 function isLiveRun(run: OrchestrationV2Run): boolean {
650 return run.status === "preparing" || run.status === "starting" || run.status === "running";
@@ -919,26 +918,6 @@ function latestContextTransfer(
918 }, undefined);
919 }
920
922 -function visibleDeltaRunOrdinals(
923 - projection: Pick<OrchestrationV2ThreadProjection, "runs">,
924 - items: ReadonlyArray<OrchestrationV2TurnItem>,
925 -): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
926 - const ordinals = items.flatMap((item) => {
927 - if (item.runId === null) {
928 - return [];
929 - }
930 - const run = projection.runs.find((candidate) => candidate.id === item.runId);
931 - return run === undefined ? [] : [run.ordinal];
932 - });
933 - if (ordinals.length === 0) {
934 - return { from: 1, to: 1 };
935 - }
936 - return {
937 - from: Math.min(...ordinals),
938 - to: Math.max(...ordinals),
939 - };
940 -}
941 -
921 export function shouldPrepareLegacyImportHandoff(input: {
922 readonly hasCompletedRun: boolean;
923 readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
@@ -1199,6 +1178,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1178 Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
1179 );
1180
1181 + const readInheritedItems = (thread: OrchestrationV2AppThread) =>
1182 + readInheritedHandoffItems(projectionStore, thread).pipe(
1183 + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId: thread.id, cause })),
1184 + );
1185 +
1186 + /** Includes tombstones, which still reserve their id. */
1187 + const findThread = (threadId: ThreadId) =>
1188 + projectionStore.getThread(threadId).pipe(
1189 + Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
1190 + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
1191 + );
1192 +
1193 + /** Side chats live inside their parent, so deleting the parent deletes them too. */
1194 + const liveSideChatIds = Effect.fn("Orchestrator.liveSideChatIds")(
1195 + function* (threadId: ThreadId) {
1196 + const { contextTransfers } = yield* projectionStore
1197 + .getThreadRecords(threadId, ["contextTransfers"])
1198 + .pipe(
1199 + Effect.catchTags({
1200 + ProjectionStoreThreadNotFoundError: () => Effect.succeed({ contextTransfers: [] }),
1201 + }),
1202 + );
1203 + const sideChatIds: Array<ThreadId> = [];
1204 + for (const transfer of contextTransfers) {
1205 + if (transfer.type !== "fork" || transfer.sourceThreadId !== threadId) continue;
1206 + const child = yield* projectionStore
1207 + .getThread(transfer.targetThreadId)
1208 + .pipe(
1209 + Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
1210 + );
1211 + if (child?.lineage.sideChat === true && child.deletedAt === null) {
1212 + sideChatIds.push(child.id);
1213 + }
1214 + }
1215 + return sideChatIds;
1216 + },
1217 + (effect, threadId) =>
1218 + effect.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
1219 + );
1220 +
1221 const getProjectionWithPendingEvents =
1222 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1223 Effect.fnUntraced(function* (
@@ -1527,7 +1546,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1546 if (
1547 projection.thread.archivedAt !== null ||
1548 projection.thread.deletedAt !== null ||
1530 - projection.runs.some(isBlockingRun)
1549 + projection.runs.some(isActiveRun)
1550 ) {
1551 return;
1552 }
@@ -4246,26 +4265,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4265 }),
4266 ),
4267 );
4249 - // The source is unlocked; validate the modes copied here, not an earlier read.
4268 + // Only side chat forks lock the source; validate the modes copied here, not an earlier read.
4269 yield* refuseAboveDispatchModeLimit(command, command.sourceThreadId, sourceProjection.thread);
4270 + if (command.sideChat === true && sourceProjection.thread.deletedAt !== null) {
4271 + return yield* new OrchestratorDispatchError({
4272 + commandId: command.commandId,
4273 + commandType: command.type,
4274 + cause: `Thread ${command.sourceThreadId} was deleted.`,
4275 + });
4276 + }
4277 + // The fork would copy no worktree path and run in the project checkout.
4278 + if (
4279 + command.sideChat === true &&
4280 + orchestrationV2WorktreePending(sourceProjection.thread.worktreePath, sourceProjection.runs)
4281 + ) {
4282 + return yield* new OrchestratorDispatchError({
4283 + commandId: command.commandId,
4284 + commandType: command.type,
4285 + cause: `Thread ${command.sourceThreadId} has no worktree yet. Start the side chat once its worktree is set up.`,
4286 + });
4287 + }
4288 + if ((yield* findThread(command.targetThreadId)) !== null) {
4289 + return yield* new OrchestratorThreadAlreadyExistsError({
4290 + commandId: command.commandId,
4291 + threadId: command.targetThreadId,
4292 + });
4293 + }
4294
4295 const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);
4296
4254 - if (sourceRun === null) {
4297 + // A side chat may open during the parent's first turn; it starts from a digest instead.
4298 + if (
4299 + sourceRun === null &&
4300 + !(command.sideChat === true && command.sourcePoint.type === "latest_stable")
4301 + ) {
4302 return yield* new OrchestratorDispatchError({
4303 commandId: command.commandId,
4304 commandType: command.type,
4305 cause: `No stable source run was found for fork source ${command.sourcePoint.type}.`,
4306 });
4307 }
4261 - if (!isForkableSourceRunStatus(sourceRun.status)) {
4308 + if (sourceRun !== null && !isForkableSourceRunStatus(sourceRun.status)) {
4309 return yield* new OrchestratorDispatchError({
4310 commandId: command.commandId,
4311 commandType: command.type,
4312 cause: forkableSourceRunStatusError(sourceRun),
4313 });
4314 }
4268 - const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun);
4315 + const sourceProviderThread =
4316 + sourceRun === null ? undefined : providerThreadForRun(sourceProjection, sourceRun);
4317 const now = command.createdAt ?? (yield* DateTime.now);
4318 const emitEvent = emit(events, command);
4319 const transferId = yield* mapDispatchError(command)(
@@ -4280,11 +4328,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4328 sourceProjection,
4329 sourceRun,
4330 sourceProviderThread,
4283 - sourceTokenUsage: providerTurnForRun(sourceProjection, sourceRun)?.tokenUsage,
4284 - canonicalSourcePoint: contextSourcePointForRun(sourceProjection, sourceRun),
4331 + sourceTokenUsage:
4332 + sourceRun === null
4333 + ? undefined
4334 + : providerTurnForRun(sourceProjection, sourceRun)?.tokenUsage,
4335 + canonicalSourcePoint:
4336 + sourceRun === null
4337 + ? { threadId: sourceProjection.thread.id }
4338 + : contextSourcePointForRun(sourceProjection, sourceRun),
4339 transferId,
4340 targetThreadId: command.targetThreadId,
4341 ...(command.title === undefined ? {} : { title: command.title }),
4342 + ...(command.sideChat ? { sideChat: true } : {}),
4343 createdBy: command.createdBy,
4344 creationSource: command.creationSource,
4345 createdAt: now,
@@ -4301,7 +4356,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4356 yield* emitEvent({
4357 type: "context-transfer.created",
4358 threadId: command.targetThreadId,
4304 - providerInstanceId: sourceRun.providerInstanceId,
4359 + providerInstanceId: transfer.sourceProviderInstanceId ?? targetThread.providerInstanceId,
4360 occurredAt: now,
4361 payload: transfer,
4362 });
@@ -4361,6 +4416,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4416 cause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`,
4417 });
4418 }
4419 + // Queued runs cannot consume merge-back context. Refuse under the target's
4420 + // command lock before a pending transfer can block its ordinary messages.
4421 + if (targetProjection.runs.some((run) => isActiveRun(run) || run.status === "queued")) {
4422 + return yield* new OrchestratorDispatchError({
4423 + commandId: command.commandId,
4424 + commandType: command.type,
4425 + cause:
4426 + "Finish or stop the target thread's active work and clear its queue before merging back.",
4427 + });
4428 + }
4429 + const otherPendingMergeBack = targetProjection.contextTransfers.some(
4430 + (transfer) =>
4431 + transfer.type === "merge_back" &&
4432 + transfer.status === "pending" &&
4433 + transfer.targetThreadId === command.targetThreadId &&
4434 + transfer.sourceThreadId !== command.sourceThreadId,
4435 + );
4436 + if (otherPendingMergeBack) {
4437 + return yield* new OrchestratorDispatchError({
4438 + commandId: command.commandId,
4439 + commandType: command.type,
4440 + cause: `Thread ${command.targetThreadId} already has pending context from another side chat or fork. Send a message there first.`,
4441 + });
4442 + }
4443
4444 const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);
4445 if (sourceRun === null) {
@@ -4392,17 +4471,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4471 });
4472 }
4473
4395 - // Queued runs cannot consume merge-back context. Refuse under the target's
4396 - // command lock before a pending transfer can block its ordinary messages.
4397 - if (targetProjection.runs.some((run) => isBlockingRun(run) || run.status === "queued")) {
4398 - return yield* new OrchestratorDispatchError({
4399 - commandId: command.commandId,
4400 - commandType: command.type,
4401 - cause:
4402 - "Finish or stop the target thread's active work and clear its queue before merging back.",
4403 - });
4404 - }
4405 -
4474 const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun);
4475 const now = command.createdAt ?? (yield* DateTime.now);
4476 const emitEvent = emit(events, command);
@@ -5652,7 +5720,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5720 const activeProviderThread = projection.providerThreads.find(
5721 (candidate) => candidate.id === projection.thread.activeProviderThreadId,
5722 );
5655 - const activeRun = projection.runs.find(isBlockingRun);
5723 + const activeRun = projection.runs.find(isActiveRun);
5724 // A message queued during worktree setup can arrive after that setup failed
5725 // without a worktree. It waits, held, like the messages queued before the
5726 // failure, instead of starting in the project checkout.
@@ -6432,8 +6500,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6500 sourceProjection.attempts.find((candidate) => candidate.id === sourceRun.activeAttemptId)
6501 ?.providerTurnId ??
6502 undefined);
6503 + const sideChatFork =
6504 + pendingForkTransfer !== undefined && projection.thread.lineage.sideChat === true;
6505 + // Opened during the parent's first turn: the digest is the whole context.
6506 + const sideChatWithoutSource =
6507 + sideChatFork && pendingForkTransfer.sourcePoint.runId === undefined;
6508 if (pendingForkTransfer !== undefined) {
6436 - if (sourceRun === null || sourceProviderThread === undefined) {
6509 + if (!sideChatWithoutSource && (sourceRun === null || sourceProviderThread === undefined)) {
6510 return yield* new OrchestratorDispatchError({
6511 commandId: command.commandId,
6512 commandType: command.type,
@@ -6498,6 +6571,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6571 }),
6572 ),
6573 );
6574 + const sourceRunsAfterFork =
6575 + sourceProjection === null
6576 + ? []
6577 + : sourceProjection.runs.filter(
6578 + (candidate) => sourceRun === null || candidate.ordinal > sourceRun.ordinal,
6579 + );
6580 const forkExecution =
6581 pendingForkTransfer === undefined || sourceRun === null
6582 ? null
@@ -6512,6 +6591,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6591 hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",
6592 sourceRunStatus: sourceRun.status,
6593 fromSpecificTurn: sourceRun !== null,
6594 + sourceBusy: sourceRunsAfterFork.some(isActiveRun),
6595 }),
6596 );
6597 const canResolveForkNatively = forkExecution === "native_fork";
@@ -6568,12 +6648,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6648 const portableForkItems =
6649 !requiresPortableFork || sourceProjection === null || sourceRun === null
6650 ? []
6571 - : yield* readHandoffItems(sourceProjection.thread.id, [
6572 - ...sourceProjection.runs
6573 - .filter((run) => run.ordinal <= sourceRun.ordinal)
6574 - .map((run) => run.id),
6575 - ...(sourceProjection.thread.historyOrigin === "v1_import" ? [null] : []),
6576 - ]);
6651 + : yield* readForkHistoryItems(projectionStore, sourceProjection, sourceRun).pipe(
6652 + Effect.mapError(
6653 + (cause) =>
6654 + new OrchestratorProjectionError({ threadId: sourceProjection.thread.id, cause }),
6655 + ),
6656 + );
6657 const portableForkHandoff =
6658 !requiresPortableFork ||
6659 pendingForkTransfer === undefined ||
@@ -6606,6 +6686,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6686 }),
6687 ),
6688 );
6689 + // Without a source run the digest covers the parent's whole history: inherited fork rows
6690 + // first, so the cap truncates them first, then imported and run items.
6691 + const sideChatParentRunIds = [
6692 + // Queued messages have not reached the main thread yet.
6693 + ...sourceRunsAfterFork.filter((run) => run.status !== "queued").map((run) => run.id),
6694 + ...(sourceRun === null && sourceProjection?.thread.historyOrigin === "v1_import"
6695 + ? [null]
6696 + : []),
6697 + ];
6698 + const sideChatParentItems =
6699 + !sideChatFork || sourceProjection === null
6700 + ? []
6701 + : [
6702 + ...(sideChatWithoutSource ? yield* readInheritedItems(sourceProjection.thread) : []),
6703 + ...(sideChatParentRunIds.length === 0
6704 + ? []
6705 + : visibleConversationItems(
6706 + sourceProjection,
6707 + yield* readHandoffItems(sourceProjection.thread.id, sideChatParentRunIds),
6708 + )),
6709 + ];
6710 + // The framing note goes in even when the parent has no activity after the fork point.
6711 + const sideChatContextHandoff =
6712 + !sideChatFork || pendingForkTransfer === undefined || sourceProjection === null
6713 + ? null
6714 + : yield* contextHandoffService
6715 + .prepareSideChatContext({
6716 + threadId: command.threadId,
6717 + parentThreadId: sourceProjection.thread.id,
6718 + targetRunId: runId,
6719 + transferId: pendingForkTransfer.id,
6720 + toProviderThreadId: ensuredProviderThread.id,
6721 + fromProviderInstanceId:
6722 + pendingForkTransfer.sourceProviderInstanceId ?? modelSelection.instanceId,
6723 + toProviderInstanceId: modelSelection.instanceId,
6724 + coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, sideChatParentItems),
6725 + parentItems: sideChatParentItems,
6726 + createdAt: now,
6727 + })
6728 + .pipe(mapDispatchError(command));
6729 const requiresFullProviderSwitchContext =
6730 isProviderSwitch && pendingMergeBackTransfer !== undefined;
6731 const targetLastCompletedRun =
@@ -6722,9 +6842,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6842 lastRunOrdinal: ordinal,
6843 handoffIds: [
6844 ...ensuredProviderThread.handoffIds,
6725 - ...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(
6726 - (handoff) => (handoff === null ? [] : [handoff.id]),
6727 - ),
6845 + ...[
6846 + portableForkHandoff,
6847 + sideChatContextHandoff,
6848 + providerSwitchHandoff,
6849 + legacyImportRecoveryHandoff,
6850 + ].flatMap((handoff) => (handoff === null ? [] : [handoff.id])),
6851 ],
6852 updatedAt: now,
6853 };
@@ -6790,11 +6913,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6913 const mergeBackDeltaItems =
6914 mergeBackSourceProjection === null || mergeBackSourceRun === null
6915 ? []
6793 - : yield* readHandoffItems(
6794 - mergeBackSourceProjection.thread.id,
6795 - mergeBackSourceProjection.runs
6796 - .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)
6797 - .map((run) => run.id),
6916 + : visibleConversationItems(
6917 + mergeBackSourceProjection,
6918 + yield* readHandoffItems(
6919 + mergeBackSourceProjection.thread.id,
6920 + mergeBackSourceProjection.runs
6921 + .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)
6922 + .map((run) => run.id),
6923 + ),
6924 );
6925 const mergeBackHandoff =
6926 pendingMergeBackTransfer === undefined ||
@@ -7027,12 +7153,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7153 strategy: "native_fork",
7154 providerThreadRef: providerThread.nativeThreadRef,
7155 };
7156 + const portableForkContext =
7157 + portableForkHandoff ?? (sideChatWithoutSource ? sideChatContextHandoff : null);
7158 const portableForkResolution: OrchestrationV2ContextTransferResolution | null =
7031 - pendingForkTransfer === undefined || portableForkHandoff === null
7159 + pendingForkTransfer === undefined || portableForkContext === null
7160 ? null
7161 : {
7162 strategy: "portable_context",
7035 - contextHandoffId: portableForkHandoff.id,
7163 + contextHandoffId: portableForkContext.id,
7164 };
7165 const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =
7166 pendingMergeBackTransfer === undefined || mergeBackHandoff === null
@@ -7095,6 +7223,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7223 payload: portableForkHandoff,
7224 });
7225 }
7226 + if (sideChatContextHandoff !== null) {
7227 + yield* emitEvent({
7228 + type: "context-handoff.updated",
7229 + threadId: command.threadId,
7230 + runId,
7231 + providerInstanceId: modelSelection.instanceId,
7232 + occurredAt: now,
7233 + payload: sideChatContextHandoff,
7234 + });
7235 + }
7236 if (legacyImportRecoveryHandoff !== null) {
7237 yield* emitEvent({
7238 type: "context-handoff.updated",
@@ -7354,7 +7492,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7492 const parentRun = parentProjection.runs.find(
7493 (candidate) => candidate.id === command.parentRunId,
7494 );
7357 - if (parentRun === undefined || !isBlockingRun(parentRun)) {
7495 + if (parentRun === undefined || !isActiveRun(parentRun)) {
7496 return yield* new OrchestratorDispatchError({
7497 commandId: command.commandId,
7498 commandType: command.type,
@@ -7658,7 +7796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7796 );
7797 if (original === undefined || original.result === null) return;
7798 const owner =
7661 - parent.runs.filter(isBlockingRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??
7799 + parent.runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??
7800 latestExecutedRun(parent.runs);
7801 if (owner === null || owner.rootNodeId === null) return;
7802 const now = message.createdAt;
@@ -7785,7 +7923,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7923 const parentRun = parentProjection.runs.find(
7924 (candidate) => candidate.id === command.parentRunId,
7925 );
7788 - if (parentRun === undefined || !isBlockingRun(parentRun) || parentRun.rootNodeId === null) {
7926 + if (parentRun === undefined || !isActiveRun(parentRun) || parentRun.rootNodeId === null) {
7927 return yield* new OrchestratorDispatchError({
7928 commandId: command.commandId,
7929 commandType: command.type,
@@ -8507,7 +8645,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8645 }
8646 if (
8647 existing === undefined &&
8510 - (!isBlockingRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))
8648 + (!isActiveRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))
8649 ) {
8650 return yield* new OrchestratorDispatchError({
8651 commandId: command.commandId,
@@ -9916,7 +10054,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10054 cause: `Run ${command.runId} has no failed workspace preparation to retry.`,
10055 });
10056 }
9919 - if (projection.runs.some((run) => run.id !== state.run.id && isBlockingRun(run))) {
10057 + if (projection.runs.some((run) => run.id !== state.run.id && isActiveRun(run))) {
10058 return yield* new OrchestratorDispatchError({
10059 commandId: command.commandId,
10060 commandType: command.type,
@@ -11416,7 +11554,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11554 continue;
11555 const idle =
11556 idleChildren.get(task.childThreadId) ??
11419 - (!child.runs.some((run) => run.status === "queued" || isBlockingRun(run)) &&
11557 + (!child.runs.some((run) => run.status === "queued" || isActiveRun(run)) &&
11558 !child.providerThreads.some(
11559 (thread) =>
11560 thread.status === "active" || (thread.pendingBackgroundTasks?.length ?? 0) > 0,
@@ -12689,6 +12827,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12827
12828 const dispatchOnce = Effect.fn("orchestrationV2.dispatch.once")(function* (
12829 command: OrchestrationV2ServerCommand,
12830 + sideChatIds: ReadonlyArray<ThreadId>,
12831 ): Effect.fn.Return<
12832 {
12833 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
@@ -12755,31 +12894,64 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12894 break;
12895 }
12896 case "thread.delete": {
12758 - const projection = yield* projectionStore
12759 - .getThreadRecords(command.threadId, [
12760 - "runs",
12761 - "attempts",
12762 - "nodes",
12763 - "runtimeRequests",
12764 - "subagents",
12765 - "providerSessions",
12766 - ])
12767 - .pipe(
12768 - Effect.mapError(
12769 - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
12770 - ),
12897 + const now = yield* DateTime.now;
12898 + const planDeletion = Effect.fn("Orchestrator.planDeletion")(function* (
12899 + deletion: typeof command,
12900 + ) {
12901 + const projection = yield* projectionStore
12902 + .getThreadRecords(deletion.threadId, [
12903 + "runs",
12904 + "attempts",
12905 + "nodes",
12906 + "runtimeRequests",
12907 + "subagents",
12908 + "providerSessions",
12909 + ])
12910 + .pipe(
12911 + Effect.mapError(
12912 + (cause) => new OrchestratorProjectionError({ threadId: deletion.threadId, cause }),
12913 + ),
12914 + );
12915 + return yield* mapDispatchError(command)(
12916 + planThreadDeletion({
12917 + command: deletion,
12918 + projection,
12919 + attachmentIds: yield* projectionStore
12920 + .getThreadAttachmentIds(deletion.threadId)
12921 + .pipe(mapDispatchError(command)),
12922 + now,
12923 + idAllocator,
12924 + }),
12925 );
12772 - return yield* mapDispatchError(command)(
12773 - planThreadDeletion({
12774 - command,
12775 - projection,
12776 - attachmentIds: yield* projectionStore
12777 - .getThreadAttachmentIds(command.threadId)
12778 - .pipe(mapDispatchError(command)),
12779 - now: yield* DateTime.now,
12780 - idAllocator,
12781 - }),
12782 - );
12926 + });
12927 + // Checked under the thread lock: a message sent since the client looked keeps the thread.
12928 + if (command.onlyIfUnused === true) {
12929 + const usage = yield* projectionStore
12930 + .getThreadRecords(command.threadId, ["runs", "messages"])
12931 + .pipe(
12932 + Effect.mapError(
12933 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
12934 + ),
12935 + );
12936 + if (usage.runs.length > 0 || usage.messages.length > 0) {
12937 + return { events: [], effects: [] };
12938 + }
12939 + }
12940 + // The dispatch wrapper holds each side chat's lock, so none can commit after this plan.
12941 + const plans = [
12942 + yield* planDeletion(command),
12943 + ...(yield* Effect.forEach(sideChatIds, (threadId) =>
12944 + planDeletion({
12945 + ...command,
12946 + commandId: CommandId.make(`${command.commandId}:side-chat:${threadId}`),
12947 + threadId,
12948 + }),
12949 + )),
12950 + ];
12951 + return {
12952 + events: plans.flatMap((plan) => plan.events),
12953 + effects: plans.flatMap((plan) => plan.effects),
12954 + };
12955 }
12956 case "thread.archive":
12957 case "thread.unarchive":
@@ -12943,7 +13115,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13115 selectedMessage === undefined ||
13116 selectedMessage.delegatedCompletion !== undefined ||
13117 selectedMessage.notification !== undefined ||
12946 - projection.runs.some(isBlockingRun)
13118 + projection.runs.some(isActiveRun)
13119 ) {
13120 return yield* new OrchestratorDispatchError({
13121 commandId: command.commandId,
@@ -13067,8 +13239,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13239 };
13240 });
13241
13242 + /** `sideChatIds` are the live side chats a `thread.delete` cascades to, read under their locks. */
13243 const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* (
13244 command: OrchestrationV2ServerCommand,
13245 + sideChatIds: ReadonlyArray<ThreadId> = [],
13246 ): Effect.fn.Return<OrchestratorV2DispatchResult, OrchestratorV2Error> {
13247 yield* Effect.annotateCurrentSpan({
13248 "orchestration_v2.command_id": command.commandId,
@@ -13144,7 +13318,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13318 if (shell !== null) yield* refuseAboveDispatchModeLimit(command, threadId, shell);
13319 }
13320
13147 - const plan = yield* dispatchOnce(command).pipe(
13321 + const plan = yield* dispatchOnce(command, sideChatIds).pipe(
13322 Effect.filterOrFail(
13323 (planned) =>
13324 planned.events.length > 0 ||
@@ -13153,7 +13327,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13327 command.type === "thread.stop" ||
13328 command.type === "subagent.stop" ||
13329 // Closing a share again, or after it ended, is not an error.
13156 - command.type === "thread.guest-share.close",
13330 + command.type === "thread.guest-share.close" ||
13331 + (command.type === "thread.delete" && command.onlyIfUnused === true),
13332 (_planned) =>
13333 new OrchestratorDispatchError({
13334 commandId: command.commandId,
@@ -13295,6 +13470,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13470 commandThreadId(command),
13471 dispatchWithReceiptEffect(command),
13472 );
13473 + // A parent's lock comes before its side chats' locks, so a delete cascade and a side chat
13474 + // fork or command never interleave. A fork from a side chat or onto an existing thread would
13475 + // invert that order; dispatch rejects both, so they skip the source lock.
13476 + if (
13477 + command.type === "thread.fork" &&
13478 + command.sideChat === true &&
13479 + command.sourceThreadId !== command.targetThreadId
13480 + ) {
13481 + const source = yield* findThread(command.sourceThreadId);
13482 + const target = yield* findThread(command.targetThreadId);
13483 + return yield* source === null || source.lineage.sideChat === true || target !== null
13484 + ? dispatch
13485 + : threadDispatch.withLock(command.sourceThreadId, dispatch);
13486 + }
13487 + if (command.type === "thread.delete")
13488 + return yield* threadDispatch.withLock(
13489 + command.threadId,
13490 + liveSideChatIds(command.threadId).pipe(
13491 + Effect.flatMap((sideChatIds) =>
13492 + sideChatIds.reduce(
13493 + (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked),
13494 + dispatchWithReceiptEffect(command, sideChatIds),
13495 + ),
13496 + ),
13497 + ),
13498 + );
13499 // Answering a message-mode question can also start a follow-up.
13500 if (
13501 command.type !== "runtime-request.respond" &&
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+54 -37
@@ -5086,13 +5086,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
5086 }),
5087 );
5088
5089 - it.effect("counts imported runless history inherited by fork shells", () =>
5089 + it.effect("counts history inherited by fork shells, but not by side chats", () =>
5090 Effect.gen(function* () {
5091 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
5092 const now = yield* DateTime.now;
5093 const projectId = ProjectId.make("project:projection-imported-fork-shell");
5094 const sourceThreadId = ThreadId.make("thread:projection-imported-fork-shell:source");
5095 const targetThreadId = ThreadId.make("thread:projection-imported-fork-shell:target");
5096 + const sideChatThreadId = ThreadId.make("thread:projection-imported-fork-shell:side-chat");
5097 const sourceRunId = RunId.make("run:projection-imported-fork-shell:source");
5098 const rootNodeId = NodeId.make("node:projection-imported-fork-shell:source");
5099
@@ -5130,43 +5131,49 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
5131 deletedAt: null,
5132 },
5133 });
5133 - yield* projectionStore.apply({
5134 - id: EventId.make("event:projection-imported-fork-shell:target-thread"),
5135 - type: "thread.created",
5136 - threadId: targetThreadId,
5137 - occurredAt: now,
5138 - payload: {
5139 - createdBy: "user",
5140 - creationSource: "web",
5141 - id: targetThreadId,
5142 - projectId,
5143 - title: "Imported fork target",
5144 - providerInstanceId,
5145 - modelSelection,
5146 - runtimeMode: "full-access",
5147 - interactionMode: "default",
5148 - branch: null,
5149 - worktreePath: null,
5150 - activeProviderThreadId: null,
5151 - lineage: {
5152 - parentThreadId: sourceThreadId,
5153 - relationshipToParent: "fork",
5154 - rootThreadId: sourceThreadId,
5155 - },
5156 - forkedFrom: {
5157 - type: "run",
5158 - threadId: sourceThreadId,
5159 - runId: sourceRunId,
5134 + for (const [threadId, sideChat] of [
5135 + [targetThreadId, false],
5136 + [sideChatThreadId, true],
5137 + ] as const) {
5138 + yield* projectionStore.apply({
5139 + id: EventId.make(`event:projection-imported-fork-shell:created:${threadId}`),
5140 + type: "thread.created",
5141 + threadId,
5142 + occurredAt: now,
5143 + payload: {
5144 + createdBy: "user",
5145 + creationSource: "web",
5146 + id: threadId,
5147 + projectId,
5148 + title: "Imported fork target",
5149 + providerInstanceId,
5150 + modelSelection,
5151 + runtimeMode: "full-access",
5152 + interactionMode: "default",
5153 + branch: null,
5154 + worktreePath: null,
5155 + activeProviderThreadId: null,
5156 + lineage: {
5157 + parentThreadId: sourceThreadId,
5158 + relationshipToParent: "fork",
5159 + rootThreadId: sourceThreadId,
5160 + sideChat,
5161 + },
5162 + forkedFrom: {
5163 + type: "run",
5164 + threadId: sourceThreadId,
5165 + runId: sourceRunId,
5166 + },
5167 + createdAt: now,
5168 + updatedAt: now,
5169 + archivedAt: null,
5170 + settledOverride: null,
5171 + settledAt: null,
5172 + lastVisitedAt: null,
5173 + deletedAt: null,
5174 },
5161 - createdAt: now,
5162 - updatedAt: now,
5163 - archivedAt: null,
5164 - settledOverride: null,
5165 - settledAt: null,
5166 - lastVisitedAt: null,
5167 - deletedAt: null,
5168 - },
5169 - });
5175 + });
5176 + }
5177 yield* projectionStore.apply({
5178 id: EventId.make("event:projection-imported-fork-shell:source-run"),
5179 type: "run.created",
@@ -5235,6 +5242,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
5242 assert.equal(targetShell.itemCount, 0);
5243 assert.equal(targetShell.visibleItemCount, 4);
5244 assert.equal(targetProjection.visibleTurnItems.length, 4);
5245 +
5246 + const sideChatShell = shell.threads.find((thread) => thread.id === sideChatThreadId);
5247 + assert.equal(sideChatShell?.visibleItemCount, 0);
5248 + const sideChatProjection = yield* projectionStore.getThreadProjection(sideChatThreadId);
5249 + assert.deepEqual(sideChatProjection.visibleTurnItems, []);
5250 + const sideChatTimeline = yield* projectionStore.getTimelinePage(sideChatThreadId, {
5251 + limit: 20,
5252 + view: "activity",
5253 + });
5254 + assert.equal(sideChatTimeline.totalItems, 0);
5255 }),
5256 );
5257
apps/server/src/orchestration-v2/ProjectionStore.ts
+32 -11
@@ -256,6 +256,8 @@ export interface ProjectionCheckpointCaptureContext {
256 readonly scope: OrchestrationV2CheckpointScope | undefined;
257 readonly providerThread: OrchestrationV2ProviderThread | undefined;
258 readonly readyCheckpointOrdinals: ReadonlyArray<number>;
259 + /** Side chats share their parent's worktree and never snapshot it. */
260 + readonly sideChat: boolean;
261 }
262
263 const RollbackTargetAttempts = Schema.Array(
@@ -1335,14 +1337,21 @@ function visibleTurnItemsThroughRun(input: {
1337 return [...inheritedPrefix, ...localPrefix];
1338 }
1339
1340 +// Side chats show only their own rows; the fork transfer carries the parent's context to the model.
1341 +function inheritedRunFork(thread: Pick<OrchestrationV2AppThread, "forkedFrom" | "lineage">) {
1342 + return thread.forkedFrom?.type === "run" && thread.lineage.sideChat !== true
1343 + ? thread.forkedFrom
1344 + : null;
1345 +}
1346 +
1347 function buildVisibleTurnItems(input: {
1348 readonly projection: OrchestrationV2ThreadProjection;
1349 readonly sourceProjection: OrchestrationV2ThreadProjection | null;
1350 readonly inheritedRowCount?: number;
1351 }): Array<OrchestrationV2ProjectedTurnItem> {
1343 - const forkedFrom = input.projection.thread.forkedFrom;
1352 + const forkedFrom = inheritedRunFork(input.projection.thread);
1353 if (
1345 - forkedFrom?.type !== "run" ||
1354 + forkedFrom === null ||
1355 (input.sourceProjection === null && input.inheritedRowCount === undefined)
1356 ) {
1357 return localVisibleTurnItems(input.projection);
@@ -1721,8 +1730,8 @@ function visibleItemCountForShell(input: {
1730 return 0;
1731 }
1732
1724 - const forkedFrom = state.thread.forkedFrom;
1725 - if (forkedFrom?.type !== "run") {
1733 + const forkedFrom = inheritedRunFork(state.thread);
1734 + if (forkedFrom === null) {
1735 return state.itemCount;
1736 }
1737
@@ -1736,9 +1745,8 @@ function visibleItemCountForShell(input: {
1745 return state.itemCount;
1746 }
1747
1739 - const sourceForkedFrom = sourceState.thread.forkedFrom;
1748 const inheritedPrefixCount =
1741 - sourceForkedFrom?.type === "run"
1749 + inheritedRunFork(sourceState.thread) !== null
1750 ? visibleItemCountForShell({
1751 threadId: sourceState.thread.id,
1752 statesByThreadId: input.statesByThreadId,
@@ -3628,8 +3636,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3636 ? ["runs", "attempts", "turnItems"]
3637 : undefined,
3638 );
3631 - const forkedFrom = projection.thread.forkedFrom;
3632 - if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
3639 + const forkedFrom = inheritedRunFork(projection.thread);
3640 + if (forkedFrom === null || seenThreadIds.has(forkedFrom.threadId)) {
3641 return withLocalVisibleTurnItems(projection);
3642 }
3643
@@ -4305,6 +4313,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4313 message_id IN (SELECT json_extract(payload_json, '$.userMessageId') FROM orchestration_v2_projection_runs
4314 WHERE thread_id = ${threadId} AND run_id = ${runId})
4315 OR (role = 'user' AND lower(trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace})) = '/compact')
4316 + -- Earlier /goal turns defer context too; parseGoalCommand narrows this prefix match.
4317 + OR (role = 'user' AND trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace}) GLOB '/goal*')
4318 ) ORDER BY created_at ASC, message_id ASC
4319 `.pipe(Effect.flatMap(decodeRows(decodeMessagePayload, threadId)));
4320 const conversation = yield* sql<{ present: number }>`
@@ -5064,7 +5074,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5074 sql
5075 .withTransaction(
5076 Effect.gen(function* () {
5067 - yield* requireThread(threadId);
5077 + const threadRows = yield* sql<{ readonly side_chat: number | null }>`
5078 + SELECT json_extract(payload_json, '$.lineage.sideChat') AS side_chat
5079 + FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1`;
5080 + if (threadRows[0] === undefined) {
5081 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
5082 + }
5083 const runRows = yield* sql<PayloadRow>`
5084 SELECT payload_json FROM orchestration_v2_projection_runs
5085 WHERE thread_id = ${threadId} AND run_id = ${target.runId}`;
@@ -5101,6 +5116,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5116 ? undefined
5117 : yield* decodeProviderThreadPayload(providerRows[0].payload_json),
5118 readyCheckpointOrdinals: readyRows.map(({ ordinal }) => ordinal),
5119 + sideChat: threadRows[0].side_chat === 1,
5120 };
5121 }),
5122 )
@@ -5504,8 +5520,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5520 items,
5521 });
5522 const visible = local.filter((row) => isVisible(row.item));
5507 - const fork = records.thread.forkedFrom;
5508 - if (fork?.type !== "run" || seen.has(fork.threadId)) return { records, local, visible };
5523 + const fork = inheritedRunFork(records.thread);
5524 + if (fork === null || seen.has(fork.threadId)) return { records, local, visible };
5525 const source = yield* readTimelineIndex(
5526 fork.threadId,
5527 new Set([...seen, threadId]),
@@ -5865,6 +5881,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5881 t.payload_json,
5882 CASE
5883 WHEN json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
5884 + AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1
5885 THEN json_extract(t.payload_json, '$.forkedFrom.threadId')
5886 ELSE NULL
5887 END AS forked_from_run_source_thread_id,
@@ -6749,6 +6766,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6766 readonly relationship_to_parent: string | null;
6767 readonly parent_thread_id: string | null;
6768 readonly root_thread_id: string;
6769 + readonly side_chat: number | null;
6770 readonly settled_override: string | null;
6771 readonly settled_at: string | null;
6772 readonly pinned_at: string | null;
@@ -6761,6 +6779,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6779 json_extract(t.payload_json, '$.lineage.relationshipToParent') AS relationship_to_parent,
6780 json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id,
6781 json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id,
6782 + json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat,
6783 json_extract(t.payload_json, '$.settledOverride') AS settled_override,
6784 json_extract(t.payload_json, '$.settledAt') AS settled_at,
6785 json_extract(t.payload_json, '$.pinnedAt') AS pinned_at,
@@ -6815,6 +6834,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6834 ? row.relationship_to_parent
6835 : null,
6836 rootThreadId: ThreadId.make(row.root_thread_id),
6837 + ...(row.side_chat === null ? {} : { sideChat: row.side_chat === 1 }),
6838 },
6839 settledOverride:
6840 row.settled_override === "settled" || row.settled_override === "active"
@@ -6850,6 +6870,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6870 WHERE t.deleted_at IS NULL
6871 AND json_extract(t.payload_json, '$.archivedAt') IS NULL
6872 AND json_extract(t.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent'
6873 + AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1
6874 AND json_extract(t.payload_json, '$.settledOverride') = 'settled'
6875 AND json_extract(t.payload_json, '$.settledAt') IS NOT NULL${
6876 projectIds === undefined ? sql`` : sql` AND t.project_id IN ${sql.in(projectIds)}`
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+322 -54
@@ -3,6 +3,8 @@ import { expect, it, vi } from "vite-plus/test";
3 import { it as effectIt } from "@effect/vitest";
4 import {
5 CheckpointScopeId,
6 + ContextHandoffId,
7 + ContextTransferId,
8 GitCommandError,
9 MessageId,
10 NodeId,
@@ -40,6 +42,7 @@ import * as ProjectService from "../project/ProjectService.ts";
42 import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
43 import * as ServerSettings from "../serverSettings.ts";
44 import * as ContextHandoffService from "./ContextHandoffService.ts";
45 +import { withInlineContext } from "./ContextHandoffDelivery.ts";
46 import * as EventSink from "./EventSink.ts";
47 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
@@ -96,6 +99,7 @@ function startWithMissingWorktree(
99 projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
100 branch: "feature/restore",
101 worktreePath,
102 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
103 },
104 runs: [
105 {
@@ -286,6 +290,16 @@ function makeLocalCommandHarness(input: {
290 readonly interruptFailure?: boolean;
291 readonly interruptCurrentRun?: boolean;
292 };
293 + /**
294 + * A side chat whose context targets this run, an earlier run that failed or was cancelled before
295 + * the provider, or an earlier run that delivered it. `nativeForkFrom` plans a native fork of the
296 + * parent. `switchedProvider` puts the earlier run and its context on another provider thread.
297 + */
298 + readonly sideChat?: {
299 + readonly contextRun: "current" | "failed" | "cancelled" | "delivered";
300 + readonly nativeForkFrom?: "idle" | "busy";
301 + readonly switchedProvider?: boolean;
302 + };
303 }) {
304 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
305 const threadId = ThreadId.make("thread-native-account-command");
@@ -354,6 +368,7 @@ function makeLocalCommandHarness(input: {
368 projectId: ProjectId.make("project-native-account-command"),
369 branch: input.worktreePath === undefined ? null : "feature/restore",
370 worktreePath: input.worktreePath ?? null,
371 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
372 } as OrchestrationV2ThreadProjection["thread"],
373 runs: [
374 ...(input.previousNativeSession
@@ -458,6 +473,139 @@ function makeLocalCommandHarness(input: {
473 checkpoints: [],
474 updatedAt: now,
475 };
476 + const parentThreadId = ThreadId.make("side-chat-parent");
477 + const parentRunId = RunId.make("side-chat-parent-run");
478 + const parentProviderThread = {
479 + ...providerThread,
480 + id: ProviderThreadId.make("side-chat-parent-provider-thread"),
481 + appThreadId: parentThreadId,
482 + nativeThreadRef: {
483 + driver: providerThread.driver,
484 + nativeId: "side-chat-parent-native",
485 + strength: "strong" as const,
486 + },
487 + };
488 + const parentRecords = {
489 + ...projection,
490 + thread: { ...projection.thread, id: parentThreadId },
491 + runs: [
492 + {
493 + ...run,
494 + id: parentRunId,
495 + threadId: parentThreadId,
496 + ordinal: 1,
497 + providerThreadId: parentProviderThread.id,
498 + activeAttemptId: null,
499 + status: "completed" as const,
500 + completedAt: now,
501 + },
502 + ...(input.sideChat?.nativeForkFrom === "busy"
503 + ? [
504 + {
505 + ...run,
506 + id: RunId.make("side-chat-parent-busy-run"),
507 + threadId: parentThreadId,
508 + ordinal: 2,
509 + providerThreadId: parentProviderThread.id,
510 + status: "running" as const,
511 + },
512 + ]
513 + : []),
514 + ],
515 + providerThreads: [parentProviderThread],
516 + attempts: [],
517 + providerTurns: [],
518 + turnItems: [],
519 + };
520 + if (input.sideChat !== undefined) {
521 + const earlierRunId = RunId.make("side-chat-earlier-run");
522 + projection = {
523 + ...projection,
524 + thread: {
525 + ...projection.thread,
526 + runtimeMode: "full-access",
527 + lineage: {
528 + parentThreadId,
529 + relationshipToParent: "fork",
530 + rootThreadId: parentThreadId,
531 + sideChat: true,
532 + },
533 + },
534 + runs:
535 + input.sideChat.contextRun === "current"
536 + ? projection.runs
537 + : [
538 + {
539 + ...run,
540 + id: earlierRunId,
541 + ordinal: 1,
542 + userMessageId: MessageId.make("side-chat-earlier-message"),
543 + activeAttemptId: RunAttemptId.make("side-chat-earlier-attempt"),
544 + ...(input.sideChat.switchedProvider
545 + ? { providerThreadId: oldProviderThreadId }
546 + : {}),
547 + status:
548 + input.sideChat.contextRun === "delivered"
549 + ? "completed"
550 + : input.sideChat.contextRun,
551 + completedAt: now,
552 + },
553 + run,
554 + ],
555 + contextTransfers:
556 + input.sideChat.nativeForkFrom === undefined
557 + ? []
558 + : [
559 + {
560 + id: ContextTransferId.make("side-chat-fork"),
561 + type: "fork",
562 + sourceThreadId: parentThreadId,
563 + targetThreadId: threadId,
564 + sourcePoint: { threadId: parentThreadId, runId: parentRunId },
565 + basePoint: null,
566 + sourceProviderInstanceId: newInstanceId,
567 + targetProviderInstanceId: newInstanceId,
568 + targetRunId: runId,
569 + status: "pending",
570 + resolution: null,
571 + createdBy: "user",
572 + error: null,
573 + createdAt: now,
574 + updatedAt: now,
575 + consumedAt: null,
576 + },
577 + ],
578 + contextHandoffs: [
579 + {
580 + id: ContextHandoffId.make("side-chat-context"),
581 + transferId: ContextTransferId.make("side-chat-fork"),
582 + threadId,
583 + targetRunId: input.sideChat.contextRun === "current" ? runId : earlierRunId,
584 + fromProviderThreadIds: [],
585 + toProviderThreadId: input.sideChat.switchedProvider
586 + ? oldProviderThreadId
587 + : providerThreadId,
588 + coveredRunOrdinals: { from: 1, to: 1 },
589 + strategy: "manual_context",
590 + status: "ready",
591 + summaryMessageId: null,
592 + summaryText: "SIDE_CHAT_CONTEXT",
593 + createdByProviderInstanceId: null,
594 + createdAt: now,
595 + updatedAt: now,
596 + ...(input.sideChat.contextRun === "delivered"
597 + ? {
598 + delivery: {
599 + nativeThreadId: "side-chat-native",
600 + status: "inline" as const,
601 + itemIds: [],
602 + },
603 + }
604 + : {}),
605 + },
606 + ],
607 + };
608 + }
609 if ("historyReadFailureAfterFallback" in input) {
610 const nativeThreadRef = {
611 driver: providerThread.driver,
@@ -577,55 +725,78 @@ function makeLocalCommandHarness(input: {
725 ),
726 ensureThread: () => Effect.succeed(providerThread),
727 };
728 + const providerSession = {
729 + id: providerSessionId,
730 + driver: providerThread.driver,
731 + providerInstanceId: newInstanceId,
732 + status: "ready",
733 + cwd: "/tmp/native-account-command",
734 + model: null,
735 + capabilities: CodexProviderCapabilitiesV2,
736 + createdAt: now,
737 + updatedAt: now,
738 + lastError: null,
739 + };
740 + const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void);
741 + const sideChatThread = {
742 + ...providerThread,
743 + nativeThreadRef: {
744 + driver: providerThread.driver,
745 + nativeId: "side-chat-native",
746 + strength: "strong" as const,
747 + },
748 + };
749 + const forkThread = vi.fn(() => Effect.succeed(sideChatThread));
750 + const sideChatSession = {
751 + driver: providerThread.driver,
752 + providerSession,
753 + ensureThread: () => Effect.succeed(sideChatThread),
754 + resumeThread: () => Effect.succeed(sideChatThread),
755 + forkThread,
756 + startTurn,
757 + };
758 const open = vi.fn(() =>
581 - input.interruptOpen === true
582 - ? Effect.interrupt
583 - : "historyReadFailureAfterFallback" in input
584 - ? Effect.succeed(resumeFallbackSession as never)
585 - : "ensureThreadFailure" in input
586 - ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
587 - : "openFailure" in input
588 - ? Effect.sync(() => {
589 - if (input.interruptRunBeforeOpenFailure === true) interruptRun();
590 - }).pipe(
591 - Effect.andThen(
592 - Effect.fail(
593 - new ProviderSessionManager.ProviderSessionOpenError({
594 - instanceId: newInstanceId,
595 - providerSessionId,
596 - cause: input.openFailure,
597 - }),
759 + input.sideChat !== undefined
760 + ? Effect.succeed(sideChatSession as never)
761 + : input.interruptOpen === true
762 + ? Effect.interrupt
763 + : "historyReadFailureAfterFallback" in input
764 + ? Effect.succeed(resumeFallbackSession as never)
765 + : "ensureThreadFailure" in input
766 + ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
767 + : "openFailure" in input
768 + ? Effect.sync(() => {
769 + if (input.interruptRunBeforeOpenFailure === true) interruptRun();
770 + }).pipe(
771 + Effect.andThen(
772 + Effect.fail(
773 + new ProviderSessionManager.ProviderSessionOpenError({
774 + instanceId: newInstanceId,
775 + providerSessionId,
776 + cause: input.openFailure,
777 + }),
778 + ),
779 ),
599 - ),
600 - )
601 - : input.failReadsAfterRunning === true || input.previousTurn !== undefined
602 - ? Effect.succeed({
603 - driver: providerThread.driver,
604 - providerSession: {
605 - id: providerSessionId,
780 + )
781 + : input.failReadsAfterRunning === true || input.previousTurn !== undefined
782 + ? Effect.succeed({
783 driver: providerThread.driver,
607 - providerInstanceId: newInstanceId,
608 - status: "ready",
609 - cwd: "/tmp/native-account-command",
610 - model: null,
611 - capabilities: CodexProviderCapabilitiesV2,
612 - createdAt: now,
613 - updatedAt: now,
614 - lastError: null,
615 - },
616 - ensureThread: () => Effect.succeed(providerThread),
617 - resumeThread: () => Effect.succeed(projection.providerThreads[0]),
618 - } as never)
619 - : Effect.die("A local command must not open a native session."),
784 + providerSession,
785 + ensureThread: () => Effect.succeed(providerThread),
786 + resumeThread: () => Effect.succeed(projection.providerThreads[0]),
787 + } as never)
788 + : Effect.die("A local command must not open a native session."),
789 );
790 const startRootRun = vi.fn<
791 (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>
623 - >(() =>
624 - input.failReadsAfterRunning === true || input.previousTurn !== undefined
625 - ? Effect.suspend(() =>
626 - providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,
627 - )
628 - : Effect.die("A local command must not start a native turn."),
792 + >((runInput) =>
793 + input.sideChat !== undefined
794 + ? runInput.session.startTurn(runInput as never).pipe(Effect.orDie)
795 + : input.failReadsAfterRunning === true || input.previousTurn !== undefined
796 + ? Effect.suspend(() =>
797 + providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,
798 + )
799 + : Effect.die("A local command must not start a native turn."),
800 );
801 const failReadIfRunning = Effect.suspend(() =>
802 input.failReadsAfterRunning === true &&
@@ -672,13 +843,16 @@ function makeLocalCommandHarness(input: {
843 );
844 const resolveRuntimePolicy = vi.fn(
845 ({ thread }: Parameters<RuntimePolicy.RuntimePolicyV2Shape["resolve"]>[0]) =>
675 - Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command" } as never),
846 + Effect.succeed({
847 + cwd: thread.worktreePath ?? "/tmp/native-account-command",
848 + runtimeMode: thread.runtimeMode,
849 + } as never),
850 );
851 const createWorktree = vi.fn<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>(() =>
852 Effect.succeed({} as never),
853 );
680 - const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(() =>
681 - Effect.succeed(projection),
854 + const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>((id) =>
855 + Effect.succeed(id === parentThreadId ? parentRecords : projection),
856 );
857 const getTurnStartContext = vi.fn(() =>
858 Effect.succeed({
@@ -694,9 +868,30 @@ function makeLocalCommandHarness(input: {
868 Layer.provide(
869 Layer.mergeAll(
870 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({
697 - prepareProviderHandoff: () => Effect.die("history read must fail first"),
871 + prepareProviderHandoff: (handoff) =>
872 + input.sideChat?.nativeForkFrom === undefined
873 + ? Effect.die("history read must fail first")
874 + : Effect.succeed({
875 + ...handoff,
876 + id: ContextHandoffId.make("side-chat-fork-context"),
877 + createdByProviderInstanceId: handoff.toProviderInstanceId,
878 + status: "ready",
879 + summaryMessageId: null,
880 + summaryText: "PARENT_HISTORY",
881 + updatedAt: handoff.createdAt,
882 + }),
883 + }),
884 + Layer.mock(EventSink.EventSinkV2)({
885 + writeIfRunCurrent,
886 + write: ({ events: incoming }) =>
887 + Effect.sync(() => {
888 + for (const event of incoming) {
889 + events.push(event);
890 + projection = ProjectionStore.applyToProjection(projection, event);
891 + }
892 + return [];
893 + }),
894 }),
699 - Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
895 IdAllocator.layer,
896 layerWorktreeLocation(input.worktreesDir),
897 input.fileSystem === undefined
@@ -728,12 +923,14 @@ function makeLocalCommandHarness(input: {
923 ),
924 }),
925 getTurnStartHistory: () =>
731 - Effect.fail(
732 - new ProjectionStore.ProjectionStoreReadError({
733 - threadId,
734 - cause: input.historyReadFailureAfterFallback,
735 - }),
736 - ),
926 + input.sideChat !== undefined
927 + ? Effect.succeed([])
928 + : Effect.fail(
929 + new ProjectionStore.ProjectionStoreReadError({
930 + threadId,
931 + cause: input.historyReadFailureAfterFallback,
932 + }),
933 + ),
934 }),
935 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
936 open,
@@ -767,6 +964,8 @@ function makeLocalCommandHarness(input: {
964 open,
965 writeIfRunCurrent,
966 startRootRun,
967 + startTurn,
968 + forkThread,
969 interruptTurn,
970 tryHandlePromptCommand,
971 events,
@@ -1006,6 +1205,75 @@ effectIt.effect("recovers an abandoned failed turn before continuing its native
1205 }),
1206 );
1207
1208 +effectIt.effect.each([
1209 + { contextRun: "current", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },
1210 + { contextRun: "failed", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },
1211 + { contextRun: "cancelled", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },
1212 + {
1213 + contextRun: "failed",
1214 + switchedProvider: true,
1215 + runtimeMode: "approval-required",
1216 + context: "SIDE_CHAT_CONTEXT",
1217 + },
1218 + { contextRun: "delivered", runtimeMode: "full-access", context: "" },
1219 +] as const)(
1220 + "sends side chat context inline once, for the first turn that reaches the provider: %j",
1221 + ({ runtimeMode, context, ...sideChat }) =>
1222 + Effect.gen(function* () {
1223 + const harness = makeLocalCommandHarness({
1224 + text: "What is the main thread doing?",
1225 + sideChat,
1226 + });
1227 +
1228 + yield* harness.start;
1229 +
1230 + // The turn that delivers the context is clamped; a later one follows the thread's mode.
1231 + expect(harness.open).toHaveBeenCalledWith(
1232 + expect.objectContaining({ runtimePolicy: expect.objectContaining({ runtimeMode }) }),
1233 + );
1234 + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([
1235 + withInlineContext(context, "What is the main thread doing?"),
1236 + ]);
1237 + expect(harness.projection().contextHandoffs).toMatchObject([
1238 + {
1239 + id: "side-chat-context",
1240 + toProviderThreadId: "new-provider-thread",
1241 + delivery: { nativeThreadId: "side-chat-native", status: "inline" },
1242 + },
1243 + ]);
1244 + }),
1245 +);
1246 +
1247 +effectIt.effect.each([
1248 + { nativeForkFrom: "idle", forks: true, transferStatus: "consumed", handoffIds: [] },
1249 + {
1250 + nativeForkFrom: "busy",
1251 + forks: false,
1252 + transferStatus: "resolved_portable",
1253 + handoffIds: ["side-chat-fork-context"],
1254 + },
1255 +] as const)(
1256 + "runs a planned native side chat fork when the parent is $nativeForkFrom",
1257 + ({ nativeForkFrom, forks, transferStatus, handoffIds }) =>
1258 + Effect.gen(function* () {
1259 + const harness = makeLocalCommandHarness({
1260 + text: "What is the main thread doing?",
1261 + sideChat: { contextRun: "current", nativeForkFrom },
1262 + });
1263 +
1264 + yield* harness.start;
1265 +
1266 + expect(harness.forkThread).toHaveBeenCalledTimes(forks ? 1 : 0);
1267 + expect(harness.projection().contextTransfers).toMatchObject([
1268 + { id: "side-chat-fork", status: transferStatus },
1269 + ]);
1270 + expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("PARENT_HISTORY")).toBe(
1271 + !forks,
1272 + );
1273 + expect(harness.projection().providerThreads[0]?.handoffIds).toEqual(handoffIds);
1274 + }),
1275 +);
1276 +
1277 effectIt.effect.each([
1278 { runStatus: "failed", turnStatus: "completed" },
1279 { runStatus: "completed", turnStatus: "completed" },
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+183 -61
@@ -34,6 +34,7 @@ import * as ServerSettings from "../serverSettings.ts";
34 import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
35 import * as EventSink from "./EventSink.ts";
36 import * as ContextHandoffService from "./ContextHandoffService.ts";
37 +import { isActiveRun } from "./CommandPolicy.ts";
38 import {
39 DEFAULT_HANDOFF_TOKEN_CAP,
40 handoffTokenCapConfig,
@@ -43,7 +44,7 @@ import {
44 historicalMessage,
45 latestNativeContextUsage,
46 } from "@t3tools/provider-core/server/handoffBudget";
46 -import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";
47 +import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts";
48 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
49 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
50 import * as ProjectionStore from "./ProjectionStore.ts";
@@ -363,27 +364,40 @@ export const layer: Layer.Layer<
364 .filter((transfer) => transfer.type === "subagent_result")
365 .map((transfer) => transfer.id),
366 );
367 + const isPendingForRun = (handoff: OrchestrationV2ContextHandoff, anyProviderThread = false) =>
368 + handoff.status === "ready" &&
369 + (handoff.targetRunId === run.id ||
370 + ((anyProviderThread || handoff.toProviderThreadId === run.providerThreadId) &&
371 + projection.runs.some(
372 + (source) =>
373 + source.id === handoff.targetRunId &&
374 + (source.status === "failed" ||
375 + source.status === "interrupted" ||
376 + source.status === "cancelled" ||
377 + (source.status === "completed" &&
378 + handoff.delivery === undefined &&
379 + // Compaction and /goal turns defer history to the next turn.
380 + projection.messages.some(
381 + (message) =>
382 + message.id === source.userMessageId &&
383 + (isCompactionCommandMessage(message) || parseGoalCommand(message) !== null),
384 + ))),
385 + )));
386 + const isSideChatHandoff = (handoff: OrchestrationV2ContextHandoff) =>
387 + projection.thread.lineage.sideChat === true &&
388 + ContextHandoffService.isSideChatContextHandoff(handoff);
389 const handoffs = projection.contextHandoffs.filter(
390 (handoff) =>
391 + !isSideChatHandoff(handoff) &&
392 (handoff.transferId == null || !subagentResultTransfers.has(handoff.transferId)) &&
369 - handoff.status === "ready" &&
370 - (handoff.targetRunId === run.id ||
371 - (handoff.toProviderThreadId === run.providerThreadId &&
372 - projection.runs.some(
373 - (source) =>
374 - source.id === handoff.targetRunId &&
375 - (source.status === "failed" ||
376 - source.status === "interrupted" ||
377 - (source.status === "completed" &&
378 - handoff.delivery === undefined &&
379 - // Compaction and /goal turns defer history to the next turn.
380 - projection.messages.some(
381 - (message) =>
382 - message.id === source.userMessageId &&
383 - (isCompactionCommandMessage(message) ||
384 - parseGoalCommand(message) !== null),
385 - ))),
386 - ))),
393 + isPendingForRun(handoff),
394 + );
395 + // Carried forward until a provider turn accepts it, also after a provider switch.
396 + const sideChatHandoff = projection.contextHandoffs.find(
397 + (handoff) =>
398 + isSideChatHandoff(handoff) &&
399 + handoff.delivery === undefined &&
400 + isPendingForRun(handoff, true),
401 );
402 const nativeForkTransfer = projection.contextTransfers.find(
403 (transfer) =>
@@ -675,8 +689,14 @@ export const layer: Layer.Layer<
689 });
690 const { isCurrentAttemptInStatus } = runControls;
691
692 + // A side chat shares its parent's worktree; the turn that gets its context asks before acting.
693 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
679 - thread: projection.thread,
694 + thread:
695 + projection.thread.lineage.sideChat === true &&
696 + (sideChatHandoff !== undefined ||
697 + !projection.runs.some((previous) => previous.ordinal < run.ordinal))
698 + ? { ...projection.thread, runtimeMode: "approval-required" }
699 + : projection.thread,
700 modelSelection: run.modelSelection,
701 });
702 if (!(yield* isCurrentAttemptInStatus("starting"))) return;
@@ -1072,6 +1092,7 @@ export const layer: Layer.Layer<
1092 };
1093 let resumedRetryHandoff: ReadonlyArray<OrchestrationV2ContextHandoff> | undefined;
1094 let resumedHandoffContext: ReturnType<typeof handoffContextForThread> | undefined;
1095 + let portableForkFallback: OrchestrationV2ContextHandoff | undefined;
1096 const loadedProviderThread = yield* Effect.gen(function* () {
1097 if (nativeForkTransfer !== undefined) {
1098 const sourceProjection = yield* projectionStore.getThreadRecords(
@@ -1098,18 +1119,91 @@ export const layer: Layer.Layer<
1119 cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
1120 });
1121 }
1101 - return yield* loadFromProvider(
1102 - session.forkThread({
1103 - sourceProviderThread,
1104 - sourceProviderTurns: sourceProjection.providerTurns,
1105 - targetThreadId: projection.thread.id,
1122 + // Providers refuse to fork a busy thread, so a source that started a turn after
1123 + // dispatch planned this fork gets the portable context dispatch gives a busy source.
1124 + const sourceBusy = sourceProjection.runs.some(
1125 + (candidate) => candidate.ordinal > sourceRun.ordinal && isActiveRun(candidate),
1126 + );
1127 + if (!sourceBusy) {
1128 + return yield* loadFromProvider(
1129 + session.forkThread({
1130 + sourceProviderThread,
1131 + sourceProviderTurns: sourceProjection.providerTurns,
1132 + targetThreadId: projection.thread.id,
1133 + modelSelection: run.modelSelection,
1134 + runtimePolicy: resolvedRuntimePolicy,
1135 + ...(sourceProviderTurn === undefined
1136 + ? {}
1137 + : { providerTurnId: sourceProviderTurn.id }),
1138 + }),
1139 + );
1140 + }
1141 + const sourceItems = yield* ContextHandoffService.readForkHistoryItems(
1142 + projectionStore,
1143 + sourceProjection,
1144 + sourceRun,
1145 + );
1146 + const createdAt = yield* DateTime.now;
1147 + const handoff = yield* contextHandoffService.prepareProviderHandoff({
1148 + threadId: projection.thread.id,
1149 + targetRunId: run.id,
1150 + transferId: nativeForkTransfer.id,
1151 + fromProviderThreadIds: [sourceProviderThread.id],
1152 + toProviderThreadId: providerThread.id,
1153 + fromProviderInstanceId: sourceRun.providerInstanceId,
1154 + toProviderInstanceId: run.providerInstanceId,
1155 + coveredRunOrdinals: ContextHandoffService.visibleDeltaRunOrdinals(
1156 + sourceProjection,
1157 + sourceItems,
1158 + ),
1159 + strategy: "full_thread_summary",
1160 + items: sourceItems,
1161 + runs: sourceProjection.runs,
1162 + createdAt,
1163 + });
1164 + const loaded = yield* loadFromProvider(
1165 + session.ensureThread({
1166 + threadId: projection.thread.id,
1167 + title: projection.thread.title,
1168 modelSelection: run.modelSelection,
1169 runtimePolicy: resolvedRuntimePolicy,
1108 - ...(sourceProviderTurn === undefined
1109 - ? {}
1110 - : { providerTurnId: sourceProviderTurn.id }),
1170 + providerSessionId,
1171 + existingProviderThread: { ...providerThread, forkedFrom: null },
1172 }),
1173 );
1174 + if (loaded === undefined) return undefined;
1175 + portableForkFallback = handoff;
1176 + effectiveHandoffs = [handoff, ...effectiveHandoffs];
1177 + yield* eventSink.write({
1178 + events: [
1179 + {
1180 + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
1181 + type: "context-handoff.updated",
1182 + threadId: projection.thread.id,
1183 + runId: run.id,
1184 + providerInstanceId: run.providerInstanceId,
1185 + occurredAt: createdAt,
1186 + payload: handoff,
1187 + },
1188 + {
1189 + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
1190 + type: "context-transfer.updated",
1191 + threadId: projection.thread.id,
1192 + runId: run.id,
1193 + providerInstanceId: run.providerInstanceId,
1194 + occurredAt: createdAt,
1195 + payload: {
1196 + ...nativeForkTransfer,
1197 + targetProviderInstanceId: run.providerInstanceId,
1198 + status: "resolved_portable",
1199 + resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
1200 + error: null,
1201 + updatedAt: createdAt,
1202 + },
1203 + },
1204 + ],
1205 + });
1206 + return loaded;
1207 }
1208 if (providerThread.nativeThreadRef === null) {
1209 // Pass the stored provider row for adoption; adapter-minted duplicates make activeProviderThreadId flap.
@@ -1299,8 +1393,11 @@ export const layer: Layer.Layer<
1393 ownerNodeId: providerThread.ownerNodeId,
1394 firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
1395 lastRunOrdinal: run.ordinal,
1302 - handoffIds: providerThread.handoffIds,
1303 - forkedFrom: providerThread.forkedFrom,
1396 + handoffIds:
1397 + portableForkFallback === undefined
1398 + ? providerThread.handoffIds
1399 + : [...providerThread.handoffIds, portableForkFallback.id],
1400 + forkedFrom: portableForkFallback === undefined ? providerThread.forkedFrom : null,
1401 status: "active",
1402 createdAt: providerThread.createdAt,
1403 updatedAt: now,
@@ -1345,7 +1442,9 @@ export const layer: Layer.Layer<
1442 occurredAt: now,
1443 payload: runningProviderThread,
1444 },
1348 - ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
1445 + ...(nativeForkTransfer === undefined ||
1446 + portableForkFallback !== undefined ||
1447 + runningProviderThread.nativeThreadRef === null
1448 ? []
1449 : [
1450 {
@@ -1415,6 +1514,26 @@ export const layer: Layer.Layer<
1514 const routableSubagents = projection.subagents.filter((subagent) =>
1515 RunExecutionService.canRouteRelatedSubagent(subagent.status),
1516 );
1517 + const persistHandoff = Effect.fn("ProviderTurnStartService.persist")(function* (
1518 + handoff: OrchestrationV2ContextHandoff,
1519 + ) {
1520 + const updatedAt = yield* DateTime.now;
1521 + yield* eventSink.write({
1522 + events: [
1523 + {
1524 + id: yield* idAllocator.allocate.event({
1525 + threadId: projection.thread.id,
1526 + }),
1527 + type: "context-handoff.updated",
1528 + threadId: projection.thread.id,
1529 + runId: run.id,
1530 + providerInstanceId: run.providerInstanceId,
1531 + occurredAt: updatedAt,
1532 + payload: { ...handoff, updatedAt },
1533 + },
1534 + ],
1535 + });
1536 + });
1537 const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")(
1538 function* (turnInput: Parameters<typeof session.startTurn>[0], compact = false) {
1539 const delivery = yield* deliverContextHandoffs({
@@ -1432,28 +1551,16 @@ export const layer: Layer.Layer<
1551 ...history,
1552 }),
1553 }),
1435 - persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) {
1436 - const updatedAt = yield* DateTime.now;
1437 - yield* eventSink.write({
1438 - events: [
1439 - {
1440 - id: yield* idAllocator.allocate.event({
1441 - threadId: projection.thread.id,
1442 - }),
1443 - type: "context-handoff.updated",
1444 - threadId: projection.thread.id,
1445 - runId: run.id,
1446 - providerInstanceId: run.providerInstanceId,
1447 - occurredAt: updatedAt,
1448 - payload: { ...handoff, updatedAt },
1449 - },
1450 - ],
1451 - });
1452 - }),
1554 + persist: persistHandoff,
1555 });
1556 if (!(yield* isCurrentAttemptInStatus("running"))) return;
1557 const start = compact ? session.compactThread! : session.startTurn;
1456 - const context = [delivery.context, restartNote]
1558 + // Like history, the side chat context waits for a turn that sends a prompt.
1559 + const sideChatContext =
1560 + sideChatHandoff === undefined || compact || goalCommand
1561 + ? ""
1562 + : sideChatHandoff.summaryText;
1563 + const context = [delivery.context, sideChatContext, restartNote]
1564 .filter((part) => part !== "")
1565 .join("\n\n");
1566 const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput;
@@ -1461,10 +1568,7 @@ export const layer: Layer.Layer<
1568 ...(noteContinuation ? promptedInput : turnInput),
1569 message: {
1570 ...turnInput.message,
1464 - text:
1465 - context === "" || goalCommand
1466 - ? userText
1467 - : `${context}\n\nUser message:\n${userText}`,
1571 + text: goalCommand ? userText : withInlineContext(context, userText),
1572 },
1573 }).pipe(
1574 // Clear pending handoff markers for refused prompts so the next turn retains the native session.
@@ -1481,13 +1585,30 @@ export const layer: Layer.Layer<
1585 ),
1586 );
1587 // After provider acceptance, failed delivery bookkeeping must not stop live ingestion.
1484 - yield* delivery.delivered.pipe(
1485 - Effect.catchCause(() =>
1486 - Effect.logWarning("Failed to record accepted context handoff delivery", {
1487 - runId: run.id,
1488 - deliveryStatus: "pending",
1489 - }),
1490 - ),
1588 + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId;
1589 + yield* Effect.forEach(
1590 + [
1591 + delivery.delivered,
1592 + ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null
1593 + ? []
1594 + : [
1595 + persistHandoff({
1596 + ...sideChatHandoff,
1597 + toProviderThreadId: runningProviderThread.id,
1598 + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] },
1599 + }),
1600 + ]),
1601 + ],
1602 + (record) =>
1603 + record.pipe(
1604 + Effect.catchCause(() =>
1605 + Effect.logWarning("Failed to record accepted context handoff delivery", {
1606 + runId: run.id,
1607 + deliveryStatus: "pending",
1608 + }),
1609 + ),
1610 + ),
1611 + { discard: true },
1612 );
1613 },
1614 Effect.mapError((cause) =>
@@ -1505,6 +1626,7 @@ export const layer: Layer.Layer<
1626 const deliverySession =
1627 effectiveHandoffs.length === 0 &&
1628 retryHandoff.length === 0 &&
1629 + sideChatHandoff === undefined &&
1630 restartNote === "" &&
1631 !noteContinuation
1632 ? session
apps/server/src/orchestration-v2/RunExecutionService.ts
+18 -15
@@ -920,21 +920,24 @@ export const layer: Layer.Layer<
920 .responseStreamingMode,
921 ),
922 );
923 - yield* checkpointService
924 - .captureBaseline({
925 - scope: input.checkpointScope,
926 - ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
927 - })
928 - .pipe(
929 - Effect.catchCauseIf(
930 - (cause) => !Cause.hasInterruptsOnly(cause),
931 - (_cause) =>
932 - Effect.logWarning(
933 - "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
934 - { runId: input.run.id },
935 - ),
936 - ),
937 - );
923 + // Side chats share the parent's worktree; a snapshot would capture the parent's edits.
924 + yield* (
925 + input.appThread.lineage.sideChat === true
926 + ? Effect.void
927 + : checkpointService.captureBaseline({
928 + scope: input.checkpointScope,
929 + ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
930 + })
931 + ).pipe(
932 + Effect.catchCauseIf(
933 + (cause) => !Cause.hasInterruptsOnly(cause),
934 + (_cause) =>
935 + Effect.logWarning(
936 + "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
937 + { runId: input.run.id },
938 + ),
939 + ),
940 + );
941 if (
942 input.shouldStartProviderTurn !== undefined &&
943 !(yield* input.shouldStartProviderTurn())
apps/server/src/orchestration-v2/ShellStream.test.ts
+29 -3
@@ -235,9 +235,24 @@ describe("omitOlderSettledShells", () => {
235 omitOlderSettledShells({ threads, snapshotSequence: 7, now });
236
237 it("keeps the 25 newest settled threads and counts the rest per project", () => {
238 - const result = omit([...newest, row("old", 30), row("b-old", 40), row("unsettled", null)]);
238 + const sideChat = row("side-chat", 0, {
239 + lineage: {
240 + parentThreadId: ThreadId.make("new-0"),
241 + relationshipToParent: "fork",
242 + rootThreadId: ThreadId.make("new-0"),
243 + sideChat: true,
244 + },
245 + });
246 + const result = omit([
247 + ...newest,
248 + sideChat,
249 + row("old", 30),
250 + row("b-old", 40),
251 + row("unsettled", null),
252 + ]);
253 expect(result.threads.map((thread) => thread.id)).toEqual([
254 ...newest.map((thread) => thread.id),
255 + "side-chat",
256 "unsettled",
257 ]);
258 expect(result.olderSettled).toEqual({
@@ -262,7 +277,7 @@ describe("omitOlderSettledShells", () => {
277 expect(result.olderSettled.counts).toEqual([]);
278 });
279
265 - it("keeps older rows that are snoozed, live, or above a kept subagent, and still counts them", () => {
280 + it("keeps older rows that are snoozed, live, or above a kept subagent or side chat, and still counts them", () => {
281 const threads = [
282 ...newest,
283 row("snoozed", 30, { snoozedUntil: DateTime.makeUnsafe(101 * DAY) }),
@@ -280,6 +295,15 @@ describe("omitOlderSettledShells", () => {
295 settledOverride: null,
296 settledAt: null,
297 }),
298 + row("side-chat-parent", 30),
299 + row("side-chat", null, {
300 + lineage: {
301 + parentThreadId: ThreadId.make("side-chat-parent"),
302 + relationshipToParent: "fork",
303 + rootThreadId: ThreadId.make("side-chat-parent"),
304 + sideChat: true,
305 + },
306 + }),
307 ];
308 const result = omit(threads);
309 expect(result.threads.map((thread) => thread.id).slice(25)).toEqual([
@@ -287,8 +311,10 @@ describe("omitOlderSettledShells", () => {
311 "running",
312 "parent",
313 "child",
314 + "side-chat-parent",
315 + "side-chat",
316 ]);
291 - expect(result.olderSettled.counts).toEqual([{ projectId: "project-a", count: 4 }]);
317 + expect(result.olderSettled.counts).toEqual([{ projectId: "project-a", count: 5 }]);
318 });
319 });
320
apps/server/src/orchestration-v2/ShellStream.ts
+17 -6
@@ -12,6 +12,7 @@ import type {
12 ThreadId,
13 } from "@t3tools/contracts";
14 import {
15 + isListedThreadLineage,
16 isLiveSubagentShell,
17 isOlderSettledThreadShell,
18 OrchestrationProjectShell as ProjectShellSchema,
@@ -98,7 +99,11 @@ function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {
99 if (row.lineage.relationshipToParent === "subagent") {
100 subagentThreadIds.add(row.id);
101 if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId);
101 - } else if (row.settledOverride === "settled" && row.settledAt !== null) {
102 + } else if (
103 + isListedThreadLineage(row.lineage) &&
104 + row.settledOverride === "settled" &&
105 + row.settledAt !== null
106 + ) {
107 settledTimes.push(DateTime.toEpochMillis(row.settledAt));
108 }
109 }
@@ -121,10 +126,12 @@ function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {
126 };
127 }
128
124 -function subagentAncestorIds(threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>) {
129 +function hiddenChildAncestorIds(
130 + threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>,
131 +) {
132 const ancestorIds = new Set<string>();
133 for (const thread of threads) {
127 - if (thread.lineage.relationshipToParent !== "subagent") continue;
134 + if (isListedThreadLineage(thread.lineage)) continue;
135 if (thread.lineage.parentThreadId !== null) ancestorIds.add(thread.lineage.parentThreadId);
136 ancestorIds.add(thread.lineage.rootThreadId);
137 }
@@ -156,7 +163,7 @@ function omitOlderSettledShellsWith(
163 } {
164 const nowMs = DateTime.toEpochMillis(input.now);
165 const beforeMs = facts.olderSettledBeforeMs ?? nowMs;
159 - const ancestorIds = subagentAncestorIds(input.threads);
166 + const ancestorIds = hiddenChildAncestorIds(input.threads);
167 const threads = input.threads.filter(
168 (thread) =>
169 !isOlderSettledThreadShell(thread, beforeMs) ||
@@ -207,7 +214,8 @@ export function activeShellRowsForSubscriber(
214 /**
215 * Opted-in snapshots keep the 25 newest settled top-level threads (and ties) and count the rest per
216 * project in `olderSettled`; clients page them with `getOlderSettledThreads`. Older rows stay while
210 - * pinned, snoozed, live, or above a kept subagent, so walks over shell rows still find them.
217 + * pinned, snoozed, live, or above a kept subagent or side chat, so walks over shell rows still find
218 + * them.
219 */
220 export function omitOlderSettledShells(input: {
221 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
@@ -255,7 +263,10 @@ function shellSubscriberThreadIds(
263 entry.lineage.relationshipToParent === "subagent" &&
264 (!options.omitIdleSubagents || entry.mayBeLive || facts.subagentParentIds.has(entry.id)),
265 );
258 - const ancestorIds = subagentAncestorIds(subagents);
266 + const ancestorIds = hiddenChildAncestorIds([
267 + ...subagents,
268 + ...index.filter((entry) => entry.lineage.sideChat === true),
269 + ]);
270 const keptSubagentIds = new Set(subagents.map((entry) => entry.id));
271 const beforeMs = facts.olderSettledBeforeMs;
272 return index.flatMap((entry) =>
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+79
@@ -1547,3 +1547,82 @@ it.effect("stops the running turn when a goal clear ends the goal driving it", (
1547 }),
1548 ),
1549 );
1550 +
1551 +it.effect("a side chat that opens with /goal gets its context on the next question", () =>
1552 + Effect.scoped(
1553 + Effect.gen(function* () {
1554 + const { events, layer, started, startFirstTurn } = yield* goalHarness("side-chat-goal");
1555 + yield* Effect.gen(function* () {
1556 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1557 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1558 + const parentId = yield* startFirstTurn;
1559 + const sideChatId = ThreadId.make("thread:side-chat-goal-child");
1560 + yield* orchestrator.dispatch({
1561 + type: "thread.fork",
1562 + commandId: CommandId.make("side-chat"),
1563 + sourceThreadId: parentId,
1564 + targetThreadId: sideChatId,
1565 + sourcePoint: { type: "latest_stable" },
1566 + sideChat: true,
1567 + createdBy: "user",
1568 + creationSource: "web",
1569 + });
1570 + const ask = (id: string, text: string) =>
1571 + orchestrator.dispatch({
1572 + type: "message.dispatch",
1573 + commandId: CommandId.make(id),
1574 + threadId: sideChatId,
1575 + messageId: MessageId.make(`message:${id}`),
1576 + text,
1577 + attachments: [],
1578 + modelSelection: runSelection,
1579 + dispatchMode: { type: "start_immediately" },
1580 + createdBy: "user",
1581 + creationSource: "web",
1582 + });
1583 + const sideChatEvent = (matches: (event: OrchestrationV2DomainEvent) => boolean) =>
1584 + orchestrator.streamDomainEvents.pipe(
1585 + Stream.filter((event) => event.threadId === sideChatId && matches(event)),
1586 + Stream.take(1),
1587 + Stream.runDrain,
1588 + Effect.forkScoped({ startImmediately: true }),
1589 + );
1590 + const running = yield* sideChatEvent(
1591 + (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
1592 + );
1593 + const settled = yield* sideChatEvent(
1594 + (event) => event.type === "run.updated" && event.payload.status === "waiting",
1595 + );
1596 + yield* ask("goal", "/goal clear");
1597 + yield* worker.drain();
1598 + yield* Fiber.join(running);
1599 + const turn = (yield* orchestrator.getThreadProjection(sideChatId)).providerTurns[0]!;
1600 + yield* Queue.offer(events, {
1601 + type: "provider_turn.updated",
1602 + driver,
1603 + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1604 + });
1605 + yield* Queue.offer(events, {
1606 + type: "turn.terminal",
1607 + driver,
1608 + providerThreadId: turn.providerThreadId,
1609 + providerTurnId: turn.id,
1610 + runOrdinal: started[1]!.runOrdinal,
1611 + status: "completed",
1612 + failure: null,
1613 + threadDisposition: "reusable",
1614 + });
1615 + yield* Fiber.join(settled);
1616 + yield* worker.drain();
1617 + yield* ask("question", "What is the main thread doing?");
1618 + yield* worker.drain();
1619 +
1620 + const [first, goal, question] = started.map((turn) => turn.message.text);
1621 + assert.deepEqual([first, goal], ["first", "/goal clear"]);
1622 + assert.include(question, "You are in a side chat beside the main thread.");
1623 + assert.include(question, "- User: first");
1624 + assert.isTrue(question?.endsWith("What is the main thread doing?"));
1625 + }).pipe(Effect.provide(layer));
1626 + }),
1627 + ),
1628 +);
apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+604 -10
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 + CheckpointId,
4 CommandId,
5 EventId,
6 MessageId,
@@ -214,13 +215,15 @@ it.effect.each(forkCases)(
215 const attemptId = RunAttemptId.make("interrupted-source-attempt");
216 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
217 const rootNodeId = NodeId.make("interrupted-source-root");
218 + const grandparentThreadId = ThreadId.make("fork-boundary-grandparent");
219 + const grandparentRunId = RunId.make("fork-boundary-grandparent-run");
220
221 yield* orchestrator.dispatch({
222 type: "thread.create",
220 - commandId: CommandId.make("create-source"),
221 - threadId: sourceThreadId,
223 + commandId: CommandId.make("create-grandparent"),
224 + threadId: grandparentThreadId,
225 projectId: ProjectId.make("fork-boundary-project"),
223 - title: "Fork boundary source",
226 + title: "Fork boundary grandparent",
227 modelSelection,
228 runtimeMode: "full-access",
229 interactionMode: "default",
@@ -229,6 +232,29 @@ it.effect.each(forkCases)(
232 createdBy: "user",
233 creationSource: "web",
234 });
235 + yield* writeParentRun({
236 + threadId: grandparentThreadId,
237 + runId: RunId.make("fork-boundary-grandparent-rolled-back-run"),
238 + ordinal: 1,
239 + status: "rolled_back",
240 + text: "ROLLED_BACK_MARKER",
241 + });
242 + yield* writeParentRun({
243 + threadId: grandparentThreadId,
244 + runId: grandparentRunId,
245 + ordinal: 2,
246 + status: "completed",
247 + text: "GRANDPARENT_MARKER",
248 + });
249 + yield* orchestrator.dispatch({
250 + type: "thread.fork",
251 + commandId: CommandId.make("fork-grandparent"),
252 + sourceThreadId: grandparentThreadId,
253 + targetThreadId: sourceThreadId,
254 + sourcePoint: { type: "run", runId: grandparentRunId },
255 + createdBy: "user",
256 + creationSource: "web",
257 + });
258 yield* eventSink.write({
259 events: [
260 {
@@ -246,8 +272,8 @@ it.effect.each(forkCases)(
272 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
273 nativeConversationHeadRef: null,
274 status: "idle",
249 - firstRunOrdinal: 1,
250 - lastRunOrdinal: 2,
275 + firstRunOrdinal: 2,
276 + lastRunOrdinal: 3,
277 handoffIds: [],
278 forkedFrom: null,
279 createdAt: now,
@@ -299,8 +325,15 @@ it.effect.each(forkCases)(
325 ],
326 });
327 }
302 - for (const ordinal of [1, 2]) {
303 - const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
328 + yield* writeParentRun({
329 + threadId: sourceThreadId,
330 + runId: RunId.make("fork-boundary-source-rolled-back-run"),
331 + ordinal: 1,
332 + status: "rolled_back",
333 + text: "SOURCE_ROLLED_BACK_MARKER",
334 + });
335 + for (const ordinal of [2, 3]) {
336 + const runId = ordinal === 2 ? sourceRunId : RunId.make("later-run");
337 const messageId = MessageId.make(`source-message-${ordinal}`);
338 yield* eventSink.write({
339 events: [
@@ -319,8 +352,8 @@ it.effect.each(forkCases)(
352 providerThreadId,
353 userMessageId: messageId,
354 rootNodeId: null,
322 - activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
323 - status: ordinal === 1 ? status : "completed",
355 + activeAttemptId: ordinal === 2 && status === "interrupted" ? attemptId : null,
356 + status: ordinal === 2 ? status : "completed",
357 queuePosition: null,
358 requestedAt: now,
359 startedAt: now,
@@ -355,7 +388,7 @@ it.effect.each(forkCases)(
388 creationSource: "web",
389 inputIntent: "turn_start",
390 messageId,
358 - text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
391 + text: ordinal === 2 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
392 attachments: [],
393 },
394 },
@@ -388,6 +421,9 @@ it.effect.each(forkCases)(
421 assert.lengthOf(target.contextHandoffs, 1);
422 const handoff = target.contextHandoffs[0]!;
423 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
424 + assert.include(`${handoff.summaryText}\n${history}`, "GRANDPARENT_MARKER");
425 + assert.notInclude(`${handoff.summaryText}\n${history}`, "SOURCE_ROLLED_BACK_MARKER");
426 + assert.notInclude(`${handoff.summaryText}\n${history}`, "ROLLED_BACK_MARKER");
427 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
428 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
429 assert.isNull(target.providerThreads[0]?.forkedFrom);
@@ -607,3 +643,561 @@ it.effect.each([
643 );
644 },
645 );
646 +
647 +const writeParentRun = (input: {
648 + readonly threadId: ThreadId;
649 + readonly runId: RunId;
650 + readonly ordinal: number;
651 + /** Preparing, failed, and interrupted runs asked for a new worktree. */
652 + readonly status:
653 + | "preparing"
654 + | "running"
655 + | "queued"
656 + | "completed"
657 + | "rolled_back"
658 + | "failed"
659 + | "interrupted";
660 + readonly text: string;
661 + /** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */
662 + readonly stable?: boolean;
663 +}) =>
664 + Effect.gen(function* () {
665 + const eventSink = yield* EventSink.EventSinkV2;
666 + const now = yield* DateTime.now;
667 + const { driver, instanceId, modelSelection } = forkCases[0]!;
668 + const messageId = MessageId.make(`${input.runId}:message`);
669 + const providerThreadId = input.stable
670 + ? ProviderThreadId.make(`${input.runId}:provider-thread`)
671 + : null;
672 + yield* eventSink.write({
673 + events: [
674 + ...(providerThreadId === null
675 + ? []
676 + : [
677 + {
678 + id: EventId.make(`${input.runId}:provider-thread`),
679 + type: "provider-thread.updated" as const,
680 + threadId: input.threadId,
681 + occurredAt: now,
682 + payload: {
683 + id: providerThreadId,
684 + driver,
685 + providerInstanceId: instanceId,
686 + providerSessionId: null,
687 + appThreadId: input.threadId,
688 + ownerNodeId: null,
689 + nativeThreadRef: {
690 + driver,
691 + nativeId: `${input.runId}:native`,
692 + strength: "strong" as const,
693 + },
694 + nativeConversationHeadRef: null,
695 + status: "idle" as const,
696 + firstRunOrdinal: input.ordinal,
697 + lastRunOrdinal: input.ordinal,
698 + handoffIds: [],
699 + forkedFrom: null,
700 + createdAt: now,
701 + updatedAt: now,
702 + },
703 + },
704 + ]),
705 + {
706 + id: EventId.make(`${input.runId}:created`),
707 + type: "run.created",
708 + threadId: input.threadId,
709 + runId: input.runId,
710 + occurredAt: now,
711 + payload: {
712 + id: input.runId,
713 + threadId: input.threadId,
714 + ordinal: input.ordinal,
715 + providerInstanceId: instanceId,
716 + modelSelection,
717 + providerThreadId,
718 + userMessageId: messageId,
719 + rootNodeId: null,
720 + activeAttemptId: null,
721 + status: input.status,
722 + queuePosition: null,
723 + requestedAt: now,
724 + startedAt: now,
725 + completedAt: input.status === "completed" ? now : null,
726 + checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
727 + contextHandoffId: null,
728 + ...(input.status === "preparing" ||
729 + input.status === "failed" ||
730 + input.status === "interrupted"
731 + ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }
732 + : {}),
733 + },
734 + },
735 + {
736 + id: EventId.make(`${input.runId}:item`),
737 + type: "turn-item.updated",
738 + threadId: input.threadId,
739 + runId: input.runId,
740 + occurredAt: now,
741 + payload: {
742 + id: TurnItemId.make(`${input.runId}:item`),
743 + threadId: input.threadId,
744 + runId: input.runId,
745 + nodeId: null,
746 + providerThreadId,
747 + providerTurnId: null,
748 + nativeItemRef: null,
749 + parentItemId: null,
750 + ordinal: input.ordinal * 100,
751 + status: "completed",
752 + title: null,
753 + startedAt: now,
754 + completedAt: now,
755 + updatedAt: now,
756 + type: "user_message",
757 + createdBy: "user",
758 + creationSource: "web",
759 + inputIntent: "turn_start",
760 + messageId,
761 + text: input.text,
762 + attachments: [],
763 + },
764 + },
765 + ],
766 + });
767 + });
768 +
769 +/** Marks `threadId` as imported from V1 and gives it one runless imported user message. */
770 +const writeImportedHistory = (threadId: ThreadId, text: string) =>
771 + Effect.gen(function* () {
772 + const orchestrator = yield* Orchestrator.OrchestratorV2;
773 + const eventSink = yield* EventSink.EventSinkV2;
774 + const now = yield* DateTime.now;
775 + const { thread } = yield* orchestrator.getThreadProjection(threadId);
776 + yield* eventSink.write({
777 + events: [
778 + {
779 + id: EventId.make(`${threadId}:imported`),
780 + type: "thread.metadata-updated",
781 + threadId,
782 + occurredAt: now,
783 + payload: { ...thread, historyOrigin: "v1_import" },
784 + },
785 + {
786 + id: EventId.make(`${threadId}:imported-item`),
787 + type: "turn-item.updated",
788 + threadId,
789 + occurredAt: now,
790 + payload: {
791 + id: TurnItemId.make(`${threadId}:imported-item`),
792 + threadId,
793 + runId: null,
794 + nodeId: null,
795 + providerThreadId: null,
796 + providerTurnId: null,
797 + nativeItemRef: null,
798 + parentItemId: null,
799 + ordinal: 1,
800 + status: "completed",
801 + title: null,
802 + startedAt: now,
803 + completedAt: now,
804 + updatedAt: now,
805 + type: "user_message",
806 + createdBy: "user",
807 + creationSource: "web",
808 + inputIntent: "turn_start",
809 + messageId: MessageId.make(`${threadId}:imported-message`),
810 + text,
811 + attachments: [],
812 + },
813 + },
814 + ],
815 + });
816 + });
817 +
818 +const createParent = (threadId: ThreadId) =>
819 + Effect.gen(function* () {
820 + const orchestrator = yield* Orchestrator.OrchestratorV2;
821 + yield* orchestrator.dispatch({
822 + type: "thread.create",
823 + commandId: CommandId.make(`${threadId}:create`),
824 + threadId,
825 + projectId: ProjectId.make("side-chat-project"),
826 + title: "Side chat parent",
827 + modelSelection: forkCases[0]!.modelSelection,
828 + runtimeMode: "full-access",
829 + interactionMode: "default",
830 + branch: null,
831 + worktreePath: null,
832 + createdBy: "user",
833 + creationSource: "web",
834 + });
835 + });
836 +
837 +const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
838 + Effect.gen(function* () {
839 + const orchestrator = yield* Orchestrator.OrchestratorV2;
840 + return yield* orchestrator.dispatch({
841 + type: "thread.fork",
842 + commandId: CommandId.make(commandId),
843 + sourceThreadId,
844 + targetThreadId,
845 + sourcePoint: { type: "latest_stable" },
846 + sideChat: true,
847 + createdBy: "user",
848 + creationSource: "web",
849 + });
850 + });
851 +
852 +const askSideChat = (threadId: ThreadId, commandId: string) =>
853 + Effect.gen(function* () {
854 + const orchestrator = yield* Orchestrator.OrchestratorV2;
855 + yield* orchestrator.dispatch({
856 + type: "message.dispatch",
857 + commandId: CommandId.make(commandId),
858 + threadId,
859 + messageId: MessageId.make(commandId),
860 + text: "What is the main thread doing?",
861 + attachments: [],
862 + dispatchMode: { type: "start_immediately" },
863 + createdBy: "user",
864 + creationSource: "web",
865 + });
866 + });
867 +
868 +it.effect("a side chat of an idle parent still starts with the framing note", () =>
869 + Effect.gen(function* () {
870 + const orchestrator = yield* Orchestrator.OrchestratorV2;
871 + const parentId = ThreadId.make("side-chat-idle-parent");
872 + const sideChatId = ThreadId.make("side-chat-idle-child");
873 + yield* createParent(parentId);
874 + yield* writeParentRun({
875 + threadId: parentId,
876 + runId: RunId.make("side-chat-idle-parent-run"),
877 + ordinal: 1,
878 + status: "completed",
879 + text: "Parent work",
880 + stable: true,
881 + });
882 +
883 + yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId);
884 + yield* askSideChat(sideChatId, "side-chat-idle-first-message");
885 +
886 + const started = yield* orchestrator.getThreadProjection(sideChatId);
887 + assert.isNotNull(started.providerThreads[0]?.forkedFrom);
888 + assert.lengthOf(started.contextHandoffs, 1);
889 + const [handoff] = started.contextHandoffs;
890 + assert.isTrue(
891 + handoff!.summaryText.startsWith("You are in a side chat beside the main thread."),
892 + );
893 + assert.notInclude(handoff!.summaryText, "Main thread activity");
894 + }).pipe(Effect.provide(forkCases[0]!.layer)),
895 +);
896 +
897 +it.effect("a side chat waits for the parent's new worktree, also after its setup ended", () =>
898 + Effect.gen(function* () {
899 + for (const status of ["preparing", "failed", "interrupted"] as const) {
900 + const parentId = ThreadId.make(`side-chat-worktree-parent-${status}`);
901 + yield* createParent(parentId);
902 + yield* writeParentRun({
903 + threadId: parentId,
904 + runId: RunId.make(`side-chat-worktree-parent-run-${status}`),
905 + ordinal: 1,
906 + status,
907 + text: "Parent work",
908 + });
909 +
910 + const rejected = yield* forkSideChat(
911 + `side-chat-worktree-fork-${status}`,
912 + parentId,
913 + ThreadId.make(`side-chat-worktree-child-${status}`),
914 + ).pipe(Effect.flip);
915 + assert.include(String(rejected.cause), "has no worktree yet", status);
916 + }
917 + }).pipe(Effect.provide(forkCases[0]!.layer)),
918 +);
919 +
920 +it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
921 + Effect.gen(function* () {
922 + const orchestrator = yield* Orchestrator.OrchestratorV2;
923 + const parentId = ThreadId.make("side-chat-close-parent");
924 + const unused = ThreadId.make("side-chat-close-unused");
925 + const used = ThreadId.make("side-chat-close-used");
926 + yield* createParent(parentId);
927 + yield* writeParentRun({
928 + threadId: parentId,
929 + runId: RunId.make("side-chat-close-parent-run"),
930 + ordinal: 1,
931 + status: "completed",
932 + text: "Parent work",
933 + stable: true,
934 + });
935 + yield* forkSideChat("side-chat-close-fork-unused", parentId, unused);
936 + yield* forkSideChat("side-chat-close-fork-used", parentId, used);
937 + yield* askSideChat(used, "side-chat-close-used-message");
938 + const close = (threadId: ThreadId) =>
939 + orchestrator.dispatch({
940 + type: "thread.delete",
941 + commandId: CommandId.make(`side-chat-close:${threadId}`),
942 + threadId,
943 + onlyIfUnused: true,
944 + });
945 +
946 + yield* close(unused);
947 + yield* close(used);
948 + assert.isNotNull((yield* orchestrator.getThreadProjection(unused)).thread.deletedAt);
949 + assert.isNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
950 +
951 + yield* orchestrator.dispatch({
952 + type: "thread.delete",
953 + commandId: CommandId.make("side-chat-close-delete-parent"),
954 + threadId: parentId,
955 + });
956 + assert.isNotNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
957 + const orphan = yield* forkSideChat(
958 + "side-chat-close-orphan",
959 + parentId,
960 + ThreadId.make("side-chat-close-orphan"),
961 + ).pipe(Effect.flip);
962 + assert.include(String(orphan.cause), "was deleted");
963 + }).pipe(Effect.provide(forkCases[0]!.layer)),
964 +);
965 +
966 +it.effect("a side chat opened during the parent's first turn starts from a digest", () =>
967 + Effect.gen(function* () {
968 + const orchestrator = yield* Orchestrator.OrchestratorV2;
969 + const grandparentId = ThreadId.make("side-chat-busy-grandparent");
970 + const grandparentRunId = RunId.make("side-chat-busy-grandparent-run");
971 + const parentId = ThreadId.make("side-chat-busy-parent");
972 + const sideChatId = ThreadId.make("side-chat-busy-child");
973 + yield* createParent(grandparentId);
974 + yield* writeParentRun({
975 + threadId: grandparentId,
976 + runId: grandparentRunId,
977 + ordinal: 1,
978 + status: "completed",
979 + text: "GRANDPARENT_MARKER",
980 + stable: true,
981 + });
982 + yield* orchestrator.dispatch({
983 + type: "thread.fork",
984 + commandId: CommandId.make("side-chat-busy-parent-fork"),
985 + sourceThreadId: grandparentId,
986 + targetThreadId: parentId,
987 + sourcePoint: { type: "run", runId: grandparentRunId },
988 + createdBy: "user",
989 + creationSource: "web",
990 + });
991 + yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");
992 + yield* writeParentRun({
993 + threadId: parentId,
994 + runId: RunId.make("side-chat-rewound-parent-run"),
995 + ordinal: 1,
996 + status: "rolled_back",
997 + text: "PARENT_ROLLED_BACK_MARKER",
998 + });
999 + yield* writeParentRun({
1000 + threadId: parentId,
1001 + runId: RunId.make("side-chat-busy-parent-run"),
1002 + ordinal: 2,
1003 + status: "running",
1004 + text: "PARENT_RUNNING_MARKER",
1005 + });
1006 + yield* writeParentRun({
1007 + threadId: parentId,
1008 + runId: RunId.make("side-chat-queued-parent-run"),
1009 + ordinal: 3,
1010 + status: "queued",
1011 + text: "PARENT_QUEUED_MARKER",
1012 + });
1013 + const fork = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
1014 + orchestrator.dispatch({
1015 + type: "thread.fork",
1016 + commandId: CommandId.make(commandId),
1017 + sourceThreadId,
1018 + targetThreadId,
1019 + sourcePoint: { type: "latest_stable" },
1020 + sideChat: true,
1021 + createdBy: "user",
1022 + creationSource: "web",
1023 + });
1024 +
1025 + yield* fork("side-chat-busy-fork", parentId, sideChatId);
1026 + const created = yield* orchestrator.getThreadProjection(sideChatId);
1027 + assert.isTrue(created.thread.lineage.sideChat);
1028 + assert.equal(created.thread.runtimeMode, "approval-required");
1029 + assert.isNull(created.thread.forkedFrom);
1030 + assert.deepEqual(created.contextTransfers[0]?.sourcePoint, { threadId: parentId });
1031 +
1032 + const nested = yield* fork(
1033 + "side-chat-busy-nested",
1034 + sideChatId,
1035 + ThreadId.make("side-chat-busy-nested"),
1036 + ).pipe(Effect.flip);
1037 + assert.equal(nested._tag, "OrchestratorDispatchError");
1038 + // Either would take the side chat's lock before the parent's, against the delete cascade.
1039 + const ontoParent = yield* fork("side-chat-busy-onto-parent", sideChatId, parentId).pipe(
1040 + Effect.flip,
1041 + );
1042 + assert.equal(ontoParent._tag, "OrchestratorThreadAlreadyExistsError");
1043 + const ontoExisting = yield* fork("side-chat-busy-onto-existing", parentId, sideChatId).pipe(
1044 + Effect.flip,
1045 + );
1046 + assert.equal(ontoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1047 + const plainOntoExisting = yield* orchestrator
1048 + .dispatch({
1049 + type: "thread.fork",
1050 + commandId: CommandId.make("side-chat-busy-plain-onto-existing"),
1051 + sourceThreadId: parentId,
1052 + targetThreadId: sideChatId,
1053 + sourcePoint: { type: "latest_stable" },
1054 + createdBy: "user",
1055 + creationSource: "web",
1056 + })
1057 + .pipe(Effect.flip);
1058 + assert.equal(plainOntoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1059 + const busyMergeBack = yield* orchestrator
1060 + .dispatch({
1061 + type: "thread.merge_back",
1062 + commandId: CommandId.make("side-chat-busy-merge-back"),
1063 + sourceThreadId: sideChatId,
1064 + targetThreadId: parentId,
1065 + sourcePoint: { type: "latest_stable" },
1066 + createdBy: "user",
1067 + creationSource: "web",
1068 + })
1069 + .pipe(Effect.flip);
1070 + assert.include(String(busyMergeBack.cause), "active work");
1071 +
1072 + yield* orchestrator.dispatch({
1073 + type: "message.dispatch",
1074 + commandId: CommandId.make("side-chat-busy-first-message"),
1075 + threadId: sideChatId,
1076 + messageId: MessageId.make("side-chat-busy-first-message"),
1077 + text: "What is the main thread doing?",
1078 + attachments: [],
1079 + dispatchMode: { type: "start_immediately" },
1080 + createdBy: "user",
1081 + creationSource: "web",
1082 + });
1083 + const started = yield* orchestrator.getThreadProjection(sideChatId);
1084 + const [handoff] = started.contextHandoffs;
1085 + assert.lengthOf(started.contextHandoffs, 1);
1086 + assert.deepEqual(started.contextTransfers[0]?.resolution, {
1087 + strategy: "portable_context",
1088 + contextHandoffId: handoff!.id,
1089 + });
1090 + assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");
1091 + // Inherited rows come first, so the cap truncates them first.
1092 + assert.isAbove(
1093 + handoff!.summaryText.indexOf("- User: PARENT_IMPORTED_MARKER"),
1094 + handoff!.summaryText.indexOf("- User: GRANDPARENT_MARKER"),
1095 + );
1096 + assert.include(handoff!.summaryText, "- User: GRANDPARENT_MARKER");
1097 + assert.notInclude(handoff!.summaryText, "PARENT_ROLLED_BACK_MARKER");
1098 + assert.notInclude(handoff!.summaryText, "PARENT_QUEUED_MARKER");
1099 + assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");
1100 + assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");
1101 + assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);
1102 + assert.equal(
1103 + started.messages.find((message) => message.role === "user")?.text,
1104 + "What is the main thread doing?",
1105 + );
1106 +
1107 + yield* orchestrator.dispatch({
1108 + type: "thread.delete",
1109 + commandId: CommandId.make("side-chat-busy-delete-parent"),
1110 + threadId: parentId,
1111 + });
1112 + assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
1113 + }).pipe(Effect.provide(forkCases[0]!.layer)),
1114 +);
1115 +
1116 +it.effect("merge-back rejects a second fork's context until the first is consumed", () =>
1117 + Effect.gen(function* () {
1118 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1119 + const parentId = ThreadId.make("merge-back-guard-parent");
1120 + const parentRunId = RunId.make("merge-back-guard-parent-run");
1121 + yield* createParent(parentId);
1122 + yield* writeParentRun({
1123 + threadId: parentId,
1124 + runId: parentRunId,
1125 + ordinal: 1,
1126 + status: "completed",
1127 + text: "Parent work",
1128 + });
1129 + const forkAndRun = (name: string) =>
1130 + Effect.gen(function* () {
1131 + const threadId = ThreadId.make(`merge-back-guard-${name}`);
1132 + const runId = RunId.make(`merge-back-guard-${name}-run`);
1133 + yield* orchestrator.dispatch({
1134 + type: "thread.fork",
1135 + commandId: CommandId.make(`merge-back-guard-fork-${name}`),
1136 + sourceThreadId: parentId,
1137 + targetThreadId: threadId,
1138 + sourcePoint: { type: "run", runId: parentRunId },
1139 + sideChat: true,
1140 + createdBy: "user",
1141 + creationSource: "web",
1142 + });
1143 + yield* writeParentRun({ threadId, runId, ordinal: 1, status: "completed", text: name });
1144 + return { threadId, runId };
1145 + });
1146 + const mergeBack = (commandId: string, fork: { threadId: ThreadId; runId: RunId }) =>
1147 + orchestrator.dispatch({
1148 + type: "thread.merge_back",
1149 + commandId: CommandId.make(commandId),
1150 + sourceThreadId: fork.threadId,
1151 + targetThreadId: parentId,
1152 + sourcePoint: { type: "run", runId: fork.runId },
1153 + createdBy: "user",
1154 + creationSource: "web",
1155 + });
1156 + const first = yield* forkAndRun("first");
1157 + const second = yield* forkAndRun("second");
1158 +
1159 + yield* mergeBack("merge-back-guard-first", first);
1160 + const rejected = yield* mergeBack("merge-back-guard-second", second).pipe(Effect.flip);
1161 + assert.include(String(rejected.cause), "pending context from another side chat or fork");
1162 + yield* mergeBack("merge-back-guard-first-again", first);
1163 + // That pending merge-back targets the parent, so it does not block one into `first`.
1164 + const nested = { threadId: ThreadId.make("merge-back-guard-nested") };
1165 + const nestedRunId = RunId.make("merge-back-guard-nested-run");
1166 + yield* orchestrator.dispatch({
1167 + type: "thread.fork",
1168 + commandId: CommandId.make("merge-back-guard-fork-nested"),
1169 + sourceThreadId: first.threadId,
1170 + targetThreadId: nested.threadId,
1171 + sourcePoint: { type: "run", runId: first.runId },
1172 + createdBy: "user",
1173 + creationSource: "web",
1174 + });
1175 + yield* writeParentRun({
1176 + threadId: nested.threadId,
1177 + runId: nestedRunId,
1178 + ordinal: 1,
1179 + status: "completed",
1180 + text: "nested",
1181 + });
1182 + yield* orchestrator.dispatch({
1183 + type: "thread.merge_back",
1184 + commandId: CommandId.make("merge-back-guard-nested"),
1185 + sourceThreadId: nested.threadId,
1186 + targetThreadId: first.threadId,
1187 + sourcePoint: { type: "run", runId: nestedRunId },
1188 + createdBy: "user",
1189 + creationSource: "web",
1190 + });
1191 +
1192 + const parent = yield* orchestrator.getThreadProjection(parentId);
1193 + assert.deepEqual(
1194 + parent.contextTransfers
1195 + .filter((transfer) => transfer.type === "merge_back")
1196 + .map((transfer) => [transfer.sourceThreadId, transfer.status]),
1197 + [
1198 + [first.threadId, "superseded"],
1199 + [first.threadId, "pending"],
1200 + ],
1201 + );
1202 + }).pipe(Effect.provide(forkCases[0]!.layer)),
1203 +);
apps/server/src/orchestration-v2/ThreadForkService.test.ts
+63
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
2 import {
3 CommandId,
4 ContextTransferId,
5 + EnvironmentId,
6 MessageId,
7 type ModelSelection,
8 type OrchestrationV2AppThread,
@@ -111,6 +112,7 @@ function makeSourceProjection(sourceRun: OrchestrationV2Run): OrchestrationV2Thr
112 const planFork = (
113 sourceRun: OrchestrationV2Run,
114 sourceProjection = makeSourceProjection(sourceRun),
115 + options: { readonly sideChat?: boolean } = {},
116 ) =>
117 Effect.gen(function* () {
118 const service = yield* ThreadForkService.ThreadForkServiceV2;
@@ -125,6 +127,7 @@ const planFork = (
127 transferId: ContextTransferId.make("context-transfer:fork-snoozed-source"),
128 targetThreadId,
129 title: "Awake fork",
130 + ...options,
131 createdBy: "user",
132 creationSource: "mobile",
133 createdAt: forkCreatedAt,
@@ -261,3 +264,63 @@ it.effect("rejects in-progress and rolled-back fork sources", () =>
264 }
265 }),
266 );
267 +
268 +it.effect("marks only requested forks as supervised side chats", () =>
269 + Effect.gen(function* () {
270 + const sourceRun = makeSourceRun("completed");
271 + const sideChat = yield* planFork(sourceRun, makeSourceProjection(sourceRun), {
272 + sideChat: true,
273 + });
274 + assert.isTrue(sideChat.targetThread.lineage.sideChat);
275 + assert.equal(sideChat.targetThread.runtimeMode, "approval-required");
276 +
277 + const sideChatSource = makeSourceProjection(sourceRun);
278 + const sideChatProjection = {
279 + ...sideChatSource,
280 + thread: {
281 + ...sideChatSource.thread,
282 + lineage: { ...sideChatSource.thread.lineage, sideChat: true },
283 + },
284 + };
285 + const forkOfSideChat = yield* planFork(sourceRun, sideChatProjection);
286 + assert.isUndefined(forkOfSideChat.targetThread.lineage.sideChat);
287 + assert.equal(forkOfSideChat.targetThread.runtimeMode, "full-access");
288 +
289 + const nested = yield* planFork(sourceRun, sideChatProjection, { sideChat: true }).pipe(
290 + Effect.flip,
291 + );
292 + assert.equal(nested.cause, "A side chat cannot start another side chat.");
293 +
294 + const subagentSource = makeSourceProjection(sourceRun);
295 + const fromSubagent = yield* planFork(
296 + sourceRun,
297 + {
298 + ...subagentSource,
299 + thread: {
300 + ...subagentSource.thread,
301 + lineage: { ...subagentSource.thread.lineage, relationshipToParent: "subagent" },
302 + },
303 + },
304 + { sideChat: true },
305 + ).pipe(Effect.flip);
306 + assert.equal(fromSubagent.cause, "A subagent cannot start a side chat.");
307 +
308 + const delegatedSource = makeSourceProjection(sourceRun);
309 + const fromDelegated = yield* planFork(
310 + sourceRun,
311 + {
312 + ...delegatedSource,
313 + thread: {
314 + ...delegatedSource.thread,
315 + delegatedFrom: {
316 + environmentId: EnvironmentId.make("linked-environment"),
317 + threadId: ThreadId.make("linked-parent"),
318 + title: "Linked parent",
319 + },
320 + },
321 + },
322 + { sideChat: true },
323 + ).pipe(Effect.flip);
324 + assert.equal(fromDelegated.cause, "A subagent cannot start a side chat.");
325 + }),
326 +);
apps/server/src/orchestration-v2/ThreadForkService.ts
+32 -10
@@ -51,13 +51,15 @@ export function forkableSourceRunStatusError(
51 export interface ThreadForkServiceV2Shape {
52 readonly plan: (input: {
53 readonly sourceProjection: Pick<OrchestrationV2ThreadProjection, "thread">;
54 - readonly sourceRun: OrchestrationV2Run;
54 + /** Null only for a side chat whose parent has no stable run yet. */
55 + readonly sourceRun: OrchestrationV2Run | null;
56 readonly sourceProviderThread: OrchestrationV2ProviderThread | undefined;
57 readonly sourceTokenUsage?: OrchestrationV2ProviderTurnTokenUsage | undefined;
58 readonly canonicalSourcePoint: OrchestrationV2ContextSourcePoint;
59 readonly transferId: ContextTransferId;
60 readonly targetThreadId: ThreadId;
61 readonly title?: string;
62 + readonly sideChat?: boolean;
63 readonly createdBy: OrchestrationV2Actor;
64 readonly creationSource: OrchestrationV2CreationSource;
65 readonly createdAt: DateTime.Utc;
@@ -73,11 +75,28 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
75 ThreadForkServiceV2,
76 ThreadForkServiceV2.of({
77 plan: Effect.fn("ThreadForkService.plan")(function* (input) {
76 - if (!isForkableSourceRunStatus(input.sourceRun.status)) {
78 + const { sourceRun } = input;
79 + const sourceLineage = input.sourceProjection.thread.lineage;
80 + // A task a linked environment delegated here is a subagent of a remote thread.
81 + if (
82 + input.sideChat &&
83 + (sourceLineage.sideChat ||
84 + sourceLineage.relationshipToParent === "subagent" ||
85 + input.sourceProjection.thread.delegatedFrom !== undefined)
86 + ) {
87 return yield* new ThreadForkPlanError({
88 sourceThreadId: input.sourceProjection.thread.id,
89 targetThreadId: input.targetThreadId,
80 - cause: forkableSourceRunStatusError(input.sourceRun),
90 + cause: sourceLineage.sideChat
91 + ? "A side chat cannot start another side chat."
92 + : "A subagent cannot start a side chat.",
93 + });
94 + }
95 + if (sourceRun !== null && !isForkableSourceRunStatus(sourceRun.status)) {
96 + return yield* new ThreadForkPlanError({
97 + sourceThreadId: input.sourceProjection.thread.id,
98 + targetThreadId: input.targetThreadId,
99 + cause: forkableSourceRunStatusError(sourceRun),
100 });
101 }
102 const targetThread: OrchestrationV2AppThread = {
@@ -92,17 +111,19 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
111 title: input.title ?? `${input.sourceProjection.thread.title} fork`,
112 // The source's title job completes only on the source thread.
113 titleRegeneration: null,
114 + // Side chats share the parent's worktree, so they start supervised.
115 + ...(input.sideChat ? { runtimeMode: "approval-required" as const } : {}),
116 activeProviderThreadId: null,
117 lineage: {
118 parentThreadId: input.sourceProjection.thread.id,
119 relationshipToParent: "fork",
120 rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
121 + ...(input.sideChat ? { sideChat: true } : {}),
122 },
101 - forkedFrom: {
102 - type: "run",
103 - threadId: input.sourceProjection.thread.id,
104 - runId: input.sourceRun.id,
105 - },
123 + forkedFrom:
124 + sourceRun === null
125 + ? null
126 + : { type: "run", threadId: input.sourceProjection.thread.id, runId: sourceRun.id },
127 createdAt: input.createdAt,
128 updatedAt: input.createdAt,
129 archivedAt: null,
@@ -124,10 +145,11 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
145 targetThreadId: input.targetThreadId,
146 sourcePoint: input.canonicalSourcePoint,
147 basePoint: null,
127 - sourceProviderInstanceId: input.sourceRun.providerInstanceId,
148 + sourceProviderInstanceId:
149 + sourceRun?.providerInstanceId ?? input.sourceProjection.thread.providerInstanceId,
150 // Only native forks retain this context; portable handoffs rebuild it.
151 sourceTokenUsage:
130 - (input.sourceRun.status === "completed" || input.sourceRun.status === "waiting") &&
152 + (sourceRun?.status === "completed" || sourceRun?.status === "waiting") &&
153 input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
154 ? input.sourceTokenUsage
155 : undefined,
apps/server/src/orchestration-v2/ThreadManagementService.ts
+6 -4
@@ -11,6 +11,7 @@ import type {
11 import {
12 type ChatAttachment,
13 CommandId,
14 + isListedThreadLineage,
15 MessageId,
16 OrchestrationV2StopWorkflowError,
17 type OrchestrationV2StopWorkflowInput,
@@ -418,7 +419,7 @@ export interface ThreadManagementServiceShape {
419 Orchestrator.OrchestratorV2Error
420 >;
421 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
421 - /** Omit `projectId` to list every project's threads. */
422 + /** Omit `projectId` to list every project's threads. Side chats are never listed. */
423 readonly listProjectThreads: (input: {
424 readonly projectId?: ProjectId | undefined;
425 readonly includeSubagents: boolean;
@@ -793,9 +794,10 @@ const make = Effect.gen(function* () {
794 ),
795 Effect.map((snapshot) =>
796 snapshot.threads
796 - .filter(
797 - (thread) =>
798 - input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
797 + .filter((thread) =>
798 + input.includeSubagents
799 + ? thread.lineage.sideChat !== true
800 + : isListedThreadLineage(thread.lineage),
801 )
802 .toSorted(
803 (left, right) =>
apps/server/src/orchestration-v2/ThreadSearch.test.ts
+13 -2
@@ -66,6 +66,7 @@ const thread = (
66 readonly archivedAt?: DateTime.Utc;
67 readonly deletedAt?: DateTime.Utc;
68 readonly subagentOf?: ThreadId;
69 + readonly sideChatOf?: ThreadId;
70 readonly title?: string;
71 readonly settledAt?: DateTime.Utc;
72 readonly linkedPullRequest?: ThreadLinkedPullRequest;
@@ -98,7 +99,14 @@ const thread = (
99 relationshipToParent: "subagent",
100 rootThreadId: overrides.subagentOf,
101 }
101 - : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
102 + : overrides.sideChatOf
103 + ? {
104 + parentThreadId: overrides.sideChatOf,
105 + relationshipToParent: "fork",
106 + rootThreadId: overrides.sideChatOf,
107 + sideChat: true,
108 + }
109 + : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
110 forkedFrom: null,
111 createdAt: at(0),
112 updatedAt: at(0),
@@ -366,13 +374,14 @@ it.layer(layerTest)("ThreadSearch", (it) => {
374 }),
375 );
376
369 - it.effect("matches inside identifiers and skips subagent threads and short tokens", () =>
377 + it.effect("matches inside identifiers and skips hidden threads and short tokens", () =>
378 Effect.gen(function* () {
379 const projections = yield* ProjectionStore.ProjectionStoreV2;
380 const search = yield* ThreadSearch.ThreadSearch;
381 const project = ProjectId.make("project:search-tokens");
382 const parent = ThreadId.make("thread:tokens-parent");
383 const subagent = ThreadId.make("thread:tokens-subagent");
384 + const sideChat = ThreadId.make("thread:tokens-side-chat");
385 yield* createProject(project);
386 yield* Effect.forEach(
387 [
@@ -380,6 +389,8 @@ it.layer(layerTest)("ThreadSearch", (it) => {
389 message(parent, "parent", "user", "Rename ThreadSearchService before shipping"),
390 thread(subagent, project, { subagentOf: parent }),
391 message(subagent, "subagent", "assistant", "ThreadSearchService renamed"),
392 + thread(sideChat, project, { sideChatOf: parent, title: "ThreadSearchService question" }),
393 + message(sideChat, "side-chat", "user", "Why rename ThreadSearchService?"),
394 ],
395 projections.apply,
396 { discard: true },
apps/server/src/orchestration-v2/ThreadSearch.ts
+5 -1
@@ -154,7 +154,7 @@ export function buildSearchSnippet(text: string, matchStart: number): string {
154 return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
155 }
156
157 -// Hidden subagent threads must be filtered before the hit limit so visible matches aren't lost.
157 +// Filter hidden subagents and side chats before the hit limit so visible matches aren't lost.
158 // Word starts and ranking follow the title rules in JS.
159 // Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages.
160 // The scan folds ASCII case only, so accent variants and non-ASCII case variants may not match.
@@ -174,6 +174,7 @@ export const messageHitsQuery = (
174 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
175 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
176 IS NOT 'subagent'
177 + AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
178 )
179 ${
180 match === null
@@ -332,6 +333,7 @@ export const make = Effect.gen(function* () {
333 AND projects.deleted_at IS NULL
334 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
335 IS NOT 'subagent'
336 + AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
337 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
338 `,
339 });
@@ -362,6 +364,7 @@ export const make = Effect.gen(function* () {
364 AND projects.deleted_at IS NULL
365 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
366 IS NOT 'subagent'
367 + AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
368 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
369 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
370 AND (${projectIds} IS NULL
@@ -384,6 +387,7 @@ export const make = Effect.gen(function* () {
387 AND json_extract(threads.payload_json, '$.archivedAt') IS NULL
388 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
389 IS NOT 'subagent'
390 + AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
391 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
392 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
393 AND (${projectIds} IS NULL
apps/server/src/orchestration-v2/ThreadStream.test.ts
+26 -1
@@ -1,8 +1,13 @@
1 import {
2 + ContextHandoffId,
3 + ContextTransferId,
4 EventId,
5 OrchestrationV2ThreadStreamItem,
6 + ProviderThreadId,
7 + RunId,
8 ThreadId,
9 TurnItemId,
10 + type OrchestrationV2ContextHandoff,
11 type OrchestrationV2ProjectedTurnItem,
12 type OrchestrationV2ThreadProjection,
13 type OrchestrationV2TurnItem,
@@ -149,11 +154,31 @@ describe("decideThreadResume", () => {
154 });
155
156 it("builds socket fallback snapshots with a bounded timeline and history cursor", () => {
157 + const projection = timelineProjection(80);
158 + // A delivered side chat digest stays "ready", which bounded snapshots keep.
159 + const sideChatHandoff = {
160 + id: ContextHandoffId.make("side-chat-handoff"),
161 + transferId: ContextTransferId.make("side-chat-transfer"),
162 + threadId: THREAD_ID,
163 + targetRunId: RunId.make("side-chat-run"),
164 + fromProviderThreadIds: [],
165 + toProviderThreadId: ProviderThreadId.make("side-chat-provider-thread"),
166 + coveredRunOrdinals: { from: 1, to: 1 },
167 + strategy: "manual_context",
168 + status: "ready",
169 + summaryMessageId: null,
170 + summaryText: "x".repeat(8_000),
171 + delivery: { nativeThreadId: "native", status: "inline", itemIds: [] },
172 + createdByProviderInstanceId: null,
173 + createdAt: NOW,
174 + updatedAt: NOW,
175 + } satisfies OrchestrationV2ContextHandoff;
176 const snapshot = buildBoundedThreadStreamSnapshot({
177 snapshotSequence: 44,
154 - projection: timelineProjection(80),
178 + projection: { ...projection, contextHandoffs: [sideChatHandoff] },
179 });
180
181 + expect(snapshot.projection.contextHandoffs.map((handoff) => handoff.summaryText)).toEqual([""]);
182 expect(snapshot.kind).toBe("snapshot");
183 expect(snapshot.snapshotSequence).toBe(44);
184 expect(snapshot.projection.visibleTurnItems).toHaveLength(75);
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+214
@@ -595,6 +595,220 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
595 );
596 }),
597 );
598 +
599 + it.effect(
600 + "deletes a side chat with its parent only after the side chat's in-flight command",
601 + () =>
602 + Effect.gen(function* () {
603 + const projects = yield* ProjectService.ProjectService;
604 + const orchestrator = yield* Orchestrator.OrchestratorV2;
605 + const eventSink = yield* EventSink.EventSinkV2;
606 + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
607 + const projectId = ProjectId.make("runtime-side-chat-delete");
608 + const parentId = ThreadId.make("runtime-side-chat-delete-parent");
609 + const sideChatId = ThreadId.make("runtime-side-chat-delete-child");
610 + const updateCommandId = CommandId.make("runtime-side-chat-delete-update");
611 + yield* projects.create({
612 + commandId: CommandId.make("runtime-side-chat-delete-project"),
613 + projectId,
614 + title: "Side chat deletion",
615 + workspaceRoot: "/work/side-chat-deletion",
616 + });
617 + yield* orchestrator.dispatch({
618 + type: "thread.create",
619 + commandId: CommandId.make("runtime-side-chat-delete-create"),
620 + createdBy: "user",
621 + creationSource: "web",
622 + threadId: parentId,
623 + projectId,
624 + title: "Parent",
625 + modelSelection,
626 + runtimeMode: "full-access",
627 + interactionMode: "default",
628 + branch: null,
629 + worktreePath: null,
630 + });
631 + yield* orchestrator.dispatch({
632 + type: "thread.fork",
633 + commandId: CommandId.make("runtime-side-chat-delete-fork"),
634 + sourceThreadId: parentId,
635 + targetThreadId: sideChatId,
636 + sourcePoint: { type: "latest_stable" },
637 + sideChat: true,
638 + createdBy: "user",
639 + creationSource: "web",
640 + });
641 +
642 + const updateReady = yield* Deferred.make<void>();
643 + const releaseUpdate = yield* Deferred.make<void>();
644 + const deletionQueued = yield* Deferred.make<void>();
645 + const commitCommand = eventSink.commitCommand;
646 + const withLock = executor.withLock;
647 + let sideChatLockRequests = 0;
648 + const commitSpy = vi
649 + .spyOn(eventSink, "commitCommand")
650 + .mockImplementation((input) =>
651 + input.commandId === updateCommandId
652 + ? Deferred.succeed(updateReady, undefined).pipe(
653 + Effect.andThen(Deferred.await(releaseUpdate)),
654 + Effect.andThen(commitCommand(input)),
655 + )
656 + : commitCommand(input),
657 + );
658 + const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (
659 + key,
660 + effect,
661 + ) => {
662 + if (key !== sideChatId || ++sideChatLockRequests !== 2) return withLock(key, effect);
663 + return Deferred.succeed(deletionQueued, undefined).pipe(
664 + Effect.andThen(withLock(key, effect)),
665 + );
666 + };
667 + const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);
668 + yield* Effect.gen(function* () {
669 + const updateFiber = yield* orchestrator
670 + .dispatch({
671 + type: "thread.metadata.update",
672 + commandId: updateCommandId,
673 + threadId: sideChatId,
674 + title: "Updated before deletion",
675 + })
676 + .pipe(Effect.forkChild({ startImmediately: true }));
677 + yield* Effect.raceFirst(
678 + Deferred.await(updateReady),
679 + Fiber.join(updateFiber).pipe(
680 + Effect.andThen(
681 + Effect.die("The update completed before reaching its commit barrier."),
682 + ),
683 + ),
684 + );
685 + const deleteFiber = yield* orchestrator
686 + .dispatch({
687 + type: "thread.delete",
688 + commandId: CommandId.make("runtime-side-chat-delete-parent"),
689 + threadId: parentId,
690 + })
691 + .pipe(Effect.forkChild({ startImmediately: true }));
692 + yield* Effect.raceFirst(
693 + Deferred.await(deletionQueued),
694 + Fiber.join(deleteFiber).pipe(
695 + Effect.andThen(Effect.die("Parent deletion bypassed the side chat's command.")),
696 + ),
697 + );
698 + yield* Deferred.succeed(releaseUpdate, undefined);
699 + yield* Fiber.join(updateFiber);
700 + yield* Fiber.join(deleteFiber);
701 + const sideChat = yield* orchestrator.getThreadProjection(sideChatId);
702 + assert.isNotNull(sideChat.thread.deletedAt);
703 + assert.equal(sideChat.thread.title, "Updated before deletion");
704 + }).pipe(
705 + Effect.ensuring(
706 + Effect.sync(() => {
707 + commitSpy.mockRestore();
708 + lockSpy.mockRestore();
709 + }),
710 + ),
711 + );
712 + }),
713 + );
714 +
715 + // A fork from a side chat onto its parent used to lock the side chat, then the parent: the
716 + // reverse of the parent delete's order.
717 + it.effect("a parent delete and a fork from its side chat onto the parent do not deadlock", () =>
718 + Effect.gen(function* () {
719 + const projects = yield* ProjectService.ProjectService;
720 + const orchestrator = yield* Orchestrator.OrchestratorV2;
721 + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
722 + const projectId = ProjectId.make("runtime-side-chat-lock-order");
723 + const parentId = ThreadId.make("runtime-side-chat-lock-order-parent");
724 + const sideChatId = ThreadId.make("runtime-side-chat-lock-order-child");
725 + yield* projects.create({
726 + commandId: CommandId.make("runtime-side-chat-lock-order-project"),
727 + projectId,
728 + title: "Side chat lock order",
729 + workspaceRoot: "/work/side-chat-lock-order",
730 + });
731 + yield* orchestrator.dispatch({
732 + type: "thread.create",
733 + commandId: CommandId.make("runtime-side-chat-lock-order-create"),
734 + createdBy: "user",
735 + creationSource: "web",
736 + threadId: parentId,
737 + projectId,
738 + title: "Parent",
739 + modelSelection,
740 + runtimeMode: "full-access",
741 + interactionMode: "default",
742 + branch: null,
743 + worktreePath: null,
744 + });
745 + yield* orchestrator.dispatch({
746 + type: "thread.fork",
747 + commandId: CommandId.make("runtime-side-chat-lock-order-fork"),
748 + sourceThreadId: parentId,
749 + targetThreadId: sideChatId,
750 + sourcePoint: { type: "latest_stable" },
751 + sideChat: true,
752 + createdBy: "user",
753 + creationSource: "web",
754 + });
755 +
756 + const deleteHoldsParent = yield* Deferred.make<void>();
757 + const releaseDelete = yield* Deferred.make<void>();
758 + const forkWaitsForParent = yield* Deferred.make<void>();
759 + const withLock = executor.withLock;
760 + let parentLockRequests = 0;
761 + const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (
762 + key,
763 + effect,
764 + ) => {
765 + if (key !== parentId) return withLock(key, effect);
766 + // Dispatch builds locks it may not run, so count when one runs.
767 + return Effect.suspend(() =>
768 + ++parentLockRequests === 1
769 + ? withLock(
770 + key,
771 + Deferred.succeed(deleteHoldsParent, undefined).pipe(
772 + Effect.andThen(Deferred.await(releaseDelete)),
773 + Effect.andThen(effect),
774 + ),
775 + )
776 + : Deferred.succeed(forkWaitsForParent, undefined).pipe(
777 + Effect.andThen(withLock(key, effect)),
778 + ),
779 + );
780 + };
781 + const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);
782 + yield* Effect.gen(function* () {
783 + const deleteFiber = yield* orchestrator
784 + .dispatch({
785 + type: "thread.delete",
786 + commandId: CommandId.make("runtime-side-chat-lock-order-delete"),
787 + threadId: parentId,
788 + })
789 + .pipe(Effect.forkChild({ startImmediately: true }));
790 + yield* Deferred.await(deleteHoldsParent);
791 + const forkFiber = yield* orchestrator
792 + .dispatch({
793 + type: "thread.fork",
794 + commandId: CommandId.make("runtime-side-chat-lock-order-fork-back"),
795 + sourceThreadId: sideChatId,
796 + targetThreadId: parentId,
797 + sourcePoint: { type: "latest_stable" },
798 + sideChat: true,
799 + createdBy: "user",
800 + creationSource: "web",
801 + })
802 + .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
803 + yield* Deferred.await(forkWaitsForParent);
804 + yield* Deferred.succeed(releaseDelete, undefined);
805 + yield* Fiber.join(deleteFiber);
806 + yield* Fiber.join(forkFiber);
807 + assert.isNotNull((yield* orchestrator.getThreadProjection(parentId)).thread.deletedAt);
808 + assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
809 + }).pipe(Effect.ensuring(Effect.sync(() => lockSpy.mockRestore())));
810 + }),
811 + );
812 });
813
814 const layerSharedApplicationDataPlaneTest = Layer.mergeAll(
apps/server/src/pullRequest/linkedThreads.test.ts
+9 -1
@@ -9,7 +9,7 @@ import { listLinkedPullRequestThreads } from "./linkedThreads.ts";
9 const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
10
11 it.effect(
12 - "finds active and archived threads for exactly one pull request, excluding deleted and dismissed links",
12 + "finds active and archived threads for exactly one pull request, excluding deleted, dismissed, and side chat links",
13 () =>
14 Effect.gen(function* () {
15 const sql = yield* SqlClient.SqlClient;
@@ -55,6 +55,13 @@ it.effect(
55 source: "created",
56 },
57 { id: "deleted", host: "github.com", repository: "acme/web", number: 7, source: "manual" },
58 + {
59 + id: "side-chat",
60 + host: "github.com",
61 + repository: "acme/web",
62 + number: 7,
63 + source: "manual",
64 + },
65 {
66 id: "dismissed",
67 host: "github.com",
@@ -87,6 +94,7 @@ it.effect(
94 for (const fixture of fixtures) {
95 const payload = yield* encodePayload({
96 linkedPullRequest: null,
97 + ...(fixture.id === "side-chat" ? { lineage: { sideChat: true } } : {}),
98 pullRequests: [{ ...fixture, linkedAt: createdAt, snapshot: null, stack: null }],
99 });
100 yield* sql`
apps/server/src/pullRequest/linkedThreads.ts
+1
@@ -39,6 +39,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
39 WHERE json_extract(link.value, '$.number') = ${key.number}
40 AND json_extract(link.value, '$.source') != 'stack-dismissed'
41 AND t.deleted_at IS NULL
42 + AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1
43 ORDER BY "updatedAt" DESC, id ASC
44 `.pipe(NodeSqliteClient.readOnly);
45 const threads = rows
apps/server/src/relay/AgentAwarenessRelay.ts
+13 -11
@@ -1,10 +1,11 @@
1 -import type {
2 - EnvironmentId,
3 - OrchestrationV2DomainEvent,
4 - OrchestrationV2ThreadShell,
5 - OrchestrationV2TurnItem,
6 - Project,
7 - ThreadId,
1 +import {
2 + isListedThreadLineage,
3 + type EnvironmentId,
4 + type OrchestrationV2DomainEvent,
5 + type OrchestrationV2ThreadShell,
6 + type OrchestrationV2TurnItem,
7 + type Project,
8 + type ThreadId,
9 } from "@t3tools/contracts";
10 import {
11 RelayApi,
@@ -514,10 +515,11 @@ export const make = Effect.gen(function* () {
515 // Read only this thread; full shell reads would make each activity event scale with all threads.
516 const threadShell = yield* threads.getThreadShell(threadId);
517 if (
517 - threadShell?.lineage.relationshipToParent === "subagent" &&
518 + threadShell !== null &&
519 + !isListedThreadLineage(threadShell.lineage) &&
520 !(yield* Ref.get(publishedStateByThreadRef)).has(threadId)
521 ) {
520 - // Subagents have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
522 + // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
523 return;
524 }
525 const thread =
@@ -727,9 +729,9 @@ export const make = Effect.gen(function* () {
729 }
730 const environmentId = yield* serverEnvironment.getEnvironmentId;
731 const projectSnapshot = yield* projects.snapshot;
730 - // Subagents never publish awareness, and they are most threads.
732 + // Subagents and side chats never publish awareness, and subagents are most threads.
733 const topLevelThreadIds = (yield* threads.listActiveShellIndex()).flatMap((thread) =>
732 - thread.lineage.relationshipToParent === "subagent" ? [] : [thread.id],
734 + isListedThreadLineage(thread.lineage) ? [thread.id] : [],
735 );
736 const shellSnapshot = yield* threads.getShellSnapshot({
737 location: "active",
apps/server/src/serverRuntimeStartup.ts
+2 -2
@@ -3,6 +3,7 @@ import {
3 DEFAULT_MODEL,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 DEFAULT_SERVER_SETTINGS,
6 + isListedThreadLineage,
7 type ModelSelection,
8 type Project,
9 ProjectId,
@@ -280,8 +281,7 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
281 workspaceRoot: serverConfig.cwd,
282 });
283 const existingThread = (yield* threads.listActiveShellIndex()).find(
283 - (thread) =>
284 - thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
284 + (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
285 );
286 if (existingThread === undefined) {
287 const serverSettings = yield* ServerSettings.ServerSettingsService;
apps/server/src/storageCleanup.test.ts
+10 -2
@@ -721,6 +721,7 @@ describe("subagent worktree ownership", () => {
721 "pending",
722 "unrelated",
723 "fork",
724 + "side-chat",
725 "recent-activity",
726 "recent-inactive",
727 "recent-grace",
@@ -774,7 +775,12 @@ describe("subagent worktree ownership", () => {
775 rootThreadId:
776 scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId,
777 relationshipToParent:
777 - scenario === "fork" ? "fork" : scenario === "unrelated" ? null : "subagent",
778 + scenario === "fork" || scenario === "side-chat"
779 + ? "fork"
780 + : scenario === "unrelated"
781 + ? null
782 + : "subagent",
783 + ...(scenario === "side-chat" ? { sideChat: true } : {}),
784 },
785 status: scenario === "running" ? "running" : "completed",
786 pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [],
@@ -808,7 +814,9 @@ describe("subagent worktree ownership", () => {
814 root,
815 ]);
816 const report = yield* fixture.service.runNow;
811 - const removed = ["idle", "grandchild", "isolated-owner", "fork-owner"].includes(scenario);
817 + const removed = ["idle", "grandchild", "isolated-owner", "fork-owner", "side-chat"].includes(
818 + scenario,
819 + );
820 const shared = [
821 "unrelated",
822 "fork",
apps/server/src/storageCleanup.ts
+3 -2
@@ -144,7 +144,7 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
144 );
145 }
146
147 -/** Only a complete subagent chain within this worktree shares ownership. */
147 +/** Only a complete subagent or side chat chain within this worktree shares ownership. */
148 function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineage">>(
149 threads: ReadonlyArray<T>,
150 ) {
@@ -159,7 +159,8 @@ function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineag
159 while (current.id !== owner.id) {
160 if (
161 seen.has(current.id) ||
162 - current.lineage.relationshipToParent !== "subagent" ||
162 + (current.lineage.relationshipToParent !== "subagent" &&
163 + current.lineage.sideChat !== true) ||
164 current.lineage.rootThreadId !== owner.lineage.rootThreadId
165 )
166 return undefined;
apps/web/src/browser/openFileInPreview.ts
+21 -14
@@ -24,7 +24,11 @@ import {
24 setActivePreviewTab,
25 updatePreviewServerSnapshot,
26 } from "~/previewStateStore";
27 -import { selectSelectedRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";
27 +import {
28 + rightPanelHostRef,
29 + selectSelectedRightPanelSurface,
30 + useRightPanelStore,
31 +} from "~/rightPanelStore";
32
33 import { resolveBrowserDefaults } from "./browserDefaults";
34
@@ -57,23 +61,25 @@ export async function openUrlInPreview<E>(input: {
61 readonly profileId?: PreviewOpenInput["profileId"];
62 readonly background?: boolean;
63 }): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
64 + // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping.
65 + const threadRef = rightPanelHostRef(input.threadRef);
66 const defaults = await resolveBrowserDefaults().catch(
67 (cause: unknown) => new BrowserSettingsReadError({ cause }),
68 );
69 if (defaults instanceof BrowserSettingsReadError) {
70 return AsyncResult.failure(Cause.fail(defaults));
71 }
66 - const runtime = previewRuntimeFor(input.threadRef.environmentId);
67 - const previousActiveTabId = readThreadPreviewState(input.threadRef).activeTabId;
72 + const runtime = previewRuntimeFor(threadRef.environmentId);
73 + const previousActiveTabId = readThreadPreviewState(threadRef).activeTabId;
74 // The server changes the active tab, not panel selection; selection changes come from the user.
75 const selectedSurface = () =>
70 - selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, input.threadRef)
71 - ?.id ?? null;
76 + selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.id ??
77 + null;
78 const surfaceBeforeOpen = selectedSurface();
79 const result = await input.openPreview({
74 - environmentId: input.threadRef.environmentId,
80 + environmentId: threadRef.environmentId,
81 input: {
76 - threadId: input.threadRef.threadId,
82 + threadId: threadRef.threadId,
83 url: input.url,
84 viewport: defaults.viewport,
85 profileId: input.profileId ?? defaults.profileId,
@@ -81,21 +87,21 @@ export async function openUrlInPreview<E>(input: {
87 },
88 });
89 return mapAtomCommandResult(result, (snapshot) => {
84 - rememberPreviewUrl(input.threadRef, input.url);
90 + rememberPreviewUrl(threadRef, input.url);
91 if (input.background) {
86 - updatePreviewServerSnapshot(input.threadRef, snapshot);
92 + updatePreviewServerSnapshot(threadRef, snapshot);
93 // Restore focus unless the user picked a tab while opening this one.
94 if (
95 previousActiveTabId &&
90 - readThreadPreviewState(input.threadRef).activeTabId === snapshot.tabId &&
96 + readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&
97 selectedSurface() === surfaceBeforeOpen
98 ) {
93 - setActivePreviewTab(input.threadRef, previousActiveTabId);
99 + setActivePreviewTab(threadRef, previousActiveTabId);
100 }
101 return;
102 }
97 - applyPreviewServerSnapshot(input.threadRef, snapshot);
98 - useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
103 + applyPreviewServerSnapshot(threadRef, snapshot);
104 + useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
105 });
106 }
107
@@ -124,6 +130,7 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
130 ),
131 );
132 }
133 + const hostRef = rightPanelHostRef(input.threadRef);
134 const insideWorkspace =
135 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
136 const assetResult = await input.createAssetUrl({
@@ -146,7 +153,7 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
153 );
154 }
155 return openUrlInPreview({
149 - threadRef: input.threadRef,
156 + threadRef: hostRef,
157 url: assetUrl,
158 openPreview: input.openPreview,
159 });
apps/web/src/closedViewStore.test.ts
+12
@@ -54,6 +54,12 @@ describe("closedViewStore", () => {
54 threadRef: refA,
55 surface: { kind: "pull-request", id: "pull-request:x", repository: "owner/repo", number: 1 },
56 },
57 + {
58 + id: "bad",
59 + kind: "panel-tab",
60 + threadRef: refA,
61 + surface: { kind: "side-chat", id: "side-chat:x" },
62 + },
63 ])("discards incomplete saved views %j while retaining valid history", async (entry) => {
64 const id = useClosedViewStore.getState().remember(diff(refA));
65 const { storage, name } = useClosedViewStore.persist.getOptions();
@@ -85,6 +91,11 @@ describe("closedViewStore", () => {
91
92 it("removes private metadata and malformed entries from history saved by earlier versions", async () => {
93 const store = useClosedViewStore.getState();
94 + const sideChatId = store.remember({
95 + kind: "panel-tab",
96 + threadRef: refA,
97 + surface: { id: "side-chat:side", kind: "side-chat", threadId: ThreadId.make("side") },
98 + });
99 const publicId = store.remember(diff(refA));
100 const browserId = store.remember({
101 kind: "browser",
@@ -115,6 +126,7 @@ describe("closedViewStore", () => {
126 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([
127 browserId,
128 publicId,
129 + sideChatId,
130 ]);
131 const saved = JSON.stringify(await storage!.getItem(name!));
132 expect(saved).not.toContain("private.example");
apps/web/src/closedViewStore.ts
+2
@@ -83,6 +83,8 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => {
83 typeof surface.target.name === "string" &&
84 (surface.target.platform === "ios" || surface.target.platform === "android")))
85 );
86 + case "side-chat":
87 + return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`;
88 case "pull-request":
89 return (
90 typeof surface.projectId === "string" &&
apps/web/src/components/BackgroundThreadAnnouncer.tsx
+3 -3
@@ -1,5 +1,6 @@
1 import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2 import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
3 +import { isListedThreadLineage } from "@t3tools/contracts";
4 import type { AnyRouter } from "@tanstack/react-router";
5 import type { AtomRegistry } from "effect/reactivity";
6
@@ -42,9 +43,8 @@ export function startBackgroundThreadAnnouncements(
43 const now = new Date().toISOString();
44 const snapshots: BackgroundThreadSnapshot[] = [];
45 for (const thread of threads) {
45 - // Subagents have no row of their own; their requests surface on the parent.
46 - if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
47 - continue;
46 + // Subagents and side chats have no row of their own; their requests surface on the parent.
47 + if (thread.archivedAt !== null || !isListedThreadLineage(thread.lineage)) continue;
48 if (!liveEnvironmentIds.has(thread.environmentId)) continue;
49 snapshots.push({
50 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
apps/web/src/components/ChatView.tsx
+291 -171
@@ -61,6 +61,7 @@ import {
61 type AssistantCitation,
62 type ChatFileAttachment,
63 isProviderNativeSubagentThread,
64 + orchestrationV2WorktreePending,
65 type EnvironmentId,
66 type MessageId,
67 type ModelSelection,
@@ -187,6 +188,7 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
188 import { toastManager } from "./ui/toast";
189 import { projectScriptIdFromCommand } from "~/projectScripts";
190 import { newMessageId } from "~/lib/utils";
191 +import { isInSideChatPane, type SideChatParentPanel } from "~/lib/sideChatPane";
192 import {
193 NO_PROVIDER_MODEL_SELECTION,
194 providerInstanceEntriesFor,
@@ -273,6 +275,7 @@ import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
275 import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
276 import { resolveScrollToEndClearance } from "./composerFooterLayout";
277 import { ChatHeader } from "./chat/ChatHeader";
278 +import { useSideChat } from "./chat/useSideChat";
279 import { useRemoteOpenState } from "~/remoteOpen";
280 import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic";
281 import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut";
@@ -390,6 +393,8 @@ type ChatViewProps =
393 onDiffPanelOpen?: () => void;
394 reserveTitleBarControlInset?: boolean;
395 forceExpandedMobileComposer?: boolean;
396 + /** A side chat in its parent's right panel; the parent keeps the keyboard and workspace UI. */
397 + embedded?: SideChatParentPanel;
398 routeKind: "server";
399 draftId?: never;
400 }
@@ -399,6 +404,7 @@ type ChatViewProps =
404 onDiffPanelOpen?: () => void;
405 reserveTitleBarControlInset?: boolean;
406 forceExpandedMobileComposer?: boolean;
407 + embedded?: never;
408 routeKind: "draft";
409 draftId: DraftId;
410 };
@@ -413,7 +419,9 @@ export default function ChatView(props: ChatViewProps) {
419 onDiffPanelOpen,
420 reserveTitleBarControlInset = true,
421 forceExpandedMobileComposer = false,
422 + embedded: parentPanel,
423 } = props;
424 + const embedded = parentPanel !== undefined;
425 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
426 const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
427 const draftId = routeKind === "draft" ? props.draftId : null;
@@ -866,7 +874,29 @@ export default function ChatView(props: ChatViewProps) {
874 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
875 // The title it had at delegation, until this client sees the parent itself.
876 const delegatedFromThread = useQuietThreadShell(delegatedFromRef);
877 + const sideChatParentRef =
878 + activeThread?.lineage.sideChat === true && activeThread.lineage.parentThreadId !== null
879 + ? scopeThreadRef(activeThread.environmentId, activeThread.lineage.parentThreadId)
880 + : null;
881 + const sideChatParent = useQuietThreadShell(sideChatParentRef);
882 const parentThreadLink = (() => {
883 + if (sideChatParentRef !== null) {
884 + return {
885 + title: sideChatParent?.title ?? "Parent thread",
886 + sideChat: true,
887 + // Embedded, the parent is the view around it.
888 + ...(embedded
889 + ? {}
890 + : {
891 + open: (): void => {
892 + void navigate({
893 + to: "/$environmentId/$threadId",
894 + params: buildThreadRouteParams(sideChatParentRef),
895 + });
896 + },
897 + }),
898 + };
899 + }
900 if (parentSubagentThreadRef !== null) {
901 return {
902 title: parentSubagentThread?.title ?? "Parent thread",
@@ -1066,7 +1096,9 @@ export default function ChatView(props: ChatViewProps) {
1096 renderedRightPanelSurface,
1097 );
1098 const canMaximizeRightPanel = rightPanelOpen;
1069 - const rightPanelMaximized = canMaximizeRightPanel && rightPanelState.maximized === true;
1099 + // An embedded side chat has no panel; a stale maximized flag would hide its own column.
1100 + const rightPanelMaximized =
1101 + !embedded && canMaximizeRightPanel && rightPanelState.maximized === true;
1102 const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
1103 const [threadPanelPopoverHandle] = useState(PopoverCreateHandle);
1104 const [chatCanvasStore] = useState(createChatCanvasStore);
@@ -1720,13 +1752,15 @@ export default function ChatView(props: ChatViewProps) {
1752 providerSubagentModels,
1753 reportedModelSelection,
1754 );
1723 - const showComposerContextStrip = shouldShowComposerContextStrip({
1724 - isDraftHeroState,
1725 - persistInActiveThreads: settings.persistComposerContextStrip,
1726 - hasActiveProject: activeProject !== null && !showProviderSubagentBar,
1727 - isGitRepo,
1728 - showEnvironmentIndicator: showComposerEnvironmentIndicator,
1729 - });
1755 + const showComposerContextStrip =
1756 + !embedded &&
1757 + shouldShowComposerContextStrip({
1758 + isDraftHeroState,
1759 + persistInActiveThreads: settings.persistComposerContextStrip,
1760 + hasActiveProject: activeProject !== null && !showProviderSubagentBar,
1761 + isGitRepo,
1762 + showEnvironmentIndicator: showComposerEnvironmentIndicator,
1763 + });
1764 const terminalShortcutLabelOptions = {
1765 context: {
1766 terminalFocus: true,
@@ -1807,7 +1841,10 @@ export default function ChatView(props: ChatViewProps) {
1841 };
1842 const onInterruptStable = useStableCallback(onInterrupt);
1843 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window listener for the desktop snapshot event that focuses the composer
1810 - useEffect(() => subscribeSnapShotComposerFocus(focusComposerStable), [focusComposerStable]);
1844 + useEffect(
1845 + () => (embedded ? undefined : subscribeSnapShotComposerFocus(focusComposerStable)),
1846 + [embedded, focusComposerStable],
1847 + );
1848 const scheduleComposerFocus = () => {
1849 window.requestAnimationFrame(() => {
1850 focusComposer();
@@ -1968,8 +2005,8 @@ export default function ChatView(props: ChatViewProps) {
2005 : linkedThreadPullRequestKey;
2006 const activeRunningTurnId = activeRuntime?.activeRunId ?? null;
2007 useProactivePanels({
1971 - threadRef: isServerThread ? activeThreadRef : null,
1972 - enabled: settings.proactivePanelsEnabled && !shouldUsePlanSidebarSheet,
2008 + threadRef: isServerThread && !embedded ? activeThreadRef : null,
2009 + enabled: settings.proactivePanelsEnabled && !shouldUsePlanSidebarSheet && !embedded,
2010 settingsHydrated: clientSettingsHydrated,
2011 threadDetailLoading,
2012 runningTurnId: activeRunningTurnId,
@@ -2100,18 +2137,18 @@ export default function ChatView(props: ChatViewProps) {
2137
2138 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame to focus the composer DOM element when a thread opens with the terminal closed
2139 useEffect(() => {
2103 - if (!activeThread?.id || terminalUiState.terminalOpen) return;
2140 + if (embedded || !activeThread?.id || terminalUiState.terminalOpen) return;
2141 const frame = window.requestAnimationFrame(() => {
2142 focusComposerStable();
2143 });
2144 return () => {
2145 window.cancelAnimationFrame(frame);
2146 };
2110 - }, [activeThread?.id, focusComposerStable, terminalUiState.terminalOpen]);
2147 + }, [activeThread?.id, embedded, focusComposerStable, terminalUiState.terminalOpen]);
2148
2149 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus
2150 useEffect(() => {
2114 - if (!activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;
2151 + if (embedded || !activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;
2152 let frame: number | null = null;
2153 const onWindowFocus = () => {
2154 if (frame !== null) window.cancelAnimationFrame(frame);
@@ -2120,7 +2157,12 @@ export default function ChatView(props: ChatViewProps) {
2157 frame = window.requestAnimationFrame(() => {
2158 frame = null;
2159 if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return;
2123 - if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposerStable();
2160 + if (
2161 + !isInSideChatPane(document.activeElement) &&
2162 + shouldRefocusComposerOnWindowFocus(document.activeElement)
2163 + ) {
2164 + focusComposerStable();
2165 + }
2166 });
2167 });
2168 };
@@ -2129,7 +2171,13 @@ export default function ChatView(props: ChatViewProps) {
2171 window.removeEventListener("focus", onWindowFocus);
2172 if (frame !== null) window.cancelAnimationFrame(frame);
2173 };
2132 - }, [activeThread?.id, focusComposerStable, isMobileViewport, terminalUiState.terminalOpen]);
2174 + }, [
2175 + activeThread?.id,
2176 + embedded,
2177 + focusComposerStable,
2178 + isMobileViewport,
2179 + terminalUiState.terminalOpen,
2180 + ]);
2181
2182 // Promotion drops draftId while a send may still be dispatching, so key by thread.
2183 const [localDispatchThreadId, setLocalDispatchThreadId] = useState(threadId);
@@ -2334,6 +2382,7 @@ export default function ChatView(props: ChatViewProps) {
2382 pullRequestPanelTarget,
2383 threadPanelPresentation,
2384 isServerThread,
2385 + embedded,
2386 isGitRepo,
2387 browserAvailable,
2388 canOperatePreview,
@@ -2619,8 +2668,8 @@ export default function ChatView(props: ChatViewProps) {
2668 // composer effect above.
2669 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the open drawer terminal when entering a thread
2670 useEffect(() => {
2622 - if (activeThreadRef) return focusTerminalOnThreadEnter(activeThreadRef);
2623 - }, [activeThreadRef]);
2671 + if (activeThreadRef && !embedded) return focusTerminalOnThreadEnter(activeThreadRef);
2672 + }, [activeThreadRef, embedded]);
2673
2674 const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
2675 terminalFocus: getTerminalFocusOwner() !== null,
@@ -2629,7 +2678,9 @@ export default function ChatView(props: ChatViewProps) {
2678 previewOpen: previewPanelOpen,
2679 editableFocus: isEditableFocused(eventTarget),
2680 modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
2632 - composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor",
2681 + composerFocus:
2682 + document.activeElement?.getAttribute("data-testid") === "composer-editor" &&
2683 + isInSideChatPane(document.activeElement) === embedded,
2684 draftThreadRoute: routeKind === "draft",
2685 turnRunning: phase === "running",
2686 composerRequiresModifier: composerRequiresModifier(settings.sendShortcut, promptRef.current),
@@ -2650,6 +2701,8 @@ export default function ChatView(props: ChatViewProps) {
2701
2702 useChatShortcuts({
2703 enabled: activeThreadId !== null && !backgroundThread,
2704 + embedded,
2705 + composerElement: composerOverlayElement,
2706 keybindings,
2707 scriptKeybindings,
2708 getShortcutContext,
@@ -2704,13 +2757,56 @@ export default function ChatView(props: ChatViewProps) {
2757 // A focused desktop browser page forwards these chords as menu actions.
2758 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle the right panel
2759 useEffect(() => {
2760 + if (embedded) return;
2761 return window.desktopBridge?.onMenuAction((action) => {
2762 if (action === "rightPanel.toggle") toggleRightPanelStable();
2763 else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable();
2764 });
2711 - }, [toggleRightPanelStable, toggleRightPanelMaximizedStable]);
2765 + }, [embedded, toggleRightPanelStable, toggleRightPanelMaximizedStable]);
2766
2713 - usePasteToFocusComposer(activeThreadId, composerRef);
2767 + usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef);
2768 + // A delegated task is a remote thread's subagent.
2769 + const isSubagentThread =
2770 + activeThread?.lineage.relationshipToParent === "subagent" || delegatedFrom !== null;
2771 + // Side chats do not nest or start from subagents, and older servers would fork a listed thread.
2772 + const sideChatsOffered =
2773 + !embedded &&
2774 + canOperateThread &&
2775 + activeThread?.lineage.sideChat !== true &&
2776 + !isSubagentThread &&
2777 + serverConfig?.environment.capabilities.sideChats === true;
2778 + const sideChat = useSideChat({
2779 + threadRef: sideChatsOffered && isServerThread ? activeThreadRef : null,
2780 + onError: (message) => {
2781 + if (activeThread) setThreadError(activeThread.id, message);
2782 + },
2783 + });
2784 + // A maximized panel covers the terminal drawer the command runs in.
2785 + const runSideChatShellCommandStable = useStableCallback((command: string) => {
2786 + if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false);
2787 + runShellCommandStable(command);
2788 + });
2789 + // Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast.
2790 + const sideChatDisabledReason =
2791 + activeThread?.lineage.sideChat === true
2792 + ? "Side chats cannot start side chats."
2793 + : isSubagentThread
2794 + ? "Subagent threads cannot start side chats."
2795 + : serverConfig === null
2796 + ? "Side chats are not ready yet. Try again in a moment."
2797 + : serverConfig.environment.capabilities.sideChats !== true
2798 + ? "Update this environment's T3 Code server to use side chats."
2799 + : sideChatsOffered && !isServerThread
2800 + ? "Side chats start after the first message."
2801 + : sideChat.available &&
2802 + orchestrationV2WorktreePending(
2803 + activeThread?.worktreePath ?? null,
2804 + serverProjection?.runs ?? [],
2805 + )
2806 + ? "Available once the thread's worktree is set up."
2807 + : null;
2808 + const openSideChatStable = useStableCallback(() => void sideChat.open());
2809 + const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open(prompt));
2810 const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } =
2811 useTimelineRewind({
2812 environmentId,
@@ -2873,6 +2969,8 @@ export default function ChatView(props: ChatViewProps) {
2969 anchorNewTurn,
2970 acknowledgeActiveThreadWoke,
2971 handleInteractionModeChange,
2972 + onSideChat: sideChat.available ? sendSideChatStable : undefined,
2973 + sideChatDisabledReason,
2974 handleNewThreadInActiveProject,
2975 persistThreadSettingsForNextTurn,
2976 });
@@ -3011,10 +3109,7 @@ export default function ChatView(props: ChatViewProps) {
3109 !serverProjection?.messages.some((committed) => committed.id === message.id),
3110 );
3111 const scrollToEndSummary =
3014 - [
3015 - childInputNow === null ? null : "Subagent waiting",
3016 - queuedRunCount === 0 ? null : `${queuedRunCount} queued`,
3017 - ]
3112 + [childInputNow?.waitingLabel ?? null, queuedRunCount === 0 ? null : `${queuedRunCount} queued`]
3113 .filter((part) => part !== null)
3114 .join(" · ") || null;
3115 // The end of the timeline holds the thread's present and next turns: what it is doing now,
@@ -3099,7 +3194,7 @@ export default function ChatView(props: ChatViewProps) {
3194 );
3195
3196 if (!activeThread) {
3102 - return <NoActiveThreadState />;
3197 + return embedded ? null : <NoActiveThreadState />;
3198 }
3199
3200 const rightPanelContent = activeThreadRef ? (
@@ -3116,6 +3211,10 @@ export default function ChatView(props: ChatViewProps) {
3211 getShortcutContext={getShortcutContextStable}
3212 onSendAnnotation={sendPreviewAnnotationStable}
3213 onCloseSurface={closeRightPanelSurface}
3214 + sideChatParentPanel={{
3215 + openToolDiff: onOpenToolDiffStable,
3216 + runShellCommand: runSideChatShellCommandStable,
3217 + }}
3218 terminal={{
3219 launchContext: activeTerminalLaunchContext ?? null,
3220 keybindings,
@@ -3196,12 +3295,14 @@ export default function ChatView(props: ChatViewProps) {
3295 ref={setWorkspaceLayoutElement}
3296 className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
3297 >
3199 - <DeviceSetupDialogHost
3200 - threadKey={activeThreadKey}
3201 - threadRef={activeThreadRef}
3202 - state={deviceState}
3203 - />
3204 - {rightPanelControlsAtRoot ? panelLayoutControls : null}
3298 + {embedded ? null : (
3299 + <DeviceSetupDialogHost
3300 + threadKey={activeThreadKey}
3301 + threadRef={activeThreadRef}
3302 + state={deviceState}
3303 + />
3304 + )}
3305 + {rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}
3306 <div
3307 className={cn(
3308 "flex min-h-0 min-w-0 flex-col overflow-x-hidden",
@@ -3211,47 +3312,49 @@ export default function ChatView(props: ChatViewProps) {
3312 data-chat-column
3313 inert={rightPanelMaximized}
3314 >
3214 - <header
3215 - ref={threadPanelPopoverAnchorRef}
3216 - data-chat-header
3217 - className={cn(
3218 - "relative bg-background [[data-panel-animations=true]_&]:motion-safe:transition-[padding-left] [[data-panel-animations=true]_&]:motion-safe:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:motion-safe:ease-out",
3219 - isElectron
3220 - ? cn(
3221 - "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",
3222 - reserveTitleBarControlInset &&
3223 - !inlineRightPanelOwnsTitleBar &&
3224 - "wco:pr-(--workspace-native-controls-inset)",
3225 - )
3226 - : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-(--workspace-gutter-start) pr-(--workspace-gutter-end)",
3227 - COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
3228 - )}
3229 - >
3230 - {isElectron && rightPanelControlsAtRoot ? (
3231 - <span
3232 - aria-hidden
3233 - className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
3315 + {embedded ? null : (
3316 + <header
3317 + ref={threadPanelPopoverAnchorRef}
3318 + data-chat-header
3319 + className={cn(
3320 + "relative bg-background [[data-panel-animations=true]_&]:motion-safe:transition-[padding-left] [[data-panel-animations=true]_&]:motion-safe:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:motion-safe:ease-out",
3321 + isElectron
3322 + ? cn(
3323 + "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",
3324 + reserveTitleBarControlInset &&
3325 + !inlineRightPanelOwnsTitleBar &&
3326 + "wco:pr-(--workspace-native-controls-inset)",
3327 + )
3328 + : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-(--workspace-gutter-start) pr-(--workspace-gutter-end)",
3329 + COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
3330 + )}
3331 + >
3332 + {isElectron && rightPanelControlsAtRoot ? (
3333 + <span
3334 + aria-hidden
3335 + className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
3336 + />
3337 + ) : null}
3338 + {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}
3339 + {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}
3340 + <ChatHeader
3341 + activeThreadEnvironmentId={activeThread.environmentId}
3342 + activeThreadId={activeThread.id}
3343 + isServerThread={isServerThread}
3344 + activeThreadTitle={activeThread.title}
3345 + activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}
3346 + activeProject={activeProject ?? null}
3347 + parentThreadLink={headerParentThreadLink}
3348 + onOpenThread={onOpenRelatedThreadStable}
3349 + rightPanelOpen={inlineRightPanelOwnsTitleBar}
3350 + onNewThreadInProject={handleNewThreadInActiveProjectStable}
3351 + {...(activeDraftLogicalProjectKey
3352 + ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }
3353 + : {})}
3354 + {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}
3355 />
3235 - ) : null}
3236 - {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}
3237 - {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}
3238 - <ChatHeader
3239 - activeThreadEnvironmentId={activeThread.environmentId}
3240 - activeThreadId={activeThread.id}
3241 - isServerThread={isServerThread}
3242 - activeThreadTitle={activeThread.title}
3243 - activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}
3244 - activeProject={activeProject ?? null}
3245 - parentThreadLink={headerParentThreadLink}
3246 - onOpenThread={onOpenRelatedThreadStable}
3247 - rightPanelOpen={inlineRightPanelOwnsTitleBar}
3248 - onNewThreadInProject={handleNewThreadInActiveProjectStable}
3249 - {...(activeDraftLogicalProjectKey
3250 - ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }
3251 - : {})}
3252 - {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}
3253 - />
3254 - </header>
3356 + </header>
3357 + )}
3358
3359 <div className="relative flex min-h-0 min-w-0 flex-1">
3360 <ThreadFindCanvas
@@ -3310,7 +3413,9 @@ export default function ChatView(props: ChatViewProps) {
3413 citationRequest={citationRequest}
3414 citationHistory={citationHistory}
3415 onCiteAssistantText={citeAssistantTextStable}
3313 - {...(activeProject ? { onRunShellCommand: runShellCommandStable } : {})}
3416 + {...(activeProject
3417 + ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
3418 + : {})}
3419 isWorking={isWorking}
3420 runlessWorkActive={runlessWorkStartedAt !== null}
3421 isCompacting={isCompacting}
@@ -3353,12 +3458,14 @@ export default function ChatView(props: ChatViewProps) {
3458 routeThreadKey={displayedTimelineKey}
3459 displayThreadKey={displayedTimelineKey}
3460 announceTurnStatus={!isProviderSubagent}
3356 - onOpenToolDiff={onOpenToolDiffStable}
3357 - onOpenTurnDiff={onOpenTurnDiffStable}
3461 + onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
3462 + // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
3463 + {...(embedded
3464 + ? {}
3465 + : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
3466 onOpenThread={onOpenRelatedThreadStable}
3467 parentThreadLink={parentThreadLink}
3468 workflowOpening={workflowOpening}
3361 - onForkFromRun={onForkFromRunStable}
3469 supportsConversationRollback={supportsConversationRollback}
3470 threadStartCheckpointReady={threadStartCheckpointReady}
3471 availableRevertTurnCounts={availableRevertTurnCounts}
@@ -3529,6 +3636,8 @@ export default function ChatView(props: ChatViewProps) {
3636 resumeCompactionTokens={resumeCompactionTokens}
3637 keepFullHistory={keepFullHistory}
3638 onToggleKeepFullHistory={toggleKeepFullHistoryStable}
3639 + sideChatAvailable={sideChat.available}
3640 + sideChatDisabledReason={sideChatDisabledReason}
3641 onUsageLimitsCommand={
3642 usageLimitsOffered &&
3643 usageLimitsKey !== null &&
@@ -3707,10 +3816,10 @@ export default function ChatView(props: ChatViewProps) {
3816 </div>
3817 </div>
3818
3710 - {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser ? (
3819 + {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser && !embedded ? (
3820 <PreviewSessionSync threadRef={activeThreadRef} />
3821 ) : null}
3713 - {activeThreadRef && shownPreviewMiniPlayer ? (
3822 + {activeThreadRef && shownPreviewMiniPlayer && !embedded ? (
3823 <ThreadPreviewMiniPlayer
3824 key={`${activeThreadKey}:${previewMiniPlayerSourceKey(shownPreviewMiniPlayer.source)}`}
3825 threadRef={activeThreadRef}
@@ -3718,106 +3827,114 @@ export default function ChatView(props: ChatViewProps) {
3827 />
3828 ) : null}
3829
3721 - <BranchRestoreConfirmHost
3722 - threadKey={activeThreadKey}
3723 - threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}
3724 - canWriteSourceControl={canWriteSourceControl}
3725 - onConfirm={handleSwitchCheckoutToThreadStable}
3726 - />
3830 + {embedded ? null : (
3831 + <>
3832 + <BranchRestoreConfirmHost
3833 + threadKey={activeThreadKey}
3834 + threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}
3835 + canWriteSourceControl={canWriteSourceControl}
3836 + onConfirm={handleSwitchCheckoutToThreadStable}
3837 + />
3838
3728 - <ThreadDetailsPanel
3729 - anchor={threadPanelPopoverAnchorRef}
3730 - handle={threadPanelPopoverHandle}
3731 - forceNewWorktree={multipleModelSelections !== null}
3732 - environmentId={activeThread.environmentId}
3733 - threadId={activeThread.id}
3734 - projectId={activeThread.projectId}
3735 - worktreePath={activeThread.worktreePath}
3736 - isServerThread={isServerThread}
3737 - {...(draftId ? { draftId } : {})}
3738 - activeProjectName={activeProject?.title}
3739 - activeProjectScripts={activeProject ? activeProjectScripts : undefined}
3740 - preferredScriptId={
3741 - activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
3742 - }
3743 - keybindings={keybindings}
3744 - availableEditors={availableEditors}
3745 - showOpenInPicker={showOpenInPicker}
3746 - openInShortcutEnabled={
3747 - !(
3748 - rightPanelOpen &&
3749 - renderedRightPanelSurface?.kind === "file" &&
3750 - renderedRightPanelSurface.attachment === undefined
3751 - )
3752 - }
3753 - gitCwd={gitCwd}
3754 - isGitRepo={isGitRepo}
3755 - envLocked={envLocked}
3756 - availableEnvironments={logicalProjectEnvironments}
3757 - autoEnvironmentLabel={autoEnvironmentLabel}
3758 - onAutoEnvironment={
3759 - draftId &&
3760 - !envLocked &&
3761 - canAutoBalanceEnvironments &&
3762 - loadBalancingSettings.loadBalancingEnabled
3763 - ? onAutoEnvironmentStable
3764 - : undefined
3765 - }
3766 - {...(canChangeEnvironment ? { onEnvironmentChange: onEnvironmentChangeStable } : {})}
3767 - onEnvModeChange={onEnvModeChangeStable}
3768 - envMode={envMode}
3769 - {...(canOverrideServerThreadEnvMode
3770 - ? {
3771 - activeThreadBranchOverride: activeThreadBranch,
3772 - onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
3839 + <ThreadDetailsPanel
3840 + anchor={threadPanelPopoverAnchorRef}
3841 + handle={threadPanelPopoverHandle}
3842 + forceNewWorktree={multipleModelSelections !== null}
3843 + environmentId={activeThread.environmentId}
3844 + threadId={activeThread.id}
3845 + projectId={activeThread.projectId}
3846 + worktreePath={activeThread.worktreePath}
3847 + isServerThread={isServerThread}
3848 + {...(draftId ? { draftId } : {})}
3849 + activeProjectName={activeProject?.title}
3850 + activeProjectScripts={activeProject ? activeProjectScripts : undefined}
3851 + preferredScriptId={
3852 + activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
3853 }
3774 - : {})}
3775 - startFromOrigin={startFromOrigin}
3776 - onStartFromOriginChange={onStartFromOriginChange}
3777 - {...(canCheckoutPullRequestIntoThread
3778 - ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
3779 - : {})}
3780 - onComposerFocusRequest={scheduleComposerFocusStable}
3781 - {...(isServerThread && isGitRepo
3782 - ? { onOpenChanges: openChangesFromThreadPanelStable }
3783 - : {})}
3784 - onRunProjectScript={runProjectScriptStable}
3785 - onAddProjectScript={saveProjectScriptStable}
3786 - onUpdateProjectScript={updateProjectScriptStable}
3787 - onDeleteProjectScript={deleteProjectScriptStable}
3788 - usage={{
3789 - providerInstanceId: activeProviderInstanceId,
3790 - providers: providerStatuses,
3791 - sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
3792 - contextWindow: activeContextWindow,
3793 - }}
3794 - />
3854 + keybindings={keybindings}
3855 + availableEditors={availableEditors}
3856 + showOpenInPicker={showOpenInPicker}
3857 + openInShortcutEnabled={
3858 + !(
3859 + rightPanelOpen &&
3860 + renderedRightPanelSurface?.kind === "file" &&
3861 + renderedRightPanelSurface.attachment === undefined
3862 + )
3863 + }
3864 + gitCwd={gitCwd}
3865 + isGitRepo={isGitRepo}
3866 + envLocked={envLocked}
3867 + availableEnvironments={logicalProjectEnvironments}
3868 + autoEnvironmentLabel={autoEnvironmentLabel}
3869 + onAutoEnvironment={
3870 + draftId &&
3871 + !envLocked &&
3872 + canAutoBalanceEnvironments &&
3873 + loadBalancingSettings.loadBalancingEnabled
3874 + ? onAutoEnvironmentStable
3875 + : undefined
3876 + }
3877 + {...(canChangeEnvironment
3878 + ? { onEnvironmentChange: onEnvironmentChangeStable }
3879 + : {})}
3880 + onEnvModeChange={onEnvModeChangeStable}
3881 + envMode={envMode}
3882 + {...(canOverrideServerThreadEnvMode
3883 + ? {
3884 + activeThreadBranchOverride: activeThreadBranch,
3885 + onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
3886 + }
3887 + : {})}
3888 + startFromOrigin={startFromOrigin}
3889 + onStartFromOriginChange={onStartFromOriginChange}
3890 + {...(canCheckoutPullRequestIntoThread
3891 + ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
3892 + : {})}
3893 + onComposerFocusRequest={scheduleComposerFocusStable}
3894 + {...(isServerThread && isGitRepo
3895 + ? { onOpenChanges: openChangesFromThreadPanelStable }
3896 + : {})}
3897 + onRunProjectScript={runProjectScriptStable}
3898 + onAddProjectScript={saveProjectScriptStable}
3899 + onUpdateProjectScript={updateProjectScriptStable}
3900 + onDeleteProjectScript={deleteProjectScriptStable}
3901 + usage={{
3902 + providerInstanceId: activeProviderInstanceId,
3903 + providers: providerStatuses,
3904 + sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
3905 + contextWindow: activeContextWindow,
3906 + }}
3907 + />
3908
3796 - <PullRequestThreadDialogHost
3797 - threadKey={activeThreadKey}
3798 - environmentId={activeThread.environmentId}
3799 - threadId={activeThread.id}
3800 - cwd={activeProject?.workspaceRoot ?? null}
3801 - onPrepared={handlePreparedPullRequestThreadStable}
3802 - />
3909 + <PullRequestThreadDialogHost
3910 + threadKey={activeThreadKey}
3911 + environmentId={activeThread.environmentId}
3912 + threadId={activeThread.id}
3913 + cwd={activeProject?.workspaceRoot ?? null}
3914 + onPrepared={handlePreparedPullRequestThreadStable}
3915 + />
3916 + </>
3917 + )}
3918 </ThreadFindCanvas>
3919 </div>
3920
3806 - <ChatTerminalDrawers
3807 - activeThreadKey={activeThreadKey}
3808 - activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}
3809 - composerHeight={composerReservedHeight}
3810 - launchContext={activeTerminalLaunchContext ?? null}
3811 - splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
3812 - splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
3813 - newShortcutLabel={newTerminalShortcutLabel ?? undefined}
3814 - closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
3815 - keybindings={keybindings}
3816 - onAddTerminalContext={addTerminalContextToDraftStable}
3817 - />
3921 + {embedded ? null : (
3922 + <ChatTerminalDrawers
3923 + activeThreadKey={activeThreadKey}
3924 + activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}
3925 + composerHeight={composerReservedHeight}
3926 + launchContext={activeTerminalLaunchContext ?? null}
3927 + splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
3928 + splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
3929 + newShortcutLabel={newTerminalShortcutLabel ?? undefined}
3930 + closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
3931 + keybindings={keybindings}
3932 + onAddTerminalContext={addTerminalContextToDraftStable}
3933 + />
3934 + )}
3935 </div>
3936
3820 - {rightPanelPresent && activeThreadRef ? (
3937 + {rightPanelPresent && activeThreadRef && !embedded ? (
3938 <ChatRightPanel
3939 sheet={shouldUsePlanSidebarSheet}
3940 workspaceLayoutElement={workspaceLayoutElement}
@@ -3866,6 +3983,7 @@ export default function ChatView(props: ChatViewProps) {
3983 onAddPullRequest={addPullRequestSurfaceStable}
3984 onAddPullRequests={addPullRequestsSurfaceStable}
3985 onAddDevice={addDeviceSurfaceStable}
3986 + onAddSideChat={sideChatsOffered ? openSideChatStable : undefined}
3987 browserAvailable={canOperatePreview && browserAvailable}
3988 terminalAvailable={activeProject !== null && canOperateTerminal}
3989 diffAvailable={isServerThread && isGitRepo}
@@ -3873,13 +3991,15 @@ export default function ChatView(props: ChatViewProps) {
3991 pullRequestAvailable={pullRequestSurfaceAvailable}
3992 pullRequestsAvailable={pullRequestsSurfaceAvailable}
3993 deviceAvailable={activeThreadRef !== null}
3994 + sideChatAvailable={sideChat.available}
3995 + sideChatDisabledReason={sideChatDisabledReason}
3996 >
3997 {rightPanelContent}
3998 </ChatRightPanel>
3999 ) : null}
4000
4001 <RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />
3882 - <LinkPullRequestDialogHost />
4002 + {embedded ? null : <LinkPullRequestDialogHost />}
4003 <ThreadVisitWatermark threadRef={routeThreadRef} />
4004 <ExpandedImageDialogHost threadKey={routeThreadKey} />
4005 </div>
apps/web/src/components/CommandPalette.logic.ts
+2 -2
@@ -32,7 +32,7 @@ import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/fil
32 import { type ReactNode } from "react";
33 import { formatRelativeTimeLabel } from "../timestampFormat";
34 import { type Project, type SidebarThreadSummary, type Thread } from "../types";
35 -import { isSidebarSubagentThread } from "./Sidebar.logic";
35 +import { isSidebarHiddenThread } from "./Sidebar.logic";
36
37 export const RECENT_THREAD_LIMIT = 12;
38 export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
@@ -421,7 +421,7 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
421 }): CommandPaletteActionItem[] {
422 // Callers order these: recents by last use, search results by rank.
423 const visibleThreads = input.threads.filter(
424 - (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread),
424 + (thread) => thread.archivedAt === null && !isSidebarHiddenThread(thread),
425 );
426
427 return visibleThreads.map((thread) => {
apps/web/src/components/ReopenClosedViewShortcut.tsx
+5
@@ -91,6 +91,7 @@ export function ReopenClosedViewShortcut() {
91 environmentKnown: true,
92 catalogReady: true,
93 ownerExists: true,
94 + sideChatExists: true,
95 shellLive: true,
96 panel,
97 };
@@ -99,6 +100,10 @@ export function ReopenClosedViewShortcut() {
100 environmentKnown: catalog.entries.has(ref.environmentId),
101 catalogReady: catalog.isReady,
102 ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null,
103 + sideChatExists:
104 + entry.kind !== "panel-tab" ||
105 + entry.surface.kind !== "side-chat" ||
106 + readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null,
107 shellLive:
108 appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live",
109 panel,
apps/web/src/components/RightPanelTabs.tsx
+99 -3
@@ -1,6 +1,15 @@
1 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2 -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3 -import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
2 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3 +import {
4 + threadRuntimeIsActive,
5 + type EnvironmentThreadShell,
6 +} from "@t3tools/client-runtime/state/shell";
7 +import {
8 + useProjects,
9 + useQuietThreadShell,
10 + useServerConfigs,
11 + useThreadShells,
12 +} from "~/state/entities";
13 import {
14 threadPullRequestKeysEqual,
15 visibleThreadPullRequests,
@@ -12,6 +21,7 @@ import type {
21 ProjectId,
22 PullRequestState,
23 ResolvedKeybindingsConfig,
24 + ThreadId,
25 } from "@t3tools/contracts";
26 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
27 import {
@@ -33,6 +43,7 @@ import {
43 FileDiff,
44 Files,
45 Globe2,
46 + MessagesSquare,
47 Plus,
48 TerminalSquare,
49 } from "lucide-react";
@@ -130,6 +141,8 @@ export interface RightPanelTabsProps {
141 onAddPullRequest: () => void;
142 onAddPullRequests: () => void;
143 onAddDevice: () => void;
144 + /** Absent where side chats are not offered. */
145 + onAddSideChat?: (() => void) | undefined;
146 browserAvailable: boolean;
147 terminalAvailable: boolean;
148 diffAvailable: boolean;
@@ -137,6 +150,9 @@ export interface RightPanelTabsProps {
150 pullRequestAvailable: boolean;
151 pullRequestsAvailable: boolean;
152 deviceAvailable: boolean;
153 + sideChatAvailable?: boolean;
154 + /** Overrides the default reason while side chats are available but cannot start. */
155 + sideChatDisabledReason?: string | null;
156 pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
157 children: ReactNode;
158 }
@@ -163,6 +179,7 @@ const SURFACE_DISABLED_REASONS = {
179 pullRequest: "This thread's branch has no pull request yet.",
180 pullRequests: "No linked pull requests are available for this thread.",
181 device: "Devices are only available from a thread.",
182 + sideChat: "Side chats start after the first message.",
183 } as const;
184
185 // Closed keepMounted popups must stop blocking shortcuts once their exit transition ends.
@@ -187,6 +204,7 @@ const SURFACE_UNAVAILABLE_HINTS = {
204 pullRequest: "No pull request on this branch yet.",
205 pullRequests: "No linked pull requests available.",
206 device: "Available from a thread.",
207 + sideChat: "Available after the first message.",
208 } as const;
209
210 type TabContextMenuAction =
@@ -304,6 +322,8 @@ function RightPanelEmptyState(props: {
322 onAddPullRequest: () => void;
323 onAddPullRequests: () => void;
324 onAddDevice: () => void;
325 + /** Absent where side chats are not offered. */
326 + onAddSideChat?: (() => void) | undefined;
327 browserAvailable: boolean;
328 terminalAvailable: boolean;
329 diffAvailable: boolean;
@@ -311,6 +331,8 @@ function RightPanelEmptyState(props: {
331 pullRequestAvailable: boolean;
332 pullRequestsAvailable: boolean;
333 deviceAvailable: boolean;
334 + sideChatAvailable: boolean;
335 + sideChatDisabledReason: string | null;
336 }) {
337 const [highlight, setHighlight] = useState(-1);
338
@@ -372,6 +394,19 @@ function RightPanelEmptyState(props: {
394 disabledReason: SURFACE_UNAVAILABLE_HINTS.device,
395 onClick: props.onAddDevice,
396 },
397 + ...(props.onAddSideChat
398 + ? [
399 + {
400 + label: "Side chat",
401 + description: "Ask a side question while this thread keeps working.",
402 + icon: MessagesSquare,
403 + shortcut: "S",
404 + available: props.sideChatAvailable && !props.sideChatDisabledReason,
405 + disabledReason: props.sideChatDisabledReason ?? SURFACE_UNAVAILABLE_HINTS.sideChat,
406 + onClick: props.onAddSideChat,
407 + },
408 + ]
409 + : []),
410 ] as const;
411
412 type SurfaceAction = (typeof actions)[number];
@@ -557,6 +592,8 @@ function surfaceTitle(
592 return "Pull requests";
593 case "device":
594 return surface.title ?? surface.target?.name ?? "Device";
595 + case "side-chat":
596 + return "Side chat";
597 case "preview": {
598 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
599 if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
@@ -645,6 +682,8 @@ function SurfaceIcon({
682 );
683 case "pull-requests":
684 return <PullRequestGlyph.link className="size-3 shrink-0" />;
685 + case "side-chat":
686 + return <SideChatTabIcon environmentId={environmentId} threadId={surface.threadId} />;
687 case "device":
688 return surface.target?.platform === "ios" ? (
689 <AppleIcon className="size-3 shrink-0" />
@@ -656,6 +695,41 @@ function SurfaceIcon({
695 }
696 }
697
698 +/** What a side chat tab's dot shows and its title's accessible name says. */
699 +function sideChatTabState(shell: EnvironmentThreadShell | null) {
700 + if (shell === null) return null;
701 + if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") {
702 + return "needs approval";
703 + }
704 + if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") {
705 + return "needs input";
706 + }
707 + return threadRuntimeIsActive(shell.runtime) ? "running" : null;
708 +}
709 +
710 +// Static dots: a side chat tab can stay open for a whole run.
711 +function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) {
712 + const state = sideChatTabState(
713 + useQuietThreadShell(
714 + props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId),
715 + ),
716 + );
717 + return (
718 + <>
719 + <MessagesSquare className="size-3 shrink-0" />
720 + {state === null ? null : (
721 + <span
722 + className={cn(
723 + "absolute -top-0.5 -right-0.5 size-1.5 rounded-full",
724 + state === "running" ? "bg-muted-foreground" : "bg-info",
725 + )}
726 + aria-hidden
727 + />
728 + )}
729 + </>
730 + );
731 +}
732 +
733 export function resolvePullRequestTabLink(
734 threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],
735 environmentId: EnvironmentId | null,
@@ -813,7 +887,6 @@ function RightPanelTab(
887 ) {
888 const {
889 surface,
816 - title,
890 audio,
891 audioRuntimeTabId,
892 onActivate,
@@ -827,6 +900,13 @@ function RightPanelTab(
900 id: surface.id,
901 disabled: props.dragDisabled,
902 });
903 + const sideChatShell = useQuietThreadShell(
904 + surface.kind === "side-chat" && props.environmentId !== null
905 + ? scopeThreadRef(props.environmentId, surface.threadId)
906 + : null,
907 + );
908 + const title = sideChatShell?.title ?? props.title;
909 + const sideChatState = sideChatTabState(sideChatShell);
910 const content = (
911 <>
912 <PanelTabCloseButton label={`Close ${title}`} onClick={() => onClose(surface)}>
@@ -896,6 +976,7 @@ function RightPanelTab(
976 if (surface.kind === "device" && props.canRename) onStartRename(surface.id);
977 }}
978 className="cursor-pointer flex min-w-0 items-center"
979 + aria-label={sideChatState === null ? undefined : `${title}, ${sideChatState}`}
980 onClick={() => onActivate(surface)}
981 >
982 <span className="truncate">{title}</span>
@@ -1066,6 +1147,18 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1147 disabledReason: SURFACE_DISABLED_REASONS.device,
1148 onClick: props.onAddDevice,
1149 },
1150 + ...(props.onAddSideChat
1151 + ? [
1152 + {
1153 + label: "Side chat",
1154 + icon: MessagesSquare,
1155 + shortcut: "S",
1156 + available: props.sideChatAvailable === true && !props.sideChatDisabledReason,
1157 + disabledReason: props.sideChatDisabledReason ?? SURFACE_DISABLED_REASONS.sideChat,
1158 + onClick: props.onAddSideChat,
1159 + },
1160 + ]
1161 + : []),
1162 ] as const;
1163
1164 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -1440,6 +1533,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1533 onAddPullRequest={props.onAddPullRequest}
1534 onAddPullRequests={props.onAddPullRequests}
1535 onAddDevice={props.onAddDevice}
1536 + onAddSideChat={props.onAddSideChat}
1537 browserAvailable={props.browserAvailable}
1538 terminalAvailable={props.terminalAvailable}
1539 diffAvailable={props.diffAvailable}
@@ -1447,6 +1541,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1541 pullRequestAvailable={props.pullRequestAvailable}
1542 pullRequestsAvailable={props.pullRequestsAvailable}
1543 deviceAvailable={props.deviceAvailable}
1544 + sideChatAvailable={props.sideChatAvailable === true}
1545 + sideChatDisabledReason={props.sideChatDisabledReason ?? null}
1546 />
1547 ) : (
1548 props.children
apps/web/src/components/Sidebar.logic.ts
+11 -6
@@ -16,7 +16,12 @@ import {
16 type ThreadSearchShell,
17 } from "@t3tools/client-runtime/state/thread-search";
18 import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
19 -import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
19 +import {
20 + isListedThreadLineage,
21 + type ContextMenuItem,
22 + type EnvironmentId,
23 + type ThreadId,
24 +} from "@t3tools/contracts";
25 import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
26 import type { AsyncResult } from "effect/reactivity";
27 import {
@@ -590,12 +595,12 @@ export async function archiveSelectedThreadEntries<
595 return { archivedThreadKeys, mutationFailure: null, followupFailures };
596 }
597
593 -export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
594 - return thread.lineage.relationshipToParent === "subagent";
598 +export function isSidebarHiddenThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
599 + return !isListedThreadLineage(thread.lineage);
600 }
601
597 -// Subagent threads have no sidebar row, so an open subagent is represented by
598 -// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,
602 +// Subagent and side-chat threads have no sidebar row, so an open one is represented by
603 +// its nearest listed ancestor. A broken chain (missing parent, cycle,
604 // other environment) resolves to the thread itself, which then matches no row.
605 export function resolveSidebarRowThreadId(
606 threadId: ThreadId,
@@ -606,7 +611,7 @@ export function resolveSidebarRowThreadId(
611 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
612 const visited = new Set<ThreadId>();
613 let thread = findThread(threadId);
609 - while (thread !== undefined && isSidebarSubagentThread(thread)) {
614 + while (thread !== undefined && isSidebarHiddenThread(thread)) {
615 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
616 visited.add(thread.id);
617 thread = findThread(thread.lineage.parentThreadId);
apps/web/src/components/chat/AssistantSelectionToolbar.tsx
+6 -3
@@ -5,7 +5,7 @@ import {
5 type ScopedThreadRef,
6 } from "@t3tools/contracts";
7 import { QuoteIcon } from "lucide-react";
8 -import { useEffect, useLayoutEffect, useRef, useState } from "react";
8 +import { use, useEffect, useLayoutEffect, useRef, useState } from "react";
9 import { createPortal } from "react-dom";
10 import {
11 captureAssistantTextSelection,
@@ -18,6 +18,7 @@ import {
18 type SelectionActionPoint,
19 } from "~/lib/selectionActions";
20 import { Button } from "../ui/button";
21 +import { BackgroundThreadContext } from "./backgroundThread";
22
23 export function AssistantSelectionToolbar({
24 viewport,
@@ -35,6 +36,7 @@ export function AssistantSelectionToolbar({
36 } | null>(null);
37 const toolbarRef = useRef<HTMLButtonElement>(null);
38 const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);
39 + const backgroundThread = use(BackgroundThreadContext);
40
41 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint
42 useLayoutEffect(() => {
@@ -163,7 +165,8 @@ export function AssistantSelectionToolbar({
165 event.stopPropagation();
166 toolbar.focus({ preventScroll: true });
167 };
166 - document.addEventListener("keydown", focusActions, true);
168 + // Tab belongs to the foreground chat; a background timeline only follows its selection.
169 + if (!backgroundThread) document.addEventListener("keydown", focusActions, true);
170 document.addEventListener("selectionchange", actions.selectionChanged);
171 return () => {
172 document.removeEventListener("keydown", focusActions, true);
@@ -171,7 +174,7 @@ export function AssistantSelectionToolbar({
174 actions.dispose();
175 actionsRef.current = null;
176 };
174 - }, [threadRef, viewport]);
177 + }, [backgroundThread, threadRef, viewport]);
178
179 if (!selection) return null;
180 const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;
apps/web/src/components/chat/ChatComposer.tsx
+33 -9
@@ -1,6 +1,7 @@
1 import { useComposerTypingGuard } from "./useComposerTypingGuard";
2 import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences";
3 import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
4 +import { BackgroundThreadContext } from "./backgroundThread";
5 import {
6 resolveCompatibleRuntimeMode,
7 runtimeModeConfig,
@@ -52,6 +53,7 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
53 import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
54 import {
55 memo,
56 + use,
57 useEffect,
58 useEffectEvent,
59 useId,
@@ -381,6 +383,8 @@ export interface ChatComposerProps {
383 keepFullHistory: boolean;
384 onToggleKeepFullHistory: () => void;
385 onUsageLimitsCommand?: (() => void) | undefined;
386 + sideChatAvailable?: boolean;
387 + sideChatDisabledReason?: string | null;
388 environmentUnavailable: {
389 readonly label: string;
390 readonly connection: EnvironmentConnectionPresentation;
@@ -1045,14 +1049,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1049 isRevertingCheckpointRef.current = isRevertingCheckpoint;
1050 });
1051
1048 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown, blur and the desktop paste-as-text event to arm plain-text paste
1052 + const backgroundThread = use(BackgroundThreadContext);
1053 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to keydown, window blur and the desktop paste-as-text event to arm plain-text paste
1054 useEffect(() => {
1055 + // A background composer listens on its own form, so it never hears the main composer's keys.
1056 + const target: EventTarget | null = backgroundThread ? composerFormRef.current : window;
1057 + if (target === null) return;
1058 const armPasteAsTextShortcut = () => {
1059 // Electron's menu action can precede paste; browsers deliver keydown first.
1060 pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
1061 };
1054 - const onKeyDown = (event: KeyboardEvent) => {
1062 + const onKeyDown = (event: Event) => {
1063 if (
1064 + event instanceof KeyboardEvent &&
1065 event.target instanceof Node &&
1066 composerFormRef.current?.contains(event.target) &&
1067 isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
@@ -1070,22 +1079,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1079 activeElement.closest(
1080 'input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]',
1081 ) !== null;
1082 + // A background composer takes no paste-to-focus, so it arms only for its own focus.
1083 if (
1084 (activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) ||
1075 - !blocksPasteToFocus
1085 + (!blocksPasteToFocus && !backgroundThread)
1086 ) {
1087 armPasteAsTextShortcut();
1088 }
1089 };
1080 - window.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
1081 - window.addEventListener("keydown", onKeyDown, true);
1082 - window.addEventListener("blur", onBlur);
1090 + target.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
1091 + target.addEventListener("keydown", onKeyDown, true);
1092 + // An arm lasts a second, so a background composer can skip the window blur reset.
1093 + if (!backgroundThread) window.addEventListener("blur", onBlur);
1094 return () => {
1084 - window.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
1085 - window.removeEventListener("keydown", onKeyDown, true);
1095 + target.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
1096 + target.removeEventListener("keydown", onKeyDown, true);
1097 window.removeEventListener("blur", onBlur);
1098 };
1088 - }, []);
1099 + }, [backgroundThread]);
1100
1101 const composerSendState = deriveComposerSendState({
1102 prompt,
@@ -1120,6 +1131,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1131 pullRequestRepository,
1132 threadPullRequests,
1133 planModeUiEnabled,
1134 + sideChatAvailable: props.sideChatAvailable === true,
1135 + sideChatDisabledReason: props.sideChatDisabledReason ?? null,
1136 compactSlashCommandAvailable,
1137 selectedProvider,
1138 selectedProviderSkills,
@@ -1848,6 +1861,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1861 }
1862 return;
1863 }
1864 + if (item.command === "side" || item.command === "btw") {
1865 + if (props.sideChatDisabledReason) return;
1866 + const applied = applyPromptReplacement(
1867 + trigger.rangeStart,
1868 + trigger.rangeEnd,
1869 + `/${item.command} `,
1870 + { expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd) },
1871 + );
1872 + if (applied) setComposerHighlightedItemId(null);
1873 + return;
1874 + }
1875 if (!planModeUiEnabled) return;
1876 void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
1877 const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+2
@@ -9,6 +9,7 @@ import { CheckboxMark } from "../ui/checkbox";
9 import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
10 import { Kbd } from "../ui/kbd";
11 import { cn } from "~/lib/utils";
12 +import { isInSideChatPane } from "~/lib/sideChatPane";
13 import { ComposerBanner } from "./ComposerBanner";
14 import ChatMarkdown from "../ChatMarkdown";
15
@@ -151,6 +152,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
152 const handler = (event: globalThis.KeyboardEvent) => {
153 if (event.metaKey || event.ctrlKey || event.altKey) return;
154 const target = event.target;
155 + if (isInSideChatPane(target)) return;
156 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
157 return;
158 }
apps/web/src/components/chat/MessagesTimeline.tsx
+15 -4
@@ -53,7 +53,13 @@ import {
53 import { type PendingApproval, type TimelineEntry } from "../../session-logic";
54 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
55 import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
56 -import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react";
56 +import {
57 + ArrowRightIcon,
58 + BotIcon,
59 + CircleAlertIcon,
60 + MessagesSquareIcon,
61 + Minimize2Icon,
62 +} from "lucide-react";
63 import { ChevronDown, ChevronRight } from "lucide";
64 import { MorphIcon } from "~/components/MorphIcon";
65 import { Skeleton } from "../ui/skeleton";
@@ -251,9 +257,14 @@ interface MessagesTimelineProps {
257 onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
258 renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];
259 turnItemSource?: TimelineRowSharedState["turnItemSource"];
254 - /** The thread this one is a subagent of; `open` is absent when it cannot be opened from here. */
260 + /**
261 + * The thread this one is a subagent or side chat of; `open` is absent when it cannot be
262 + * opened from here.
263 + */
264 parentThreadLink?: {
265 readonly title: string;
266 + /** A side chat's inherited rows collapse into this link. */
267 + readonly sideChat?: boolean;
268 /** Where it runs, when that is another environment. */
269 readonly environmentLabel?: string;
270 readonly open?: () => void;
@@ -1098,13 +1109,13 @@ const ConversationTimeline = memo(function ConversationTimeline({
1109 <div className="messages-timeline-row-frame">
1110 <div className="chat-content-lane pt-1 sm:pt-2">
1111 <TimelineSystemDivider
1101 - label="Subagent of"
1112 + label={parentThreadLink.sideChat ? "Context from" : "Subagent of"}
1113 detail={
1114 parentThreadLink.environmentLabel === undefined
1115 ? parentThreadLink.title
1116 : `${parentThreadLink.title} on ${parentThreadLink.environmentLabel}`
1117 }
1107 - icon={BotIcon}
1118 + icon={parentThreadLink.sideChat ? MessagesSquareIcon : BotIcon}
1119 {...(parentThreadLink.open === undefined
1120 ? {}
1121 : { actionLabel: "Open parent thread", onAction: parentThreadLink.open })}
apps/web/src/components/chat/RightPanelSurfaceContent.tsx
+14
@@ -10,8 +10,10 @@ import type {
10 } from "@t3tools/contracts";
11 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
12 import { lazy, Suspense } from "react";
13 +import SideChatPane from "./SideChatPane";
14 import type { ComposerImageAttachment, DraftId } from "../../composerDraftStore";
15 import type { ShortcutMatchContext } from "../../keybindings";
16 +import type { SideChatParentPanel } from "../../lib/sideChatPane";
17 import { type RightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
18 import {
19 PersistentThreadTerminalPanel,
@@ -75,6 +77,7 @@ export function RightPanelSurfaceContent(props: {
77 readonly terminal: RightPanelTerminalProps;
78 readonly pullRequest: RightPanelPullRequestProps;
79 readonly files: RightPanelFileProps;
80 + readonly sideChatParentPanel: SideChatParentPanel;
81 }) {
82 const { surface, threadRef, visible } = props;
83 if (surface === null) return null;
@@ -165,6 +168,17 @@ export function RightPanelSurfaceContent(props: {
168 }
169 case "pull-requests":
170 return <ThreadPullRequestsPanel threadRef={threadRef} />;
171 + case "side-chat":
172 + // Not lazy: revealing a suspended tiptap editor tears down its view and crashes the composer.
173 + return (
174 + <SideChatPane
175 + key={surface.id}
176 + parentRef={threadRef}
177 + threadId={surface.threadId}
178 + parentPanel={props.sideChatParentPanel}
179 + onClose={() => props.onCloseSurface(surface)}
180 + />
181 + );
182 case "device":
183 return (
184 <Suspense fallback={null}>
apps/web/src/components/chat/SideChatPane.tsx new
+179
@@ -0,0 +1,179 @@
1 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 +import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
3 +import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
4 +import {
5 + isAtomCommandInterrupted,
6 + settlePromise,
7 + squashAtomCommandFailure,
8 +} from "@t3tools/client-runtime/state/runtime";
9 +import {
10 + AuthOrchestrationOperateScope,
11 + type ScopedThreadRef,
12 + type ThreadId,
13 +} from "@t3tools/contracts";
14 +import { Trash2Icon, XIcon } from "lucide-react";
15 +import { useEffect, useState } from "react";
16 +
17 +import { ComposerHandleContext } from "../../composerHandleContext";
18 +import { useClientSettings } from "../../hooks/useSettings";
19 +import type { SideChatParentPanel } from "../../lib/sideChatPane";
20 +import { readLocalApi } from "../../localApi";
21 +import { hostRightPanel, useRightPanelStore } from "../../rightPanelStore";
22 +import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities";
23 +import { useEnvironmentScope } from "../../state/session";
24 +import { useEnvironmentShellHasSnapshot } from "../../state/shell";
25 +import { threadEnvironment } from "../../state/threads";
26 +import { useAtomCommand } from "../../state/use-atom-command";
27 +import ChatView from "../ChatView";
28 +import { Button } from "../ui/button";
29 +import { toastManager } from "../ui/toast";
30 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
31 +import { BackgroundThreadContext } from "./backgroundThread";
32 +
33 +/** A side chat tab: its title, Bring back, Delete and Close, over the side chat's own chat. */
34 +export default function SideChatPane(props: {
35 + readonly parentRef: ScopedThreadRef;
36 + readonly threadId: ThreadId;
37 + readonly parentPanel: SideChatParentPanel;
38 + readonly onClose: () => void;
39 +}) {
40 + const { parentRef, threadId } = props;
41 + const threadRef = scopeThreadRef(parentRef.environmentId, threadId);
42 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store
43 + useEffect(
44 + () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef),
45 + [parentRef, threadId],
46 + );
47 + const shell = useQuietThreadShell(threadRef);
48 + const parent = useQuietThreadShell(parentRef);
49 + const snapshotLoaded = useEnvironmentShellHasSnapshot(parentRef.environmentId);
50 + const projection = useQuietThreadProjection(shell === null ? null : threadRef)?.projection;
51 + const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope);
52 + const mergeBack = useAtomCommand(threadEnvironment.mergeBack, { reportFailure: false });
53 + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
54 + const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
55 + const [bringingBack, setBringingBack] = useState(false);
56 + const [deleting, setDeleting] = useState(false);
57 + const mergeRun = projection ? resolveLatestMergeBackRun(projection) : null;
58 + // A pending merge-back would fail the main thread's queued message, so the server refuses it.
59 + const bringBackBlockedReason = !canOperate
60 + ? "This connection cannot change threads."
61 + : threadRuntimeIsActive(parent?.runtime)
62 + ? "Available when the main thread is idle."
63 + : mergeRun === null
64 + ? "Available after a finished reply."
65 + : null;
66 +
67 + const bringBack = async () => {
68 + if (bringBackBlockedReason !== null || mergeRun === null || bringingBack) return;
69 + setBringingBack(true);
70 + const result = await mergeBack({
71 + environmentId: parentRef.environmentId,
72 + input: { sourceThreadId: threadId, targetThreadId: parentRef.threadId, runId: mergeRun.id },
73 + });
74 + setBringingBack(false);
75 + if (result._tag === "Success") {
76 + toastManager.add({
77 + type: "success",
78 + title: "Brought back",
79 + description: "The main thread gets this side chat with your next message there.",
80 + });
81 + } else if (!isAtomCommandInterrupted(result)) {
82 + const error = squashAtomCommandFailure(result);
83 + toastManager.add({
84 + type: "error",
85 + title: "Could not bring back the side chat",
86 + ...(error instanceof Error ? { description: error.message } : {}),
87 + });
88 + }
89 + };
90 +
91 + const deleteSideChat = async () => {
92 + if (!canOperate || shell === null || deleting) return;
93 + if (confirmThreadDelete) {
94 + const api = readLocalApi();
95 + if (!api) return;
96 + const confirmed = await settlePromise(() =>
97 + api.dialogs.confirm(
98 + [
99 + `Delete side chat "${shell.title}"?`,
100 + "This permanently clears its conversation history.",
101 + ].join("\n"),
102 + { variant: "destructive" },
103 + ),
104 + );
105 + if (confirmed._tag === "Failure" || !confirmed.value) return;
106 + }
107 + setDeleting(true);
108 + const result = await deleteThread({
109 + environmentId: parentRef.environmentId,
110 + input: { threadId },
111 + });
112 + setDeleting(false);
113 + if (result._tag === "Success") {
114 + useRightPanelStore.getState().closeSurface(parentRef, `side-chat:${threadId}`);
115 + } else if (!isAtomCommandInterrupted(result)) {
116 + const error = squashAtomCommandFailure(result);
117 + toastManager.add({
118 + type: "error",
119 + title: "Could not delete the side chat",
120 + ...(error instanceof Error ? { description: error.message } : {}),
121 + });
122 + }
123 + };
124 +
125 + return (
126 + <div data-side-chat-pane className="flex h-full min-h-0 flex-col">
127 + <div className="flex h-9 shrink-0 items-center gap-1 border-b border-border pr-1 pl-3">
128 + <span className="min-w-0 flex-1 truncate text-xs font-medium">
129 + {shell?.title ?? "Side chat"}
130 + </span>
131 + <Tooltip>
132 + <TooltipTrigger
133 + render={
134 + <Button
135 + variant="ghost"
136 + size="xs"
137 + aria-disabled={bringBackBlockedReason !== null || bringingBack || undefined}
138 + onClick={() => void bringBack()}
139 + >
140 + Bring back
141 + </Button>
142 + }
143 + />
144 + <TooltipPopup side="bottom">
145 + {bringBackBlockedReason ?? "Adds this side chat to the main thread's next message."}
146 + </TooltipPopup>
147 + </Tooltip>
148 + <Button
149 + variant="ghost"
150 + size="icon-xs"
151 + aria-label="Delete side chat"
152 + disabled={!canOperate || shell === null || deleting}
153 + onClick={() => void deleteSideChat()}
154 + >
155 + <Trash2Icon />
156 + </Button>
157 + <Button variant="ghost" size="icon-xs" aria-label="Close side chat" onClick={props.onClose}>
158 + <XIcon />
159 + </Button>
160 + </div>
161 + {shell === null ? (
162 + snapshotLoaded ? (
163 + <p className="p-3 text-xs text-muted-foreground">This side chat was deleted.</p>
164 + ) : null
165 + ) : (
166 + <BackgroundThreadContext value>
167 + <ComposerHandleContext value={null}>
168 + <ChatView
169 + environmentId={parentRef.environmentId}
170 + threadId={threadId}
171 + routeKind="server"
172 + embedded={props.parentPanel}
173 + />
174 + </ComposerHandleContext>
175 + </BackgroundThreadContext>
176 + )}
177 + </div>
178 + );
179 +}
apps/web/src/components/chat/ThreadActivityBanners.tsx
+5 -2
@@ -30,12 +30,12 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30 import type { ComposerBannerStackItem } from "./ComposerBannerStack";
31 import type { ThreadNowItem } from "./ThreadNow";
32
33 -/** Subagents waiting on the user, unless the parent is itself waiting on them. */
33 +/** Subagents and side chats waiting on the user, unless the parent is itself waiting on them. */
34 export function childInputNowItem(input: {
35 readonly childThreadInputs: ReadonlyArray<EnvironmentThreadShell>;
36 readonly parentAwaitingUser: boolean;
37 readonly onOpenThread: (threadId: ThreadId) => void;
38 -}): ThreadNowItem | null {
38 +}): (ThreadNowItem & { readonly waitingLabel: string }) | null {
39 const { childThreadInputs, onOpenThread } = input;
40 const first = childThreadInputs[0];
41 if (!first || input.parentAwaitingUser) return null;
@@ -48,6 +48,9 @@ export function childInputNowItem(input: {
48 <MessageCircleIcon className="text-info-foreground" />
49 ),
50 title: childThreadInputsTitle(childThreadInputs),
51 + waitingLabel: childThreadInputs.every((child) => child.lineage.sideChat === true)
52 + ? "Side chat waiting"
53 + : "Subagent waiting",
54 description: childThreadInputs.map((child, index) => (
55 <Fragment key={child.id}>
56 {index > 0 ? " " : null}
apps/web/src/components/chat/ThreadDetailsCard.tsx
+3 -3
@@ -78,10 +78,10 @@ export function ThreadDetailsCard({
78 const measure = () => {
79 const frame = element.closest<HTMLElement>("[data-thread-details-card]");
80 const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0);
81 - // PR lists and lineage scroll as they expand. Counting them toward density would hide
82 - // the section and workspace controls when the user asks to see more rows.
81 + // PR lists, lineage and side chats scroll as they expand. Counting them toward density
82 + // would hide the section and workspace controls when the user asks to see more rows.
83 const lists = element.querySelectorAll<HTMLElement>(
84 - "[data-thread-relationships-panel], [data-thread-details-pr-list]",
84 + "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list]",
85 );
86 const fittingHeight =
87 next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0);
apps/web/src/components/chat/ThreadDetailsPanel.tsx
+3 -1
@@ -249,10 +249,12 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
249 />
250 ) : null}
251
252 - {density === "full" && !props.draftId && visible.lineage ? (
252 + {density === "full" && !props.draftId && (visible.lineage || visible.sideChats) ? (
253 <ThreadRelationshipsPanel
254 environmentId={props.environmentId}
255 threadId={props.threadId}
256 + showLineage={visible.lineage}
257 + showSideChats={visible.sideChats}
258 />
259 ) : null}
260
apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
+12 -2
@@ -65,7 +65,12 @@ it.each([
65 setup();
66 await using screen = await render(
67 <ToastProvider timeout={0}>
68 - <ThreadRelationshipsPanel environmentId={environmentId} threadId={threadId} />
68 + <ThreadRelationshipsPanel
69 + environmentId={environmentId}
70 + threadId={threadId}
71 + showLineage
72 + showSideChats
73 + />
74 </ToastProvider>,
75 );
76
@@ -93,7 +98,12 @@ it.each([
98 setup();
99 await using screen = await render(
100 <ToastProvider timeout={0}>
96 - <ThreadRelationshipsPanel environmentId={environmentId} threadId={threadId} />
101 + <ThreadRelationshipsPanel
102 + environmentId={environmentId}
103 + threadId={threadId}
104 + showLineage
105 + showSideChats
106 + />
107 </ToastProvider>,
108 { router: "/environment/fork" },
109 );
apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+351 -324
@@ -49,6 +49,7 @@ import {
49 ChevronDownIcon,
50 CornerLeftUpIcon,
51 GitForkIcon,
52 + MessagesSquareIcon,
53 MoreHorizontalIcon,
54 PlusIcon,
55 SquareIcon,
@@ -71,6 +72,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
72 import { AgentElapsed } from "./AgentElapsed";
73 import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
74 import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow";
75 +import { openSideChatTab } from "../../lib/sideChatPane";
76
77 import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
78 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -349,6 +351,8 @@ function DelegatedFromRow(props: {
351 export function ThreadRelationshipsPanel(props: {
352 readonly environmentId: EnvironmentId;
353 readonly threadId: ThreadId;
354 + readonly showLineage: boolean;
355 + readonly showSideChats: boolean;
356 }) {
357 const ref = scopeThreadRef(props.environmentId, props.threadId);
358 const projection = useThreadProjection(ref)?.projection ?? null;
@@ -449,9 +453,12 @@ export function ThreadRelationshipsPanel(props: {
453 related = [],
454 active = [],
455 previous = [],
452 - } = groupBy(relationshipRows, ({ edge }) => {
453 - if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId))
454 - return "related";
456 + sideChats = [],
457 + } = groupBy(relationshipRows, ({ threadId, edge }) => {
458 + const isParent = isParentThreadRelationship(edge, props.threadId);
459 + if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true)
460 + return "sideChats";
461 + if (edge.kind !== "subagent" || isParent) return "related";
462 return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(
463 edge.status ?? "",
464 )
@@ -476,16 +483,25 @@ export function ThreadRelationshipsPanel(props: {
483 // A linked environment's agent may have delegated this thread from there.
484 const delegatedFrom = currentThread?.delegatedFrom;
485
479 - if (
480 - relationshipRows.length === 0 &&
481 - runningCount === 0 &&
482 - remoteSubagents.length === 0 &&
483 - delegatedFrom === undefined
484 - ) {
486 + const lineageVisible =
487 + props.showLineage &&
488 + (related.length > 0 ||
489 + active.length > 0 ||
490 + previous.length > 0 ||
491 + runningCount > 0 ||
492 + remoteSubagents.length > 0 ||
493 + delegatedFrom !== undefined ||
494 + // Disconnect lives in this heading, so a thread with only side chats still shows it.
495 + (canDetach && sideChats.length > 0));
496 + const sideChatsVisible = props.showSideChats && sideChats.length > 0;
497 + const runningSideChats = sideChats.filter(({ edge }) => edge.status === "running").length;
498 +
499 + if (!lineageVisible && !sideChatsVisible) {
500 return null;
501 }
502
503 const openThread = (threadId: ThreadId) => {
504 + if (openSideChatTab(ref, graph.nodes.get(threadId)?.thread ?? null)) return;
505 void navigate({
506 to: "/$environmentId/$threadId",
507 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
@@ -572,327 +588,338 @@ export function ThreadRelationshipsPanel(props: {
588 ? null
589 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
590
575 - return (
576 - <ThreadDetailsSection
577 - headingId="thread-details-lineage-heading"
578 - title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
579 - // A lone "Previous agents" row names itself; the heading returns for status or actions.
580 - showHeading={
581 - runningCount > 0 ||
582 - canDetach ||
583 - related.length > 0 ||
584 - active.length > 0 ||
585 - delegatedFrom !== undefined
586 - }
587 - data-thread-relationships-panel
588 - actions={
589 - canDetach ? (
590 - <Menu>
591 - <MenuTrigger
592 - render={
593 - <ThreadDetailsControl
594 - size="icon-xs"
595 - variant="ghost"
596 - part="icon"
597 - aria-label="More thread actions"
598 - disabled={busyAction !== null}
599 - />
600 - }
601 - >
602 - <MoreHorizontalIcon className="size-3.5" />
603 - </MenuTrigger>
604 - <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
605 - <MenuItem onClick={() => void detach()}>
606 - <UnplugIcon className="size-3.5" />
607 - Disconnect agent session
608 - </MenuItem>
609 - </MenuPopup>
610 - </Menu>
611 - ) : null
612 - }
613 - >
614 - {delegatedFrom === undefined ? null : (
615 - <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
616 - <DelegatedFromRow
617 - delegatedFrom={delegatedFrom}
618 - fallbackLabel={currentThread?.linkOrigin?.label}
619 - />
620 - </ThreadLineageRowList>
621 - )}
622 - {groups.map((group) => (
623 - <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
624 - {(visibleRows) =>
625 - visibleRows.map(({ threadId, edge }) => {
626 - const node = graph.nodes.get(threadId);
627 - const isSubagent = edge.kind === "subagent";
628 - const isMergeTarget = threadId === mergeTargetThreadId;
629 - const isParent = isParentThreadRelationship(edge, props.threadId);
630 - const rowStatus =
631 - (isParent && threadId === parentRef?.threadId
632 - ? (node?.thread?.activityRunStatus ?? parentNativeStatus)
633 - : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });
634 - const RelationshipIcon = isParent
635 - ? CornerLeftUpIcon
636 - : isSubagent
637 - ? BotIcon
638 - : GitForkIcon;
639 - const relationship = relationshipLabel(edge, props.threadId);
640 - const projectedAgent =
641 - isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
642 - const workflowGroup =
643 - projectedAgent === undefined
644 - ? undefined
645 - : workflowGroupsById.get(projectedAgent.id);
646 - const agent = workflowGroup
647 - ? projectedAgent
648 - : currentSubagent(projectedAgent, node?.thread);
649 - const failed = rowStatus === "failed" || rowStatus === "error";
650 - const canStop =
651 - agent &&
652 - (agent.origin === "app_owned" ||
653 - (agent.origin === "provider_native" &&
654 - agent.driver === "claudeAgent" &&
655 - agent.runId != null &&
656 - agent.nativeTaskRef?.strength === "strong" &&
657 - agent.nativeTaskRef.nativeId !== null &&
658 - ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
659 - agent.startedAt &&
660 - ["pending", "running", "waiting"].includes(agent.status);
661 - const threadTitle = relationshipThreadTitle({
662 - title:
663 - workflowGroup?.workflow.workflowName ??
664 - node?.thread?.title ??
665 - agent?.title ??
666 - threadId,
667 - isSubagent,
668 - });
669 - const provider = providers?.find(
670 - (entry) =>
671 - entry.instanceId ===
672 - (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
673 - );
674 - const providerDriver = agent?.driver ?? provider?.driver;
675 - const canStopWorkflow =
676 - canOperateWorkflow &&
677 - workflowGroup?.workflow.status === "running" &&
678 - agent?.origin === "provider_native" &&
679 - providerDriver === "claudeAgent";
680 - const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)
681 - ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
682 - : "";
683 - const project = projects.find((project) => project.id === node?.thread?.projectId);
684 - const relationshipHint = node?.missing
685 - ? "This related thread is unavailable"
686 - : `Open ${relationship.toLowerCase()} in this chat`;
687 - const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
688 - const relationshipTooltip = agent ? (
689 - <SubagentTooltipContent
690 - title={threadTitle}
691 - model={agent.model}
692 - providerInstanceId={agent.providerInstanceId}
693 - origin={agent.origin}
694 - modelSelection={agent.modelSelection}
695 - provider={provider}
696 - providers={providers}
697 - driver={providerDriver}
698 - elapsed={<AgentElapsed agent={agent} />}
699 - status={agent.status}
700 - result={agent.result}
701 - progress={agent.progress}
702 - parentThread={currentThread ?? undefined}
703 - childThread={node?.thread ?? undefined}
704 - parentProject={currentProject}
705 - childProject={project}
706 - />
707 - ) : (
708 - relationshipHint
709 - );
710 - const relationshipContent = (
711 - <>
712 - <ThreadRelationshipIcon
713 - driver={isSubagent && !isParent ? providerDriver : undefined}
714 - provider={provider}
715 - fallbackIcon={RelationshipIcon}
716 - status={rowStatus}
591 + const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {
592 + const node = graph.nodes.get(threadId);
593 + const isSubagent = edge.kind === "subagent";
594 + const isMergeTarget = threadId === mergeTargetThreadId;
595 + const isParent = isParentThreadRelationship(edge, props.threadId);
596 + const rowStatus =
597 + (isParent && threadId === parentRef?.threadId
598 + ? (node?.thread?.activityRunStatus ?? parentNativeStatus)
599 + : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });
600 + const RelationshipIcon = isParent
601 + ? CornerLeftUpIcon
602 + : isSubagent
603 + ? BotIcon
604 + : node?.thread?.lineage.sideChat === true
605 + ? MessagesSquareIcon
606 + : GitForkIcon;
607 + const relationship =
608 + node?.thread?.lineage.sideChat === true && !isParent
609 + ? "Side chat"
610 + : relationshipLabel(edge, props.threadId);
611 + const projectedAgent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
612 + const workflowGroup =
613 + projectedAgent === undefined ? undefined : workflowGroupsById.get(projectedAgent.id);
614 + const agent = workflowGroup ? projectedAgent : currentSubagent(projectedAgent, node?.thread);
615 + const failed = rowStatus === "failed" || rowStatus === "error";
616 + const canStop =
617 + agent &&
618 + (agent.origin === "app_owned" ||
619 + (agent.origin === "provider_native" &&
620 + agent.driver === "claudeAgent" &&
621 + agent.runId != null &&
622 + agent.nativeTaskRef?.strength === "strong" &&
623 + agent.nativeTaskRef.nativeId !== null &&
624 + ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
625 + agent.startedAt &&
626 + ["pending", "running", "waiting"].includes(agent.status);
627 + const threadTitle = relationshipThreadTitle({
628 + title:
629 + workflowGroup?.workflow.workflowName ?? node?.thread?.title ?? agent?.title ?? threadId,
630 + isSubagent,
631 + });
632 + const provider = providers?.find(
633 + (entry) =>
634 + entry.instanceId === (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
635 + );
636 + const providerDriver = agent?.driver ?? provider?.driver;
637 + const canStopWorkflow =
638 + canOperateWorkflow &&
639 + workflowGroup?.workflow.status === "running" &&
640 + agent?.origin === "provider_native" &&
641 + providerDriver === "claudeAgent";
642 + const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)
643 + ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
644 + : "";
645 + const project = projects.find((project) => project.id === node?.thread?.projectId);
646 + const relationshipHint = node?.missing
647 + ? "This related thread is unavailable"
648 + : `Open ${relationship.toLowerCase()} in this chat`;
649 + const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
650 + const relationshipTooltip = agent ? (
651 + <SubagentTooltipContent
652 + title={threadTitle}
653 + model={agent.model}
654 + providerInstanceId={agent.providerInstanceId}
655 + origin={agent.origin}
656 + modelSelection={agent.modelSelection}
657 + provider={provider}
658 + providers={providers}
659 + driver={providerDriver}
660 + elapsed={<AgentElapsed agent={agent} />}
661 + status={agent.status}
662 + result={agent.result}
663 + progress={agent.progress}
664 + parentThread={currentThread ?? undefined}
665 + childThread={node?.thread ?? undefined}
666 + parentProject={currentProject}
667 + childProject={project}
668 + />
669 + ) : (
670 + relationshipHint
671 + );
672 + const relationshipContent = (
673 + <>
674 + <ThreadRelationshipIcon
675 + driver={isSubagent && !isParent ? providerDriver : undefined}
676 + provider={provider}
677 + fallbackIcon={RelationshipIcon}
678 + status={rowStatus}
679 + />
680 + <span className="min-w-0 flex-1">
681 + <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
682 + {threadTitle}
683 + </span>
684 + </span>
685 + {agent ? null : (
686 + <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
687 + )}
688 + {agent && !failed && (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (
689 + <span
690 + className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}
691 + >
692 + <AgentElapsed agent={agent} compact />
693 + </span>
694 + ) : !isMergeTarget ? (
695 + <span
696 + className={
697 + workflowGroup
698 + ? "sr-only"
699 + : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`
700 + }
701 + >
702 + {threadRelationshipStatusLabel(rowStatus)}
703 + </span>
704 + ) : null}
705 + </>
706 + );
707 + const relationshipLink = (
708 + <Tooltip>
709 + <TooltipTrigger
710 + delay={200}
711 + render={
712 + <ThreadDetailsControl
713 + size="sm"
714 + variant="ghost"
715 + part={workflowGroup ? "primary" : "row"}
716 + disabled={node?.missing === true}
717 + onClick={() => openThread(threadId)}
718 + />
719 + }
720 + >
721 + {relationshipContent}
722 + </TooltipTrigger>
723 + <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
724 + </Tooltip>
725 + );
726 + if (workflowGroup && agent) {
727 + return (
728 + <ThreadLineageWorkflowRow
729 + key={threadId}
730 + group={workflowGroup}
731 + providerInstanceId={agent.providerInstanceId}
732 + provider={provider}
733 + providers={providers}
734 + driver={providerDriver}
735 + onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}
736 + isThreadAvailable={(memberThreadId) =>
737 + graph.nodes.get(memberThreadId as ThreadId)?.missing === false
738 + }
739 + onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}
740 + stopping={stoppingId === agent.id}
741 + stopDisabled={stoppingId !== null}
742 + header={relationshipLink}
743 + />
744 + );
745 + }
746 + return (
747 + <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
748 + {isMergeTarget ? (
749 + <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
750 + <Tooltip>
751 + <TooltipTrigger
752 + delay={200}
753 + render={
754 + <ThreadDetailsControl
755 + size="sm"
756 + variant="ghost"
757 + part="primary"
758 + aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}
759 + disabled={node?.missing === true}
760 + onClick={() => openThread(threadId)}
761 />
718 - <span className="min-w-0 flex-1">
719 - <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
720 - {threadTitle}
721 - </span>
722 - </span>
723 - {agent ? null : (
724 - <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
725 - )}
726 - {agent &&
727 - !failed &&
728 - (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (
729 - <span
730 - className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}
731 - >
732 - <AgentElapsed agent={agent} compact />
733 - </span>
734 - ) : !isMergeTarget ? (
735 - <span
736 - className={
737 - workflowGroup
738 - ? "sr-only"
739 - : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`
740 - }
741 - >
742 - {threadRelationshipStatusLabel(rowStatus)}
743 - </span>
744 - ) : null}
745 - </>
746 - );
747 - const relationshipLink = (
748 - <Tooltip>
749 - <TooltipTrigger
750 - delay={200}
751 - render={
752 - <ThreadDetailsControl
753 - size="sm"
754 - variant="ghost"
755 - part={workflowGroup ? "primary" : "row"}
756 - disabled={node?.missing === true}
757 - onClick={() => openThread(threadId)}
758 - />
762 + }
763 + >
764 + {relationshipContent}
765 + </TooltipTrigger>
766 + <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
767 + </Tooltip>
768 + <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
769 + <Tooltip>
770 + <TooltipTrigger
771 + render={
772 + <ThreadDetailsControl
773 + size="sm"
774 + variant="ghost"
775 + part="secondary"
776 + aria-label={
777 + parentTitle
778 + ? `Merge back to ${parentTitle}`
779 + : "Merge back to source conversation"
780 }
781 + disabled={!canMerge || busyAction !== null}
782 + onClick={() => void merge()}
783 >
761 - {relationshipContent}
762 - </TooltipTrigger>
763 - <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
764 - </Tooltip>
765 - );
766 - if (workflowGroup && agent) {
767 - return (
768 - <ThreadLineageWorkflowRow
769 - key={threadId}
770 - group={workflowGroup}
771 - providerInstanceId={agent.providerInstanceId}
772 - provider={provider}
773 - providers={providers}
774 - driver={providerDriver}
775 - onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}
776 - isThreadAvailable={(memberThreadId) =>
777 - graph.nodes.get(memberThreadId as ThreadId)?.missing === false
778 - }
779 - onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}
780 - stopping={stoppingId === agent.id}
781 - stopDisabled={stoppingId !== null}
782 - header={relationshipLink}
784 + {busyAction === "merge" ? (
785 + <Spinner size="xs" />
786 + ) : (
787 + <PullRequestGlyph.merged className="size-3" />
788 + )}
789 + </ThreadDetailsControl>
790 + }
791 + />
792 + <TooltipPopup side="left">
793 + {latestMergeBackRun === null
794 + ? "Complete a run in this fork before merging it back"
795 + : parentTitle
796 + ? `Merge this conversation back into ${parentTitle}`
797 + : "Merge this conversation back into its source"}
798 + </TooltipPopup>
799 + </Tooltip>
800 + <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
801 + {threadRelationshipStatusLabel(rowStatus)}
802 + </span>
803 + </div>
804 + ) : (
805 + relationshipLink
806 + )}
807 + {canStop && agent ? (
808 + <div className="pointer-events-none absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
809 + <Tooltip>
810 + <TooltipTrigger
811 + render={
812 + <ThreadDetailsControl
813 + size="icon-xs"
814 + variant="ghost"
815 + part="icon"
816 + tone="destructive"
817 + aria-label={`Stop subagent ${threadTitle}`}
818 + disabled={stoppingId !== null}
819 + onClick={() => void stopSubagent(threadId, agent)}
820 />
784 - );
785 - }
786 - return (
787 - <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
788 - {isMergeTarget ? (
789 - <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
790 - <Tooltip>
791 - <TooltipTrigger
792 - delay={200}
793 - render={
794 - <ThreadDetailsControl
795 - size="sm"
796 - variant="ghost"
797 - part="primary"
798 - aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}
799 - disabled={node?.missing === true}
800 - onClick={() => openThread(threadId)}
801 - />
802 - }
803 - >
804 - {relationshipContent}
805 - </TooltipTrigger>
806 - <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
807 - </Tooltip>
808 - <span
809 - aria-hidden="true"
810 - className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
811 - />
812 - <Tooltip>
813 - <TooltipTrigger
814 - render={
815 - <ThreadDetailsControl
816 - size="sm"
817 - variant="ghost"
818 - part="secondary"
819 - aria-label={
820 - parentTitle
821 - ? `Merge back to ${parentTitle}`
822 - : "Merge back to source conversation"
823 - }
824 - disabled={!canMerge || busyAction !== null}
825 - onClick={() => void merge()}
826 - >
827 - {busyAction === "merge" ? (
828 - <Spinner size="xs" />
829 - ) : (
830 - <PullRequestGlyph.merged className="size-3" />
831 - )}
832 - </ThreadDetailsControl>
833 - }
834 - />
835 - <TooltipPopup side="left">
836 - {latestMergeBackRun === null
837 - ? "Complete a run in this fork before merging it back"
838 - : parentTitle
839 - ? `Merge this conversation back into ${parentTitle}`
840 - : "Merge this conversation back into its source"}
841 - </TooltipPopup>
842 - </Tooltip>
843 - <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
844 - {threadRelationshipStatusLabel(rowStatus)}
845 - </span>
846 - </div>
847 - ) : (
848 - relationshipLink
849 - )}
850 - {canStop && agent ? (
851 - <div className="pointer-events-none absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
852 - <Tooltip>
853 - <TooltipTrigger
854 - render={
855 - <ThreadDetailsControl
856 - size="icon-xs"
857 - variant="ghost"
858 - part="icon"
859 - tone="destructive"
860 - aria-label={`Stop subagent ${threadTitle}`}
861 - disabled={stoppingId !== null}
862 - onClick={() => void stopSubagent(threadId, agent)}
863 - />
864 - }
865 - >
866 - {stoppingId === threadId ? (
867 - <Spinner aria-hidden size="xs" />
868 - ) : (
869 - <SquareIcon aria-hidden className="size-3 fill-current" />
870 - )}
871 - </TooltipTrigger>
872 - <TooltipPopup side="left">Stop subagent</TooltipPopup>
873 - </Tooltip>
874 - </div>
875 - ) : null}
876 - </li>
877 - );
878 - })
821 + }
822 + >
823 + {stoppingId === threadId ? (
824 + <Spinner aria-hidden size="xs" />
825 + ) : (
826 + <SquareIcon aria-hidden className="size-3 fill-current" />
827 + )}
828 + </TooltipTrigger>
829 + <TooltipPopup side="left">Stop subagent</TooltipPopup>
830 + </Tooltip>
831 + </div>
832 + ) : null}
833 + </li>
834 + );
835 + };
836 +
837 + return (
838 + <>
839 + {lineageVisible ? (
840 + <ThreadDetailsSection
841 + headingId="thread-details-lineage-heading"
842 + title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
843 + // A lone "Previous agents" row names itself; the heading returns for status or actions.
844 + showHeading={
845 + runningCount > 0 ||
846 + canDetach ||
847 + related.length > 0 ||
848 + active.length > 0 ||
849 + delegatedFrom !== undefined
850 }
880 - </ThreadLineageGroup>
881 - ))}
882 - {remoteSubagents.length > 0 ? (
883 - <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
884 - {remoteSubagents.map((agent) => (
885 - <RemoteSubagentRow
886 - key={agent.id}
887 - agent={agent}
888 - // Its provider instance belongs to the environment it runs in.
889 - provider={providersByEnvironment
890 - .get(agent.remoteChild.environmentId)
891 - ?.find((entry) => entry.instanceId === agent.providerInstanceId)}
892 - />
851 + data-thread-relationships-panel
852 + actions={
853 + canDetach ? (
854 + <Menu>
855 + <MenuTrigger
856 + render={
857 + <ThreadDetailsControl
858 + size="icon-xs"
859 + variant="ghost"
860 + part="icon"
861 + aria-label="More thread actions"
862 + disabled={busyAction !== null}
863 + />
864 + }
865 + >
866 + <MoreHorizontalIcon className="size-3.5" />
867 + </MenuTrigger>
868 + <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
869 + <MenuItem onClick={() => void detach()}>
870 + <UnplugIcon className="size-3.5" />
871 + Disconnect agent session
872 + </MenuItem>
873 + </MenuPopup>
874 + </Menu>
875 + ) : null
876 + }
877 + >
878 + {delegatedFrom === undefined ? null : (
879 + <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
880 + <DelegatedFromRow
881 + delegatedFrom={delegatedFrom}
882 + fallbackLabel={currentThread?.linkOrigin?.label}
883 + />
884 + </ThreadLineageRowList>
885 + )}
886 + {groups.map((group) => (
887 + <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
888 + {(visibleRows) => visibleRows.map(renderRelationshipRow)}
889 + </ThreadLineageGroup>
890 ))}
894 - </ThreadLineageRowList>
891 + {remoteSubagents.length > 0 ? (
892 + <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
893 + {remoteSubagents.map((agent) => (
894 + <RemoteSubagentRow
895 + key={agent.id}
896 + agent={agent}
897 + // Its provider instance belongs to the environment it runs in.
898 + provider={providersByEnvironment
899 + .get(agent.remoteChild.environmentId)
900 + ?.find((entry) => entry.instanceId === agent.providerInstanceId)}
901 + />
902 + ))}
903 + </ThreadLineageRowList>
904 + ) : null}
905 + </ThreadDetailsSection>
906 ) : null}
896 - </ThreadDetailsSection>
907 + {sideChatsVisible ? (
908 + <ThreadDetailsSection
909 + headingId="thread-details-side-chats-heading"
910 + title={runningSideChats > 0 ? `Side chats · ${runningSideChats} running` : "Side chats"}
911 + data-thread-side-chats-panel
912 + >
913 + <ThreadLineageGroup
914 + key={`${scopedThreadKey(ref)}:side-chats`}
915 + label={null}
916 + rows={sideChats}
917 + expanded
918 + >
919 + {(visibleRows) => visibleRows.map(renderRelationshipRow)}
920 + </ThreadLineageGroup>
921 + </ThreadDetailsSection>
922 + ) : null}
923 + </>
924 );
925 }
apps/web/src/components/chat/backgroundThread.ts
+4 -1
@@ -1,4 +1,7 @@
1 import { createContext } from "react";
2
3 -/** True for a thread kept mounted under Settings or Usage; its global shortcuts stand down. */
3 +/**
4 + * True for a thread kept mounted under Settings or Usage, or shown as a side chat in its
5 + * parent's panel; its global shortcuts and listeners stand down.
6 + */
7 export const BackgroundThreadContext = createContext(false);
apps/web/src/components/chat/composerSlashCommandSearch.ts
+6 -2
@@ -12,7 +12,7 @@ type SlashSearchItem = Extract<
12 { type: "slash-command" | "provider-slash-command" | "skill" }
13 >;
14
15 -/** Providers expand slash commands only at the message start. */
15 +/** Provider commands, `/side` and `/btw` work only at the message start. */
16 export function slashCommandItemsForPromptPosition(
17 items: ReadonlyArray<SlashSearchItem>,
18 isAtPromptStart: boolean,
@@ -20,7 +20,11 @@ export function slashCommandItemsForPromptPosition(
20 if (isAtPromptStart) {
21 return [...items];
22 }
23 - return items.filter((item) => item.type !== "provider-slash-command");
23 + return items.filter(
24 + (item) =>
25 + item.type === "skill" ||
26 + (item.type === "slash-command" && item.command !== "side" && item.command !== "btw"),
27 + );
28 }
29
30 function scoreSlashCommandItem(item: SlashSearchItem, query: string): number | null {
apps/web/src/components/chat/threadDetailsItems.ts
+1
@@ -11,6 +11,7 @@ export const THREAD_DETAILS_ITEMS = [
11 { id: "servers", label: "Servers", defaultVisible: true },
12 { id: "automations", label: "Automations", defaultVisible: true },
13 { id: "lineage", label: "Lineage", defaultVisible: true },
14 + { id: "sideChats", label: "Side chats", defaultVisible: true },
15 { id: "usage", label: "Usage limits", defaultVisible: false },
16 { id: "context", label: "Context window", defaultVisible: false },
17 ] as const;
apps/web/src/components/chat/timelineViewport.ts
+4 -2
@@ -1,3 +1,4 @@
1 +import { isInSideChatPane } from "../../lib/sideChatPane";
2 import { registerCommands } from "../../shortcuts/dispatcher";
3 import {
4 eventPathContainsSelector,
@@ -86,6 +87,7 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewpor
87 emit({ source: "pointer", onScrollbar: event.target === scrollNode });
88 // Clicking message text can leave DOM focus on body, and keyboard scrolling
89 // bypasses wheel and pointer events, so scroll keys are heard app-wide.
90 + // Body keys belong to the main timeline; a side chat's hears only its own.
91 const handleKeyDown = (event: KeyboardEvent, consumed: boolean) => {
92 const direction = UP_KEYS.has(event.key) ? "up" : DOWN_KEYS.has(event.key) ? "down" : null;
93 if (
@@ -93,8 +95,8 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewpor
95 consumed ||
96 !(event.target instanceof Node) ||
97 (!scrollNode.contains(event.target) &&
96 - event.target !== document.body &&
97 - event.target !== document.documentElement) ||
98 + ((event.target !== document.body && event.target !== document.documentElement) ||
99 + isInSideChatPane(scrollNode))) ||
100 event.isComposing ||
101 event.altKey ||
102 event.ctrlKey ||
apps/web/src/components/chat/useChatShortcuts.browser.test.tsx
+56 -1
@@ -1,4 +1,5 @@
1 -import { useEffect } from "react";
1 +import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2 +import { useEffect, useState } from "react";
3 import { expect, it } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
@@ -132,3 +133,57 @@ it.each([
133 expect(composerKeys).toEqual(composer);
134 expect(received).toEqual(launcher);
135 });
136 +
137 +const ctrlShift = (key: string, command: KeybindingCommand) => ({
138 + command,
139 + shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false },
140 +});
141 +const sideChatKeybindings: ResolvedKeybindingsConfig = [
142 + ctrlShift("m", "modelPicker.toggle"),
143 + ctrlShift("x", "thread.stop"),
144 +];
145 +
146 +// A side chat in the main chat's panel: no window listeners, only its composer's own chords.
147 +function SideChat(props: { toggles: string[]; stops: string[] }) {
148 + const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);
149 + useChatShortcuts({
150 + enabled: false,
151 + embedded: true,
152 + composerElement,
153 + keybindings: sideChatKeybindings,
154 + scriptKeybindings: [],
155 + getShortcutContext: () => shortcutContext,
156 + threadFindActive: false,
157 + composerRef: {
158 + current: {
159 + toggleModelPicker: () => props.toggles.push("model"),
160 + } as Partial<ChatComposerHandle> as ChatComposerHandle,
161 + },
162 + branchToolbarRef: { current: null },
163 + closeThreadFind: () => {},
164 + commands: { "thread.stop": () => void props.stops.push("stop") },
165 + fallback: () => undefined,
166 + });
167 + return (
168 + <>
169 + <div ref={setComposerElement}>
170 + <textarea aria-label="Side chat composer" />
171 + </div>
172 + <textarea aria-label="Main composer" />
173 + </>
174 + );
175 +}
176 +
177 +it("runs a side chat's composer chords only from its composer, and never thread commands", async () => {
178 + const toggles: string[] = [];
179 + const stops: string[] = [];
180 + await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);
181 +
182 + await userEvent.click(screen.getByLabelText("Side chat composer"));
183 + await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");
184 + await userEvent.click(screen.getByLabelText("Main composer"));
185 + await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
186 +
187 + expect(toggles).toEqual(["model"]);
188 + expect(stops).toEqual([]);
189 +});
apps/web/src/components/chat/useChatShortcuts.ts
+32 -4
@@ -7,6 +7,7 @@ import {
7 preventRepeatedTerminalCloseShortcut,
8 preventTerminalCloseShortcut,
9 } from "../../lib/terminalCloseShortcut";
10 +import { isInSideChatPane } from "../../lib/sideChatPane";
11 import { getTerminalFocusOwner, type TerminalFocusOwner } from "../../lib/terminalFocus";
12 import type { ComposerHandleRef } from "../../composerHandleContext";
13 import type { BranchToolbarHandle } from "../BranchToolbar";
@@ -23,6 +24,12 @@ export type ChatShortcutCommands = Partial<Record<KeybindingCommand, ChatShortcu
24
25 interface ChatShortcutsInput {
26 readonly enabled: boolean;
27 + /**
28 + * A side chat inside another chat leaves the window to the outer chat. It runs only
29 + * composer chords, for keys pressed inside `composerElement`.
30 + */
31 + readonly embedded?: boolean;
32 + readonly composerElement?: HTMLElement | null;
33 readonly keybindings: ResolvedKeybindingsConfig;
34 readonly scriptKeybindings: ResolvedKeybindingsConfig;
35 readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {
@@ -44,6 +51,8 @@ interface ChatShortcutsInput {
51 * act on the current render without re-registering on every change.
52 */
53 export function useChatShortcuts(input: ChatShortcutsInput) {
54 + const embedded = input.embedded === true;
55 + const composerElement = embedded ? (input.composerElement ?? null) : null;
56 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
57 const { keybindings } = input;
58 if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
@@ -55,7 +64,7 @@ export function useChatShortcuts(input: ChatShortcutsInput) {
64 event.stopPropagation();
65 return;
66 }
58 - if (!input.enabled || isCommandPaletteOpen()) return;
67 + if (!input.enabled || isCommandPaletteOpen() || isInSideChatPane(event.target)) return;
68 const terminalFocusOwner = getTerminalFocusOwner();
69 if (event.defaultPrevented && terminalFocusOwner === null) return;
70 const shortcutContext = input.getShortcutContext(event.target);
@@ -90,7 +99,8 @@ export function useChatShortcuts(input: ChatShortcutsInput) {
99 event.defaultPrevented ||
100 event.isComposing ||
101 event.keyCode === 229 ||
93 - isCommandPaletteOpen()
102 + isCommandPaletteOpen() ||
103 + isInSideChatPane(event.target)
104 )
105 return;
106 const context = input.getShortcutContext(event.target);
@@ -98,8 +108,26 @@ export function useChatShortcuts(input: ChatShortcutsInput) {
108 event.preventDefault();
109 input.closeThreadFind();
110 });
101 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window keydown listeners for chat shortcuts and find dismissal for the component's lifetime
111 + const handleComposerShortcut = useEffectEvent((event: KeyboardEvent) => {
112 + if (event.defaultPrevented || isCommandPaletteOpen()) return;
113 + const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {
114 + context: input.getShortcutContext(event.target),
115 + });
116 + const run = command
117 + ? composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command]
118 + : undefined;
119 + if (!run || run({ event, terminalFocusOwner: null }) === false) return;
120 + event.preventDefault();
121 + event.stopPropagation();
122 + });
123 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches keydown listeners for chat shortcuts and find dismissal: on the window, or on an embedded chat's composer
124 useEffect(() => {
125 + if (embedded) {
126 + if (composerElement === null) return;
127 + const onComposerKeyDown = (event: KeyboardEvent) => handleComposerShortcut(event);
128 + composerElement.addEventListener("keydown", onComposerKeyDown, true);
129 + return () => composerElement.removeEventListener("keydown", onComposerKeyDown, true);
130 + }
131 const onKeyDownCapture = (event: KeyboardEvent) => handleShortcut(event);
132 const onKeyDown = (event: KeyboardEvent) => dismissFind(event);
133 window.addEventListener("keydown", onKeyDownCapture, true);
@@ -108,5 +136,5 @@ export function useChatShortcuts(input: ChatShortcutsInput) {
136 window.removeEventListener("keydown", onKeyDownCapture, true);
137 window.removeEventListener("keydown", onKeyDown);
138 };
111 - }, []);
139 + }, [composerElement, embedded]);
140 }
apps/web/src/components/chat/useComposerMenuItems.ts
+22
@@ -64,6 +64,8 @@ export function useComposerMenuItems({
64 pullRequestRepository,
65 threadPullRequests,
66 planModeUiEnabled,
67 + sideChatAvailable,
68 + sideChatDisabledReason,
69 compactSlashCommandAvailable,
70 selectedProvider,
71 selectedProviderSkills,
@@ -80,6 +82,8 @@ export function useComposerMenuItems({
82 readonly pullRequestRepository: string | null;
83 readonly threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined;
84 readonly planModeUiEnabled: boolean;
85 + readonly sideChatAvailable: boolean;
86 + readonly sideChatDisabledReason: string | null;
87 readonly compactSlashCommandAvailable: boolean;
88 readonly selectedProvider: ProviderDriverKind;
89 readonly selectedProviderSkills: ServerProvider["skills"];
@@ -236,6 +240,24 @@ export function useComposerMenuItems({
240 },
241 ] as const)
242 : []),
243 + ...(sideChatAvailable
244 + ? ([
245 + {
246 + id: "slash:side",
247 + type: "slash-command",
248 + command: "side",
249 + label: "/side",
250 + description: sideChatDisabledReason ?? "Ask a side question in a new side chat",
251 + },
252 + {
253 + id: "slash:btw",
254 + type: "slash-command",
255 + command: "btw",
256 + label: "/btw",
257 + description: sideChatDisabledReason ?? "Same as /side",
258 + },
259 + ] as const)
260 + : []),
261 ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
262 const slashMenuSkills = getProviderSkillsForSlashMenu(
263 selectedProviderSkills,
apps/web/src/components/chat/useComposerSend.ts
+62 -2
@@ -54,6 +54,7 @@ import {
54 import {
55 type ComposerSubmissionIntent,
56 collapseExpandedComposerCursor,
57 + parseSideChatCommand,
58 parseStandaloneComposerSlashCommand,
59 } from "../../composer-logic";
60 import { resolvePlanFollowUpSubmission } from "../../proposedPlan";
@@ -76,7 +77,10 @@ import {
77 useComposerDraftStore,
78 DraftId,
79 } from "../../composerDraftStore";
79 -import { type TerminalContextDraft } from "../../lib/terminalContext";
80 +import {
81 + filterTerminalContextsWithText,
82 + type TerminalContextDraft,
83 +} from "../../lib/terminalContext";
84 import { ensureInlineContextReferences } from "../../lib/composerContextReferences";
85 import {
86 buildMessageContext,
@@ -237,6 +241,10 @@ interface ComposerSendInput {
241 readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
242 readonly acknowledgeActiveThreadWoke: () => void;
243 readonly handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
244 + /** Resolves true once the side chat started and got the prompt. */
245 + readonly onSideChat?: ((prompt: string) => Promise<boolean>) | undefined;
246 + /** Refuses `/side` with this reason and keeps the draft. */
247 + readonly sideChatDisabledReason: string | null;
248 readonly handleNewThreadInActiveProject: () => void;
249 readonly persistThreadSettingsForNextTurn: (input: {
250 threadId: ThreadId;
@@ -322,6 +330,8 @@ export function useComposerSend(input: ComposerSendInput) {
330 anchorNewTurn,
331 acknowledgeActiveThreadWoke,
332 handleInteractionModeChange,
333 + onSideChat,
334 + sideChatDisabledReason,
335 handleNewThreadInActiveProject,
336 persistThreadSettingsForNextTurn,
337 } = input;
@@ -473,7 +483,57 @@ export function useComposerSend(input: ComposerSendInput) {
483 return;
484 }
485 const sendCtx = composerRef.current?.getSendContext();
476 - if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) {
486 + // `/side` beats an open question and a plan follow-up, which would send the text to main.
487 + const sideChatCommand =
488 + sendCtx && !directAnnotation && !queuedRunEdit.isEditing
489 + ? parseSideChatCommand(promptAtSend)
490 + : null;
491 + const answeringQuestion =
492 + Boolean(activePendingProgress) && sendCtx?.answeringPendingUserInput !== false;
493 + // Where side chats are unavailable, `/side` text can still be a literal answer.
494 + if (sideChatDisabledReason !== null && sideChatCommand && !answeringQuestion) {
495 + toastManager.add(
496 + stackedThreadToast({
497 + type: "warning",
498 + title: "Side chat not started",
499 + description: sideChatDisabledReason,
500 + }),
501 + );
502 + return;
503 + }
504 + if (onSideChat && sendCtx && sideChatCommand && sideChatDisabledReason === null) {
505 + if (
506 + sendCtx.images.length > 0 ||
507 + sendCtx.files.length > 0 ||
508 + filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 ||
509 + sendCtx.previewAnnotations.length > 0 ||
510 + sendCtx.reviewComments.length > 0 ||
511 + sendCtx.threadContexts.length > 0 ||
512 + sendCtx.environmentContexts.length > 0
513 + ) {
514 + toastManager.add(
515 + stackedThreadToast({
516 + type: "warning",
517 + title: "Side chats take text only",
518 + description: "Remove the attachments and context, then send it again.",
519 + }),
520 + );
521 + return;
522 + }
523 + const started = await onSideChat(sideChatCommand.prompt);
524 + // Clear only what was sent; the user may have edited the draft or left meanwhile.
525 + if (
526 + started &&
527 + currentRouteThreadKeyRef.current === routeThreadKey &&
528 + promptRef.current === promptAtSend
529 + ) {
530 + promptRef.current = "";
531 + setComposerDraftPrompt(composerDraftTarget, "");
532 + composerRef.current?.resetCursorState();
533 + }
534 + return;
535 + }
536 + if (answeringQuestion) {
537 if (directAnnotation) {
538 notifyDirectAnnotationAttached();
539 return;
apps/web/src/components/chat/useComposerStash.ts
+6 -1
@@ -61,6 +61,7 @@ import {
61 useState,
62 } from "react";
63 import { BackgroundThreadContext } from "./backgroundThread";
64 +import { isInSideChatPane } from "../../lib/sideChatPane";
65 import { useStableCallback } from "../../hooks/useStableCallback";
66
67 /**
@@ -699,7 +700,11 @@ export function useComposerStash(input: {
700 if (backgroundThread) return;
701 return registerCommands(
702 { "composer.stash": handleStashShortcut },
702 - { capture: true, context: readShortcutContext },
703 + {
704 + capture: true,
705 + context: readShortcutContext,
706 + when: (event) => !isInSideChatPane(event.target),
707 + },
708 );
709 }, [backgroundThread, handleStashShortcut, readShortcutContext]);
710
apps/web/src/components/chat/usePasteToFocusComposer.ts
+3 -1
@@ -5,6 +5,7 @@ import { useEffect, useRef } from "react";
5 import { isMacPlatform } from "../../lib/utils";
6 import { isCommandPaletteOpen } from "../../commandPaletteBus";
7 import { getTerminalFocusOwner } from "../../lib/terminalFocus";
8 +import { isInSideChatPane } from "../../lib/sideChatPane";
9 import type { ThreadId } from "@t3tools/contracts";
10 import type { ComposerHandleRef } from "../../composerHandleContext";
11 /**
@@ -18,6 +19,7 @@ export function usePasteToFocusComposer(
19 const pasteAsTextShortcutUntilRef = useRef(0);
20 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window keydown and paste capture listeners that route stray pastes into the composer
21 useEffect(() => {
22 + if (!activeThreadId) return;
23 const keyHandler = (event: KeyboardEvent) => {
24 if (
25 shouldRedirectInputToComposer(event) &&
@@ -27,7 +29,7 @@ export function usePasteToFocusComposer(
29 }
30 };
31 const handler = (event: ClipboardEvent) => {
30 - if (!activeThreadId || isCommandPaletteOpen()) return;
32 + if (isCommandPaletteOpen() || isInSideChatPane(event.target)) return;
33 if (getTerminalFocusOwner() !== null) return;
34 if (composerRef.current?.isModelPickerOpen()) return;
35 const text = pasteTextToFocusComposer(event);
apps/web/src/components/chat/useRightPanelActions.ts
+9 -4
@@ -45,6 +45,8 @@ interface RightPanelActionsInput {
45 readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;
46 readonly threadPanelPresentation: ThreadPanelPresentation;
47 readonly isServerThread: boolean;
48 + /** A side chat pane; the main view already answers preview bus actions. */
49 + readonly embedded: boolean;
50 readonly isGitRepo: boolean;
51 readonly browserAvailable: boolean;
52 readonly canOperatePreview: boolean;
@@ -78,6 +80,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
80 pullRequestPanelTarget,
81 threadPanelPresentation,
82 isServerThread,
83 + embedded,
84 isGitRepo,
85 browserAvailable,
86 canOperatePreview,
@@ -316,10 +319,12 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
319 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel
320 useEffect(
321 () =>
319 - subscribePreviewAction((action) => {
320 - if (action === "toggle-panel") togglePreviewPanelStable();
321 - }),
322 - [togglePreviewPanelStable],
322 + embedded
323 + ? undefined
324 + : subscribePreviewAction((action) => {
325 + if (action === "toggle-panel") togglePreviewPanelStable();
326 + }),
327 + [embedded, togglePreviewPanelStable],
328 );
329
330 const shortcuts = {
apps/web/src/components/chat/useSideChat.ts new
+96
@@ -0,0 +1,96 @@
1 +import type { ScopedThreadRef } from "@t3tools/contracts";
2 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3 +import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
4 +import {
5 + type AtomCommandResult,
6 + isAtomCommandInterrupted,
7 + squashAtomCommandFailure,
8 +} from "@t3tools/client-runtime/state/runtime";
9 +import { useRef } from "react";
10 +
11 +import { newMessageId, newThreadId } from "~/lib/utils";
12 +import { useStableCallback } from "../../hooks/useStableCallback";
13 +import { useRightPanelStore } from "../../rightPanelStore";
14 +import { waitForThreadShell } from "../../state/entities";
15 +import { threadEnvironment } from "../../state/threads";
16 +import { useAtomCommand } from "../../state/use-atom-command";
17 +import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18 +
19 +/**
20 + * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the
21 + * thread's latest stable point, sends `prompt` there, and shows the side chat's tab. It
22 + * resolves false when the side chat did not start, or another one is still starting.
23 + */
24 +export function useSideChat(input: {
25 + readonly threadRef: ScopedThreadRef | null;
26 + readonly onError: (message: string) => void;
27 +}) {
28 + const pendingRef = useRef(false);
29 + const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
30 + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
31 + const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
32 + reportFailure: false,
33 + });
34 + const reportFailure = (
35 + failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
36 + fallback: string,
37 + ) => {
38 + if (isAtomCommandInterrupted(failure)) return;
39 + const error = squashAtomCommandFailure(failure);
40 + input.onError(error instanceof Error ? error.message : fallback);
41 + };
42 + const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {
43 + const targetThreadId = newThreadId();
44 + const fork = await forkSideChat({
45 + environmentId: threadRef.environmentId,
46 + input: { sourceThreadId: threadRef.threadId, targetThreadId, title: "Side chat" },
47 + });
48 + if (fork._tag === "Failure") {
49 + reportFailure(fork, "Could not start a side chat.");
50 + return false;
51 + }
52 + // Drops the empty side chat a failed start leaves behind; one that got its message stays.
53 + const discard = () =>
54 + void deleteThread({
55 + environmentId: threadRef.environmentId,
56 + input: { threadId: targetThreadId, onlyIfUnused: true },
57 + });
58 + if (!(await waitForThreadShell(scopeThreadRef(threadRef.environmentId, targetThreadId)))) {
59 + input.onError("The side chat was created, but it did not reach this client.");
60 + discard();
61 + return false;
62 + }
63 + const text = prompt?.trim();
64 + // Send before showing the tab: closing a tab whose side chat has no run deletes it.
65 + if (text) {
66 + // The server asks before edits on a side chat's first turn whatever mode is sent.
67 + const turn = await startThreadTurn({
68 + environmentId: threadRef.environmentId,
69 + input: {
70 + threadId: targetThreadId,
71 + message: { messageId: newMessageId(), role: "user", text, attachments: [] },
72 + titleSeed: deriveThreadTitleSeed({ text, attachments: [] }),
73 + runtimeMode: "approval-required",
74 + interactionMode: "default",
75 + createdAt: new Date().toISOString(),
76 + },
77 + });
78 + if (turn._tag === "Failure") {
79 + reportFailure(turn, "Could not send the side chat message.");
80 + discard();
81 + return false;
82 + }
83 + }
84 + useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
85 + return true;
86 + };
87 + const open = async (prompt?: string) => {
88 + const { threadRef } = input;
89 + if (!threadRef || pendingRef.current) return false;
90 + pendingRef.current = true;
91 + return start(threadRef, prompt).finally(() => {
92 + pendingRef.current = false;
93 + });
94 + };
95 + return { available: input.threadRef !== null, open: useStableCallback(open) };
96 +}
apps/web/src/components/chat/useThreadLifecycle.tsx
+2
@@ -69,6 +69,7 @@ import { useAtomValue } from "@effect/atom-react";
69 import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";
70 import { Atom } from "effect/reactivity";
71 import { environmentThreadDetails } from "../../state/threads";
72 +import { openSideChatTab } from "../../lib/sideChatPane";
73 import type { useLocalDispatchState } from "./useLocalDispatchState";
74 const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
75 const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(
@@ -451,6 +452,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
452 toastManager.add({ type: "info", title: "This thread is no longer available" });
453 return;
454 }
455 + if (activeThreadRef && openSideChatTab(activeThreadRef, shell)) return;
456 void navigate({
457 to: "/$environmentId/$threadId",
458 params: buildThreadRouteParams(threadRef),
apps/web/src/components/preview/openPreviewSession.test.ts
+52 -2
@@ -8,9 +8,18 @@ import { AsyncResult } from "effect/reactivity";
8 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10 import * as browserDefaults from "~/browser/browserDefaults";
11 -import { BrowserSettingsReadError, openUrlInPreview } from "~/browser/openFileInPreview";
11 +import {
12 + BrowserSettingsReadError,
13 + openFileInPreview,
14 + openUrlInPreview,
15 +} from "~/browser/openFileInPreview";
16 +import * as previewRuntime from "~/browser/previewRuntime";
17 import { __setClientSettingsForTests } from "~/hooks/useSettings";
13 -import { useRightPanelStore } from "~/rightPanelStore";
18 +import {
19 + hostRightPanel,
20 + selectActiveRightPanelSurface,
21 + useRightPanelStore,
22 +} from "~/rightPanelStore";
23 import {
24 applyPreviewServerSnapshot,
25 readThreadPreviewState,
@@ -91,6 +100,47 @@ describe("openPreviewSession", () => {
100 });
101
102 describe("openUrlInPreview from a link", () => {
103 + it.each(["link", "file"] as const)(
104 + "opens a side chat's %s in the parent's browser panel after the pane unmounts",
105 + async (entryPoint) => {
106 + const sideChatRef = { ...threadRef, threadId: "side-chat" as ScopedThreadRef["threadId"] };
107 + const unhost = hostRightPanel(sideChatRef, threadRef);
108 + const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
109 + vi.spyOn(previewRuntime, "isPreviewAvailableFor").mockReturnValue(true);
110 + vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockImplementation(async () => {
111 + unhost();
112 + return browserDefaults.getBrowserDefaults();
113 + });
114 +
115 + if (entryPoint === "link") {
116 + await openUrlInPreview({ openPreview, threadRef: sideChatRef, url: "https://t3.chat/" });
117 + } else {
118 + await openFileInPreview({
119 + threadRef: sideChatRef,
120 + filePath: "/repo/index.html",
121 + workspaceRoot: "/repo",
122 + httpBaseUrl: "http://localhost:3000",
123 + createAssetUrl: async () => {
124 + unhost();
125 + return AsyncResult.success({ relativeUrl: "/assets/index.html", expiresAt: 0 });
126 + },
127 + openPreview,
128 + });
129 + }
130 +
131 + expect(openPreview).toHaveBeenCalledWith(
132 + expect.objectContaining({
133 + input: expect.objectContaining({ threadId: threadRef.threadId }),
134 + }),
135 + );
136 + expect(readThreadPreviewState(threadRef).activeTabId).toBe(snapshot.tabId);
137 + expect(readThreadPreviewState(sideChatRef).sessions).toEqual({});
138 + expect(
139 + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.kind,
140 + ).toBe("preview");
141 + },
142 + );
143 +
144 // regression: #16961 a background link open switched the active preview tab
145 it("keeps the current tab active for a background open", async () => {
146 applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });
apps/web/src/composer-logic.test.ts
+28
@@ -22,8 +22,10 @@ import {
22 extendReplacementRangeForTrailingSpace,
23 formatAssistantCitationForComposer,
24 isPathSuggestionCurrent,
25 + parseSideChatCommand,
26 replaceTextRange,
27 } from "./composer-logic";
28 +import { slashCommandItemsForPromptPosition } from "./components/chat/composerSlashCommandSearch";
29 import { carryDisplacedCustomAnswerIntoPrompt } from "./pendingUserInput";
30 import { formatTerminalContextReference } from "./lib/terminalContext";
31
@@ -548,3 +550,29 @@ describe("extendReplacementRangeForTrailingSpace", () => {
550 expect(extendReplacementRangeForTrailingSpace("@fi", 3, "@file ")).toBe(3);
551 });
552 });
553 +
554 +describe("parseSideChatCommand", () => {
555 + it("reads an optional prompt after /side or /btw", () => {
556 + expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });
557 + expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({
558 + prompt: "why does this fail?\nline two",
559 + });
560 + expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });
561 + });
562 +
563 + it("ignores other commands and inline mentions, which the menu does not offer", () => {
564 + expect(parseSideChatCommand("/sidebar")).toBeNull();
565 + expect(parseSideChatCommand("/btwx")).toBeNull();
566 + expect(parseSideChatCommand("ask /side later")).toBeNull();
567 + const items = (["side", "btw", "plan"] as const).map((command) => ({
568 + id: `slash:${command}`,
569 + type: "slash-command" as const,
570 + command,
571 + label: `/${command}`,
572 + description: "",
573 + }));
574 + expect(slashCommandItemsForPromptPosition(items, false).map((item) => item.id)).toEqual([
575 + "slash:plan",
576 + ]);
577 + });
578 +});
apps/web/src/composer-logic.ts
+8 -2
@@ -18,7 +18,7 @@ import {
18 import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";
19
20 export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
21 -export type ComposerSlashCommand = "model" | "plan" | "default";
21 +export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw";
22 export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";
23
24 export interface ComposerTrigger {
@@ -318,9 +318,15 @@ export function composerStateAtPromptEnd(
318 };
319 }
320
321 +/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
322 +export function parseSideChatCommand(text: string): { prompt: string } | null {
323 + const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
324 + return match ? { prompt: match[1]?.trim() ?? "" } : null;
325 +}
326 +
327 export function parseStandaloneComposerSlashCommand(
328 text: string,
323 -): Exclude<ComposerSlashCommand, "model"> | null {
329 +): Exclude<ComposerSlashCommand, "model" | "side" | "btw"> | null {
330 const match = /^\/(plan|default)\s*$/i.exec(text.trim());
331 if (!match) {
332 return null;
apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
+3
@@ -31,6 +31,7 @@ vi.mock("../state/session", () => ({
31 vi.mock("../state/entities", () => ({
32 useQuietThreadShell: () => null,
33 useProject: () => null,
34 + readThreadShell: () => null,
35 }));
36 vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));
37 vi.mock("../composerDraftStore", async () => {
@@ -56,6 +57,8 @@ vi.mock("../state/use-atom-command", () => ({
57 // The commands are replaced above; importing their runtime would connect a client.
58 vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}, write: {} } }));
59 vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));
60 +vi.mock("../state/threads", () => ({ threadEnvironment: { delete: {} } }));
61 +vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: () => null } }));
62 vi.mock("@t3tools/client-runtime/state/runtime", () => ({
63 isAtomCommandInterrupted: () => false,
64 }));
apps/web/src/hooks/useRightPanelSurfaceClose.ts
+26 -1
@@ -1,8 +1,10 @@
1 import {
2 + AuthOrchestrationOperateScope,
3 AuthPreviewOperateScope,
4 AuthTerminalOperateScope,
5 type ScopedThreadRef,
6 } from "@t3tools/contracts";
7 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
8 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
9 import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";
10 import { closePreviewSession } from "../components/preview/closePreviewSession";
@@ -17,19 +19,27 @@ import {
19 useRightPanelStore,
20 type RightPanelSurface,
21 } from "../rightPanelStore";
22 +import { appAtomRegistry } from "../rpc/atomRegistry";
23 +import { readThreadShell } from "../state/entities";
24 import { previewEnvironment } from "../state/preview";
25 import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
26 +import { environmentShell } from "../state/shell";
27 +import { threadEnvironment } from "../state/threads";
28 import { useAtomCommand } from "../state/use-atom-command";
29 import { useTerminalUiStateStore } from "../terminalUiStateStore";
30 import { useStableCallback } from "./useStableCallback";
31
26 -/** Closing releases preview and terminal sessions. Agent-driven browsers and terminal tabs require confirmation. */
32 +/**
33 + * Closing releases preview and terminal sessions, and deletes a side chat that never ran.
34 + * Agent-driven browsers and terminal tabs require confirmation.
35 + */
36 export function useRightPanelSurfaceClose(input: {
37 readonly threadRef: ScopedThreadRef | null;
38 readonly terminalLabelsById: ReadonlyMap<string, string>;
39 }) {
40 const { threadRef, terminalLabelsById } = input;
41 const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
42 + const deleteThread = useAtomCommand(threadEnvironment.delete, "side chat delete");
43 const canOperatePreview = useEnvironmentScope(
44 threadRef?.environmentId ?? null,
45 AuthPreviewOperateScope,
@@ -60,6 +70,21 @@ export function useRightPanelSurfaceClose(input: {
70 terminalActions.closeTerminalSession(terminalId, ref);
71 }
72 }
73 + if (
74 + surface.kind === "side-chat" &&
75 + readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope) &&
76 + // A live shell without the side chat means it is already deleted.
77 + !(
78 + appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live" &&
79 + readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId)) === null
80 + )
81 + ) {
82 + // The server keeps a side chat with a run or message. Reopen skips one it deleted.
83 + void deleteThread({
84 + environmentId: ref.environmentId,
85 + input: { threadId: surface.threadId, onlyIfUnused: true },
86 + });
87 + }
88 };
89 const closeAfterAgentBrowserConfirmation = (
90 toClose: readonly RightPanelSurface[],
apps/web/src/lib/desktopPasteAsText.ts
+7 -2
@@ -2,14 +2,19 @@ import type { DesktopBridge } from "@t3tools/contracts";
2
3 export const DESKTOP_PASTE_AS_TEXT_EVENT = "t3:paste-as-text";
4
5 -/** Arm composer paste handling before Electron delivers the native clipboard event. */
5 +/**
6 + * Arm composer paste handling before Electron delivers the native clipboard event. The event
7 + * bubbles from the focused element, so a composer can listen on its own form or on `target`.
8 + */
9 export function installDesktopPasteAsText(
10 bridge: Pick<DesktopBridge, "onMenuAction" | "pasteAsText"> | undefined,
11 target: EventTarget,
12 ): (() => void) | undefined {
13 return bridge?.onMenuAction((action) => {
14 if (action !== "paste-as-text") return;
12 - target.dispatchEvent(new Event(DESKTOP_PASTE_AS_TEXT_EVENT));
15 + (document.activeElement ?? target).dispatchEvent(
16 + new Event(DESKTOP_PASTE_AS_TEXT_EVENT, { bubbles: true }),
17 + );
18 void bridge.pasteAsText();
19 });
20 }
apps/web/src/lib/sideChatPane.ts new
+31
@@ -0,0 +1,31 @@
1 +import type { OrchestrationV2ThreadShell, ScopedThreadRef } from "@t3tools/contracts";
2 +
3 +import type { ToolCallDiffTarget } from "../diffPanelStore";
4 +import { useRightPanelStore } from "../rightPanelStore";
5 +
6 +/** Whether an event started in the side chat pane (`data-side-chat-pane`), which the main chat ignores. */
7 +export function isInSideChatPane(target: EventTarget | null): boolean {
8 + return target instanceof Element && target.closest("[data-side-chat-pane]") !== null;
9 +}
10 +
11 +/**
12 + * Opens an embedded side chat's tool diffs in its parent's diff panel and runs its shell commands
13 + * in the parent's terminal drawer, since the embedded view hides its own. Other panel actions reach
14 + * the parent through `hostRightPanel`; diff selection and the drawer are not panel state.
15 + */
16 +export interface SideChatParentPanel {
17 + readonly openToolDiff: (target: ToolCallDiffTarget) => void;
18 + readonly runShellCommand: (command: string) => void;
19 +}
20 +
21 +/** Opens `thread` in its tab when it is a side chat of `parentRef`; false for any other thread. */
22 +export function openSideChatTab(
23 + parentRef: ScopedThreadRef,
24 + thread: Pick<OrchestrationV2ThreadShell, "id" | "lineage"> | null,
25 +): boolean {
26 + if (thread?.lineage.sideChat !== true || thread.lineage.parentThreadId !== parentRef.threadId) {
27 + return false;
28 + }
29 + useRightPanelStore.getState().openSideChat(parentRef, thread.id);
30 + return true;
31 +}
apps/web/src/reopenClosedView.test.ts
+13
@@ -134,6 +134,7 @@ describe("planNextReopen", () => {
134 environmentKnown: true,
135 catalogReady: true,
136 ownerExists: true,
137 + sideChatExists: true,
138 shellLive: true,
139 panel: { isOpen: false, activeSurfaceId: null, surfaces: [] },
140 };
@@ -163,6 +164,18 @@ describe("planNextReopen", () => {
164 [],
165 "b",
166 ],
167 + [
168 + "skips but keeps a side chat deleted from a live shell",
169 + [{ ...known, sideChatExists: false }, known],
170 + [],
171 + "b",
172 + ],
173 + [
174 + "waits when a cached shell lacks the side chat",
175 + [{ ...known, sideChatExists: false, shellLive: false }, known],
176 + [],
177 + null,
178 + ],
179 [
180 "waits when a cached shell lacks the thread",
181 [{ ...known, ownerExists: false, shellLive: false }, known],
apps/web/src/reopenClosedView.ts
+6 -1
@@ -14,6 +14,8 @@ export interface ReopenOwnerState {
14 environmentKnown: boolean;
15 catalogReady: boolean;
16 ownerExists: boolean;
17 + /** False only for a side chat tab whose thread is gone from the shell. */
18 + sideChatExists: boolean;
19 shellLive: boolean;
20 panel: ThreadRightPanelState;
21 }
@@ -30,7 +32,7 @@ export function planNextReopen(
32 drop.push(entry);
33 continue;
34 }
33 - if (!owner.ownerExists) {
35 + if (!owner.ownerExists || !owner.sideChatExists) {
36 if (owner.shellLive) continue;
37 break;
38 }
@@ -134,6 +136,9 @@ export async function reopenClosedView(
136 case "pull-request":
137 panels.openPullRequest(ref, surface);
138 break;
139 + case "side-chat":
140 + panels.openSideChat(ref, surface.threadId);
141 + break;
142 default:
143 panels.open(ref, surface.kind);
144 }
apps/web/src/rightPanelStore.test.ts
+18
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
5 import { useClosedViewStore } from "./closedViewStore";
6 import { reopenClosedView } from "./reopenClosedView";
7 import {
8 + hostRightPanel,
9 migratePersistedRightPanelState,
10 pullRequestSurface,
11 pullRequestSurfaceId,
@@ -39,6 +40,23 @@ async function reloadRightPanelStore() {
40 }
41
42 describe("rightPanelStore", () => {
43 + it("opens a hosted side chat's panel actions in its parent's panel until unhosted", () => {
44 + const store = useRightPanelStore.getState();
45 + const unhost = hostRightPanel(refB, refA);
46 + store.openFile(refB, "src/app.ts");
47 + expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id).toBe(
48 + "file:src/app.ts",
49 + );
50 + expect(
51 + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB).surfaces,
52 + ).toEqual([]);
53 + unhost();
54 + store.openFile(refB, "src/app.ts");
55 + expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refB)?.id).toBe(
56 + "file:src/app.ts",
57 + );
58 + });
59 +
60 it("records single and bulk tab closes, newest first", () => {
61 const store = useRightPanelStore.getState();
62 const pr = pullRequestSurface({
apps/web/src/rightPanelStore.ts
+42 -5
@@ -21,6 +21,7 @@ const RIGHT_PANEL_KINDS = [
21 "terminal",
22 "pull-request",
23 "pull-requests",
24 + "side-chat",
25 ] as const;
26 export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
27
@@ -74,7 +75,8 @@ export type RightPanelSurface =
75 url?: string;
76 detailTab?: PullRequestDetailTab;
77 }
77 - | { id: "pull-requests"; kind: "pull-requests" };
78 + | { id: "pull-requests"; kind: "pull-requests" }
79 + | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId };
80
81 const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
82 const RIGHT_PANEL_STORAGE_VERSION = 14;
@@ -121,8 +123,9 @@ interface RightPanelStoreState {
123 ) => boolean;
124 open: (
125 ref: ScopedThreadRef,
124 - kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
126 + kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "side-chat">,
127 ) => void;
128 + openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void;
129 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
130 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
131 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
@@ -180,7 +183,7 @@ interface RightPanelStoreState {
183 toggleVisibility: (ref: ScopedThreadRef) => void;
184 toggle: (
185 ref: ScopedThreadRef,
183 - kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
186 + kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "side-chat">,
187 ) => void;
188 setThreadPanelOpen: (
189 ref: ScopedThreadRef,
@@ -203,7 +206,7 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
206 };
207
208 const singletonSurface = (
206 - kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
209 + kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request" | "side-chat">,
210 ): RightPanelSurface => {
211 switch (kind) {
212 case "diff":
@@ -382,11 +385,39 @@ const automaticUpdate = (
385 ...updateThread(state, threadKey, updater),
386 });
387
388 +// A side chat pane has no panel of its own, so its panel actions open in its parent's panel.
389 +const panelHosts = new Map<string, ScopedThreadRef>();
390 +
391 +/** Routes `guest`'s panel actions to `host`'s panel until the returned cleanup runs. */
392 +export function hostRightPanel(guest: ScopedThreadRef, host: ScopedThreadRef): () => void {
393 + const guestKey = scopedThreadKey(guest);
394 + panelHosts.set(guestKey, host);
395 + return () => {
396 + if (panelHosts.get(guestKey) === host) panelHosts.delete(guestKey);
397 + };
398 +}
399 +
400 +/** The thread whose panel shows `ref`'s panel actions, so it also owns their browser tabs. */
401 +export function rightPanelHostRef(ref: ScopedThreadRef): ScopedThreadRef {
402 + return panelHosts.get(scopedThreadKey(ref)) ?? ref;
403 +}
404 +
405 const userAction = (
406 state: RightPanelStoreState,
387 - threadKey: string,
407 + guestKey: string,
408 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
409 closesView = false,
410 +): Partial<RightPanelStoreState> => {
411 + const host = panelHosts.get(guestKey);
412 + const threadKey = host === undefined ? guestKey : scopedThreadKey(host);
413 + return userActionOnThread(state, threadKey, updater, closesView);
414 +};
415 +
416 +const userActionOnThread = (
417 + state: RightPanelStoreState,
418 + threadKey: string,
419 + updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
420 + closesView: boolean,
421 ): Partial<RightPanelStoreState> => ({
422 ...updateThread(state, threadKey, (current) => {
423 const next = updater(current);
@@ -682,6 +713,12 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
713 );
714 }),
715 ),
716 + openSideChat: (ref, threadId) =>
717 + set((state) =>
718 + userAction(state, scopedThreadKey(ref), (current) =>
719 + upsertSurface(current, { id: `side-chat:${threadId}`, kind: "side-chat", threadId }),
720 + ),
721 + ),
722 renameDevice: (ref, surfaceId, title) =>
723 set((state) =>
724 userAction(state, scopedThreadKey(ref), (current) => ({
docs/orchestration-v2/thread-lineage-and-context-transfer.md
+2
@@ -240,6 +240,8 @@ type AppThreadLineage = {
240 parentThreadId: ThreadId | null;
241 relationshipToParent: "fork" | "subagent" | null;
242 rootThreadId: ThreadId;
243 + // A side chat: a fork shown only inside its parent. The fork planner sets it from `thread.fork`.
244 + sideChat?: boolean;
245 };
246 ```
247
docs/user/thread-sidebar.md
+24
@@ -283,6 +283,30 @@ To choose what the thread details card shows, right-click the card or open
283 shortcuts, such as Open in editor and project scripts. **Reset to default** brings
284 back the standard rows.
285
286 +## Side chats
287 +
288 +A side chat lets you ask a question about a thread without adding to it. It starts
289 +with what the thread knows, and the thread keeps working while you ask.
290 +
291 +On web and desktop, start a message with `/side` or `/btw`, then your question.
292 +You can also choose **Side chat** from the **+** menu in the right panel. The side
293 +chat opens as a tab there, with its own composer. Side chats do not show in the
294 +sidebar. Find one again under **Side chats** in thread details.
295 +
296 +A side chat works in the same folder as the thread. Its first reply asks before it
297 +edits files or runs commands. After that, it uses the permission mode you choose
298 +in its composer.
299 +
300 +To use what you learned, choose **Bring back**. The thread gets the side chat with
301 +your next message there. Bring back is available while the thread is idle.
302 +
303 +Closing a side chat you never sent a message in deletes it. To delete one you used,
304 +choose **Delete** at the top of the side chat. Deleting a thread also deletes its
305 +side chats.
306 +
307 +On mobile, a thread lists its side chats above the composer. Tap one to open it and
308 +answer its questions.
309 +
310 ## Snooze until later
311
312 To change the choices in the snooze menu, open **Settings → Threads → Snooze options**.
evals/mcp-tool-use/cases/side-chats.ndjson new
+2
@@ -0,0 +1,2 @@
1 +{"id": "side-chat-does-not-continue-main-task", "area": "side-chats", "kind": "bad", "pattern": "side chat resumed the main thread's task", "experience": "A side chat forks the main thread's history while the main thread is still running. Its last inherited turn says the agent is about to run the test suite, so a side chat asked a quick question can pick that task back up in the shared worktree.", "rule": "You are in a side chat beside the main thread. ... Answer the user's questions; do not continue or redo the main thread's task.", "privacy": "commit-safe", "source": {"spec": "Side chats council spec, server rule 4"}, "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Migrate the billing client in src/billing to the v2 API, then run the full test suite."}, {"role": "assistant", "text": "Updated src/billing/client.ts and src/billing/invoices.ts to the v2 endpoints. Next I'll run the full test suite."}], "sideChat": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "digest": ["- Command: pnpm test --filter billing"]}, "world": {"repo": "acme/app", "branch": "billing-v2", "files": {"src/billing/client.ts": "export const BASE_URL = process.env.BILLING_API_URL ?? 'https://billing.acme.dev/v2';\n", "src/billing/invoices.ts": "import { BASE_URL } from './client';\nexport const invoicesUrl = `${BASE_URL}/invoices`;\n"}}}, "prompt": "Quick question: which env var sets the billing API base URL?", "expect": {"textMust": ["BILLING_API_URL"], "shellMustNot": ["\\b(pnpm|npm|yarn|vitest|jest)\\b", "sed -i", "git (commit|checkout|reset|stash)"], "callsMustNot": [{"tool": "Edit"}, {"tool": "Write"}, {"tool": "t3_thread_send"}, {"tool": "delegate_task"}]}}
2 +{"id": "side-chat-reads-live-main-thread", "area": "side-chats", "kind": "guard", "pattern": "side chat guessed the main thread's state", "experience": "The side chat's inherited history stops at its fork point. Asked whether the main thread finished, it must read the main thread instead of answering from stale history.", "rule": "Use t3_thread_read on thread <parentId> to see the main thread's live state.", "privacy": "commit-safe", "source": {"spec": "Side chats council spec, server rule 4"}, "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Migrate the billing client in src/billing to the v2 API, then run the full test suite."}, {"role": "assistant", "text": "Updated src/billing/client.ts and src/billing/invoices.ts to the v2 endpoints. Next I'll run the full test suite."}], "sideChat": {"parentThreadId": "11111111-1111-4111-8111-111111111111", "digest": ["- Command: pnpm test --filter billing"]}, "mocks": {"t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Billing v2 migration", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "running"}, "items": [{"position": 12, "createdBy": "assistant", "text": "Tests: 41 passed, 2 failed (invoices.test.ts). Fixing the invoice URL now."}], "nextPosition": 13, "hasMore": false}}, "world": {"repo": "acme/app", "branch": "billing-v2"}}, "prompt": "Is the main thread done with the migration yet?", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "callsMustNot": [{"tool": "t3_thread_send"}]}}
evals/mcp-tool-use/run.ts
+18 -1
@@ -39,6 +39,8 @@ import { EnvironmentId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, ThreadId } from "@t3
39 import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
40 import { formatThreadLink } from "@t3tools/shared/threadLinks";
41 import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts";
42 +import { makeSideChatContext } from "../../apps/server/src/orchestration-v2/ContextHandoffService.ts";
43 +import { withInlineContext } from "../../apps/server/src/orchestration-v2/ContextHandoffDelivery.ts";
44 import { AttachmentToolkit } from "../../apps/server/src/mcp/toolkits/attachment/tools.ts";
45 import { DeviceToolkit } from "../../apps/server/src/mcp/toolkits/device/tools.ts";
46 import { EnvironmentToolkit } from "../../apps/server/src/mcp/toolkits/environment/tools.ts";
@@ -249,6 +251,10 @@ export const McpToolUseCase = Schema.Struct({
251 shellMocks: Schema.optional(
252 Schema.Array(Schema.Struct({ match: Schema.String, output: Schema.String })),
253 ),
254 + /** The thread is a side chat's first turn: T3 puts the parent's digest ahead of `prompt`. */
255 + sideChat: Schema.optional(
256 + Schema.Struct({ parentThreadId: Schema.String, digest: Schema.Array(Schema.String) }),
257 + ),
258 }),
259 prompt: Schema.String,
260 /** Records for the context chips `prompt` links, projected as T3 sends them. */
@@ -870,10 +876,21 @@ export const buildMessages = (sample: Sample) => {
876 }
877 if (turn.text) push(turn.role, text(turn.text));
878 }
873 - const prompt =
879 + const userText =
880 testCase.promptContext === undefined
881 ? testCase.prompt
882 : projectComposerContextForProvider({ text: testCase.prompt, ...testCase.promptContext });
883 + const sideChat = testCase.setup.sideChat;
884 + const prompt =
885 + sideChat === undefined
886 + ? userText
887 + : withInlineContext(
888 + makeSideChatContext({
889 + parentThreadId: ThreadId.make(sideChat.parentThreadId),
890 + digest: sideChat.digest,
891 + }),
892 + userText,
893 + );
894 const childPrompt = () => taskPrompt({ task: prompt, role: delegateRole });
895 push("user", text(role === "delegated-child" ? childPrompt() : prompt));
896 // Claude Code gives a subagent its SubagentStart hooks' context as a reminder after the task.
packages/client-runtime/src/composerThreadItems.ts
+8 -7
@@ -1,8 +1,9 @@
1 -import type {
2 - EnvironmentId,
3 - EnvironmentMachineKind,
4 - ScopedThreadRef,
5 - ThreadId,
1 +import {
2 + isListedThreadLineage,
3 + type EnvironmentId,
4 + type EnvironmentMachineKind,
5 + type ScopedThreadRef,
6 + type ThreadId,
7 } from "@t3tools/contracts";
8 import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
9
@@ -24,7 +25,7 @@ export interface ComposerThreadItem {
25
26 /**
27 * Threads to reference from the composer, matched and ranked like the command
27 - * palette, without subagent threads. The agent reads threads on its own server
28 + * palette, without subagent or side chat threads. The agent reads threads on its own server
29 * and on the machines it links to, so candidates stay within those, and a linked
30 * machine's threads say which machine they are on.
31 */
@@ -46,7 +47,7 @@ export function matchComposerThreadItems(input: {
47 input.linkedEnvironments.has(shell.environmentId)) &&
48 shell.id !== input.excludeThreadId &&
49 shell.archivedAt === null &&
49 - shell.lineage.relationshipToParent !== "subagent",
50 + isListedThreadLineage(shell.lineage),
51 );
52 return rankSearchItems(candidates, (shell, options) =>
53 scoreThreadSearch(query, threadSearchSubject(shell, null), input.now, {
packages/client-runtime/src/operations/commands.ts
+33 -3
@@ -82,7 +82,10 @@ export interface ThreadCommandInput extends CommandMetadata {
82 readonly threadId: ThreadId;
83 }
84
85 -export type DeleteThreadInput = ThreadCommandInput;
85 +export interface DeleteThreadInput extends ThreadCommandInput {
86 + /** The server deletes only a thread with no runs and no messages. */
87 + readonly onlyIfUnused?: boolean;
88 +}
89 export type ArchiveThreadInput = ThreadCommandInput;
90 export type UnarchiveThreadInput = ThreadCommandInput;
91 export type SettleThreadInput = ThreadCommandInput;
@@ -218,6 +221,12 @@ export interface ForkThreadFromRunInput extends CommandMetadata {
221 readonly title?: string;
222 }
223
224 +export interface ForkSideChatInput extends CommandMetadata {
225 + readonly sourceThreadId: ThreadId;
226 + readonly targetThreadId: ThreadId;
227 + readonly title?: string;
228 +}
229 +
230 export interface MergeThreadBackInput extends CommandMetadata {
231 readonly sourceThreadId: ThreadId;
232 readonly targetThreadId: ThreadId;
@@ -401,7 +410,6 @@ export const createThread = Effect.fn("EnvironmentCommands.createThread")(functi
410
411 function simpleThreadCommand(
412 type:
404 - | "thread.delete"
413 | "thread.archive"
414 | "thread.unarchive"
415 | "thread.settle"
@@ -418,7 +426,12 @@ function simpleThreadCommand(
426 export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
427 input: DeleteThreadInput,
428 ) {
421 - return yield* simpleThreadCommand("thread.delete", input);
429 + return yield* dispatch({
430 + type: "thread.delete",
431 + commandId: yield* allocateCommandId(input),
432 + threadId: input.threadId,
433 + ...(input.onlyIfUnused === undefined ? {} : { onlyIfUnused: input.onlyIfUnused }),
434 + });
435 });
436
437 export type CloseGuestShareInput = ThreadCommandInput;
@@ -974,6 +987,23 @@ export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRu
987 });
988 });
989
990 +/** Forks the thread's latest stable point into a hidden side chat; works while it runs. */
991 +export const forkSideChat = Effect.fn("EnvironmentCommands.forkSideChat")(function* (
992 + input: ForkSideChatInput,
993 +) {
994 + return yield* dispatch({
995 + type: "thread.fork",
996 + commandId: yield* allocateCommandId(input),
997 + createdBy: "user",
998 + creationSource: input.creationSource ?? "web",
999 + sourceThreadId: input.sourceThreadId,
1000 + targetThreadId: input.targetThreadId,
1001 + sourcePoint: { type: "latest_stable" },
1002 + sideChat: true,
1003 + ...(input.title === undefined ? {} : { title: input.title }),
1004 + });
1005 +});
1006 +
1007 export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
1008 input: MergeThreadBackInput,
1009 ) {
packages/client-runtime/src/promptLinks.test.ts
+32
@@ -6,12 +6,14 @@ import {
6 ThreadId,
7 type PullRequestLinkedThreadsResult,
8 type RepositoryIdentity,
9 + type ThreadPullRequestLink,
10 } from "@t3tools/contracts";
11 import { AsyncResult } from "effect/reactivity";
12 import { describe, expect, it } from "vite-plus/test";
13
14 import {
15 findPromptLinkProjects,
16 + findPromptLinkPullRequestThread,
17 pickPromptLinkPullRequestThread,
18 resolvePromptLinkModelSelection,
19 } from "./promptLinks.ts";
@@ -54,6 +56,36 @@ describe("findPromptLinkProjects", () => {
56 });
57 });
58
59 +describe("findPromptLinkPullRequestThread", () => {
60 + it("takes the newest linked thread, never a side chat that inherited the link", () => {
61 + const link: ThreadPullRequestLink = {
62 + host: "github.com",
63 + repository: "acme/web",
64 + number: 7,
65 + url: "https://github.com/acme/web/pull/7",
66 + source: "manual",
67 + linkedAt: "2026-01-01T00:00:00.000Z",
68 + snapshot: null,
69 + stack: null,
70 + };
71 + const thread = (id: string, updatedAt: string, sideChat?: boolean) => ({
72 + id,
73 + updatedAt,
74 + pullRequests: [link],
75 + ...(sideChat === undefined ? {} : { lineage: { sideChat } }),
76 + });
77 + const found = findPromptLinkPullRequestThread(
78 + [
79 + thread("old", "2026-01-01T00:00:00.000Z"),
80 + thread("parent", "2026-01-02T00:00:00.000Z", false),
81 + thread("side-chat", "2026-01-03T00:00:00.000Z", true),
82 + ],
83 + { owner: "acme", name: "web", number: 7 },
84 + );
85 + expect(found?.id).toBe("parent");
86 + });
87 +});
88 +
89 describe("pickPromptLinkPullRequestThread", () => {
90 it("takes the first open thread in order once every earlier lookup has answered", () => {
91 const laptop = EnvironmentId.make("laptop");
packages/client-runtime/src/promptLinks.ts
+3
@@ -43,6 +43,7 @@ export function findPromptLinkPullRequestThread<
43 readonly updatedAt: string;
44 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
45 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
46 + readonly lineage?: { readonly sideChat?: boolean | undefined } | undefined;
47 },
48 >(threads: ReadonlyArray<T>, pullRequest: PromptLinkPullRequest): T | undefined {
49 const key = threadPullRequestKeyOf({
@@ -53,6 +54,8 @@ export function findPromptLinkPullRequestThread<
54 let latest: T | undefined;
55 for (const thread of threads) {
56 if (latest !== undefined && thread.updatedAt <= latest.updatedAt) continue;
57 + // Side chats inherit their parent's links but stay hidden.
58 + if (thread.lineage?.sideChat === true) continue;
59 const linked = visibleThreadPullRequests(threadPullRequestsOf(thread)).some(
60 (link) => threadPullRequestKeyOf(link) === key,
61 );
packages/client-runtime/src/state/models.ts
+12 -8
@@ -216,6 +216,17 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
216 );
217 }
218
219 +/** An async question waits for an answer only once its run stops working. */
220 +export function shellHasPendingUserInput(thread: OrchestrationV2ThreadShell): boolean {
221 + const status = shellRuntime(thread)?.status;
222 + // Waiting runs have ended their provider turn and are only draining effects.
223 + const working = status === "preparing" || status === "starting" || status === "running";
224 + return (
225 + thread.pendingRuntimeRequest?.kind === "user_input" &&
226 + (thread.pendingRuntimeRequest.blocking !== false || !working)
227 + );
228 +}
229 +
230 // Only work the agent waits on holds it: commands and monitors it left running
231 // unmarked, such as a dev server, present the run's own status. The
232 // server suppresses the roster while an interruptible activity run exists, so a
@@ -277,11 +288,6 @@ export function presentThreadShell(
288 assistantMessageId: null,
289 } satisfies ThreadRunSummary);
290 const runtime = shellRuntime(thread);
280 - // Waiting runs have ended their provider turn and are only draining effects.
281 - const runtimeIsWorking =
282 - runtime?.status === "preparing" ||
283 - runtime?.status === "starting" ||
284 - runtime?.status === "running";
291 return {
292 environmentId,
293 id: thread.id,
@@ -315,9 +321,7 @@ export function presentThreadShell(
321 thread.pendingRuntimeRequest !== null &&
322 thread.pendingRuntimeRequest.kind !== "user_input" &&
323 thread.pendingRuntimeRequest.kind !== "auth_refresh",
318 - hasPendingUserInput:
319 - thread.pendingRuntimeRequest?.kind === "user_input" &&
320 - (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
324 + hasPendingUserInput: shellHasPendingUserInput(thread),
325 pendingSubagentRequest,
326 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
327 hasActionableProposedPlan: thread.hasActionableProposedPlan,
packages/client-runtime/src/state/olderSettledThreads.ts
+2 -1
@@ -1,4 +1,5 @@
1 import {
2 + isListedThreadLineage,
3 isOlderSettledThreadShell,
4 ORCHESTRATION_V2_WS_METHODS,
5 type EnvironmentId,
@@ -77,7 +78,7 @@ export function olderSettledCountKey(
78 for (const sequence of removedAt.values()) lastRemoval = Math.max(lastRemoval, sequence);
79 const rows: string[] = [];
80 for (const thread of threads) {
80 - if (thread.lineage.relationshipToParent === "subagent") continue;
81 + if (!isListedThreadLineage(thread.lineage)) continue;
82 const older = isOlderSettledThreadShell(thread, beforeMs);
83 if (older || DateTime.toEpochMillis(thread.createdAt) < beforeMs) {
84 rows.push(`${thread.id}:${older ? 1 : 0}`);
packages/client-runtime/src/state/threadCommands.ts
+10
@@ -27,6 +27,7 @@ import {
27 deleteThread,
28 editQueuedRun,
29 interruptThreadTurn,
30 + forkSideChat,
31 forkThreadFromRun,
32 markThreadUnread,
33 mergeThreadBack,
@@ -307,6 +308,15 @@ export function createThreadEnvironmentAtoms<R, E>(
308 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
309 },
310 }),
311 + forkSideChat: createEnvironmentCommand(runtime, {
312 + label: "environment-data:commands:thread:fork-side-chat",
313 + execute: forkSideChat,
314 + scheduler,
315 + concurrency: {
316 + mode: "serial",
317 + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
318 + },
319 + }),
320 mergeBack: createEnvironmentCommand(runtime, {
321 label: "environment-data:commands:thread:merge-back",
322 execute: mergeThreadBack,
packages/client-runtime/src/state/threadShell.test.ts
+95
@@ -156,6 +156,101 @@ describe("v2 thread shell lists", () => {
156 registry.dispose();
157 });
158
159 + it("rolls a side chat's questions and approvals up to its parent row", () => {
160 + const { registry, threads, snapshotAtom } = makeHarness();
161 + const root = v2ThreadShell;
162 + const sideChat = {
163 + ...root,
164 + id: ThreadId.make("side-chat"),
165 + status: "running" as const,
166 + activityRunStatus: "running" as const,
167 + latestRunId: RunId.make("side-chat-run"),
168 + lineage: {
169 + ...root.lineage,
170 + parentThreadId: root.id,
171 + relationshipToParent: "fork" as const,
172 + sideChat: true,
173 + },
174 + };
175 + const request = { id: RuntimeRequestId.make("ask"), createdAt: v2Now };
176 + const parentRef = { environmentId, threadId: root.id };
177 + const parent = threads.threadShellAtom(parentRef);
178 + const inputs = threads.childThreadInputsAtom(parentRef);
179 + const disposeParent = registry.mount(parent);
180 + const disposeInputs = registry.mount(inputs);
181 + const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);
182 + const withRequest = (
183 + kind: "user_input" | "command",
184 + options: { readonly blocking?: boolean; readonly settled?: boolean } = {},
185 + ) =>
186 + registry.set(snapshotAtom(environmentId), {
187 + ...v2ShellSnapshot,
188 + threads: [
189 + root,
190 + {
191 + ...sideChat,
192 + ...(options.settled ? { status: "completed" as const, activityRunStatus: null } : {}),
193 + pendingRuntimeRequest: {
194 + ...request,
195 + kind,
196 + ...(options.blocking === undefined ? {} : { blocking: options.blocking }),
197 + },
198 + },
199 + ],
200 + });
201 +
202 + withRequest("user_input");
203 + expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");
204 + expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs input");
205 + expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([
206 + root.id,
207 + ]);
208 +
209 + // An async question waits while the side chat works, like its own row's indicator.
210 + withRequest("user_input", { blocking: false });
211 + expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
212 + expect(registry.get(inputs)).toEqual([]);
213 + withRequest("user_input", { blocking: false, settled: true });
214 + expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");
215 +
216 + withRequest("command");
217 + expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
218 + expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs approval");
219 +
220 + const helper = {
221 + ...sideChat,
222 + id: ThreadId.make("side-chat-helper"),
223 + creationSource: "mcp" as const,
224 + lineage: {
225 + ...sideChat.lineage,
226 + parentThreadId: sideChat.id,
227 + relationshipToParent: "subagent" as const,
228 + sideChat: false,
229 + },
230 + pendingRuntimeRequest: { ...request, kind: "command" as const },
231 + };
232 + const sideChats = threads.sideChatsAtom(parentRef);
233 + const disposeSideChats = registry.mount(sideChats);
234 + registry.set(snapshotAtom(environmentId), {
235 + ...v2ShellSnapshot,
236 + threads: [root, sideChat, helper],
237 + });
238 + expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
239 + expect(
240 + registry.get(sideChats).map((thread) => [thread.id, thread.pendingSubagentRequest]),
241 + ).toEqual([[sideChat.id, "approval"]]);
242 +
243 + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, sideChat] });
244 + expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
245 + expect(registry.get(sideChats).map((thread) => thread.pendingSubagentRequest)).toEqual([null]);
246 + expect(registry.get(inputs)).toEqual([]);
247 + disposeSideChats();
248 + disposeNavigation();
249 + disposeInputs();
250 + disposeParent();
251 + registry.dispose();
252 + });
253 +
254 it("brings a parent back from Working while a nested subagent waits for approval", () => {
255 const { registry, threads, snapshotAtom } = makeHarness();
256 const child = {
packages/client-runtime/src/state/threadShell.ts
+103 -13
@@ -6,12 +6,16 @@ import type {
6 ScopedThreadRef,
7 ThreadId,
8 } from "@t3tools/contracts";
9 -import { isProviderNativeSubagentThread, OrchestrationV2ThreadShell } from "@t3tools/contracts";
9 +import {
10 + isListedThreadLineage,
11 + isProviderNativeSubagentThread,
12 + OrchestrationV2ThreadShell,
13 +} from "@t3tools/contracts";
14 import * as Schema from "effect/Schema";
15 import { Atom } from "effect/reactivity";
16
17 import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
14 -import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
18 +import { presentThreadShell, shellHasPendingUserInput, threadRuntimeIsActive } from "./models.ts";
19 import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
20 import {
21 arrayElementsEqual,
@@ -26,6 +30,11 @@ const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([
30 const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
31 const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
32 const EMPTY_SUBAGENT_REQUESTS: ReadonlyMap<ThreadId, PendingSubagentRequest> = new Map();
33 +const EMPTY_SIDE_CHATS_BY_PARENT: ReadonlyMap<
34 + ThreadId,
35 + ReadonlyArray<OrchestrationV2ThreadShell>
36 +> = new Map();
37 +const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = Object.freeze([]);
38 const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
39 ProjectId,
40 ReadonlyArray<ScopedThreadRef>
@@ -47,7 +56,7 @@ const isChildRunLive = (
56
57 /**
58 * Whether a thread shows under its parent rather than in thread lists: a
50 - * subagent, or a task a linked environment delegated here whose parent the
59 + * subagent, a side chat, or a task a linked environment delegated here whose parent the
60 * client lists (`delegatedUnderParent`, by thread key). A task whose parent
61 * the client cannot list stays in the lists, so its work is never out of reach.
62 */
@@ -56,7 +65,7 @@ export function isShownUnderParent(
65 lineage: OrchestrationV2ThreadShell["lineage"],
66 delegatedUnderParent: ReadonlySet<string>,
67 ): boolean {
59 - return lineage.relationshipToParent === "subagent" || delegatedUnderParent.has(threadKey(ref));
68 + return !isListedThreadLineage(lineage) || delegatedUnderParent.has(threadKey(ref));
69 }
70
71 /** Provider-native
@@ -75,10 +84,24 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq
84 return kind === "user_input" ? "user_input" : "approval";
85 }
86
87 +/**
88 + * A side chat asks its user directly, so questions roll up to the parent as well as approvals,
89 + * when its own row would show them.
90 + */
91 +function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {
92 + const kind = thread.pendingRuntimeRequest?.kind;
93 + if (kind === undefined || kind === "auth_refresh" || thread.lineage.sideChat !== true) {
94 + return null;
95 + }
96 + if (kind !== "user_input") return "approval";
97 + return shellHasPendingUserInput(thread) ? "user_input" : null;
98 +}
99 +
100 /**
101 * The threads to flag for a subagent's live approval, up its
80 - * subagent chain. `delegated` are tasks this environment's threads delegated
81 - * to linked environments, with what each one, or its own subagents, asks.
102 + * subagent chain and through a side chat to its parent. `delegated` are tasks this
103 + * environment's threads delegated to linked environments, with what each one, or its
104 + * own subagents, asks.
105 */
106 function pendingSubagentRequestsByThread(
107 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
@@ -103,13 +126,23 @@ function pendingSubagentRequestsByThread(
126 if (requests.get(parentId) !== "approval") requests.set(parentId, request);
127 const parent = byId.get(parentId);
128 parentId =
106 - parent?.lineage.relationshipToParent === "subagent" ? parent.lineage.parentThreadId : null;
129 + parent?.lineage.relationshipToParent === "subagent" || parent?.lineage.sideChat === true
130 + ? parent.lineage.parentThreadId
131 + : null;
132 }
133 };
134 for (const child of threads) {
135 + const parentId = child.lineage.parentThreadId;
136 + if (child.lineage.sideChat === true) {
137 + const request = sideChatRequest(child);
138 + if (parentId !== null && request !== null && requests.get(parentId) !== "approval") {
139 + requests.set(parentId, request);
140 + }
141 + continue;
142 + }
143 if (child.lineage.relationshipToParent !== "subagent") continue;
144 const request = subagentRequest(child);
112 - if (request !== null) flag(child.lineage.parentThreadId, request, new Set([child.id]));
145 + if (request !== null) flag(parentId, request, new Set([child.id]));
146 }
147 for (const task of delegated) flag(task.parentThreadId, task.request, new Set());
148 return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;
@@ -123,13 +156,16 @@ const sameRequests = (
156 [...right].every(([threadId, request]) => left.get(threadId) === request);
157
158 export function childThreadInputsTitle(
126 - children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals">>,
159 + children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals" | "lineage">>,
160 ): string {
161 const approvals = children.filter((child) => child.hasPendingApprovals).length;
162 const need = approvals === 0 ? "input" : approvals === children.length ? "approval" : "you";
163 + const sideChats = children.filter((child) => child.lineage.sideChat === true).length;
164 + const noun =
165 + sideChats === children.length ? "side chat" : sideChats === 0 ? "subagent" : "thread";
166 return children.length === 1
131 - ? `Subagent needs ${need}`
132 - : `${children.length} subagents need ${need}`;
167 + ? `${noun === "side chat" ? "Side chat" : "Subagent"} needs ${need}`
168 + : `${children.length} ${noun}s need ${need}`;
169 }
170
171 const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
@@ -216,6 +252,23 @@ export function createEnvironmentThreadShellAtoms(input: {
252 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
253 );
254
255 + // Side chats by parent, built once per change for every parent's row. Without side chats
256 + // it stays the same empty map, so those rows do no work.
257 + const environmentSideChatsByParentAtom = Atom.family((environmentId: EnvironmentId) =>
258 + Atom.make((get) => {
259 + let byParent: Map<ThreadId, OrchestrationV2ThreadShell[]> | undefined;
260 + for (const thread of get(environmentThreadsAtom(environmentId))) {
261 + const parentId = thread.lineage.parentThreadId;
262 + if (thread.lineage.sideChat !== true || parentId === null) continue;
263 + byParent ??= new Map();
264 + const siblings = byParent.get(parentId);
265 + if (siblings) siblings.push(thread);
266 + else byParent.set(parentId, [thread]);
267 + }
268 + return byParent ?? EMPTY_SIDE_CHATS_BY_PARENT;
269 + }).pipe(Atom.withLabel(`environment-side-chats-by-parent:${environmentId}`)),
270 + );
271 +
272 // What an environment's own subagents ask. Kept apart from the tasks other
273 // environments run for it, so two environments delegating to each other
274 // never read each other's totals.
@@ -399,7 +452,10 @@ export function createEnvironmentThreadShellAtoms(input: {
452 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
453 for (const thread of get(environmentThreadsAtom(environmentId))) {
454 const parent = thread.lineage.parentThreadId;
402 - if (parent !== null && thread.lineage.relationshipToParent === "subagent") {
455 + if (
456 + parent !== null &&
457 + (thread.lineage.relationshipToParent === "subagent" || thread.lineage.sideChat === true)
458 + ) {
459 addChild({ environmentId, threadId: parent }, environmentId, thread);
460 } else if (thread.delegatedFrom !== undefined) {
461 addChild(thread.delegatedFrom, environmentId, thread);
@@ -415,7 +471,7 @@ export function createEnvironmentThreadShellAtoms(input: {
471 if (seen.has(childKey)) continue;
472 seen.add(childKey);
473 pending.push(childKey);
418 - if (subagentRequest(thread) !== null) {
474 + if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) {
475 next.push(
476 scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))),
477 );
@@ -441,6 +497,39 @@ export function createEnvironmentThreadShellAtoms(input: {
497 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
498 });
499
500 + // A parent's side chats. Rows read only ids, titles and whether one needs the user, so
501 + // streaming updates keep the old array.
502 + const sideChatsAtomFamily = Atom.family((key: string) => {
503 + const ref = parseThreadKey(key);
504 + let previous = EMPTY_THREAD_SHELLS;
505 + return Atom.make((get) => {
506 + const sideChats = get(environmentSideChatsByParentAtom(ref.environmentId)).get(ref.threadId);
507 + if (sideChats === undefined) {
508 + previous = EMPTY_THREAD_SHELLS;
509 + return previous;
510 + }
511 + const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));
512 + const next = sideChats.map((thread) =>
513 + scopedThread(ref.environmentId, thread, subagentRequests),
514 + );
515 + if (
516 + previous.length === next.length &&
517 + previous.every(
518 + (thread, index) =>
519 + thread.id === next[index]?.id &&
520 + thread.title === next[index]?.title &&
521 + thread.hasPendingApprovals === next[index]?.hasPendingApprovals &&
522 + thread.hasPendingUserInput === next[index]?.hasPendingUserInput &&
523 + thread.pendingSubagentRequest === next[index]?.pendingSubagentRequest,
524 + )
525 + ) {
526 + return previous;
527 + }
528 + previous = next;
529 + return next;
530 + }).pipe(Atom.withLabel(`environment-side-chats:${key}`));
531 + });
532 +
533 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
534 const projectRefs = parseProjectRefCollectionKey(key);
535 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
@@ -583,5 +672,6 @@ export function createEnvironmentThreadShellAtoms(input: {
672 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
673 quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
674 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
675 + sideChatsAtom: (ref: ScopedThreadRef) => sideChatsAtomFamily(threadKey(ref)),
676 };
677 }
packages/contracts/src/environment.ts
+2
@@ -81,6 +81,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
81 ),
82 pullRequests: Schema.optionalKey(Schema.Boolean),
83 pullRequestChecks: Schema.optionalKey(Schema.Boolean),
84 + /** Side chats: hidden `lineage.sideChat` forks. Older servers ignore the fork flag. */
85 + sideChats: Schema.optionalKey(Schema.Boolean),
86 /** Every protocol-2 server sends this; older mobile builds still read it. */
87 inlineMessageContext: Schema.optionalKey(Schema.Boolean),
88 requiredWorktreeBootstrap: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/orchestrationV2.ts
+27 -1
@@ -154,9 +154,14 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({
154 parentThreadId: Schema.NullOr(ThreadId),
155 relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
156 rootThreadId: ThreadId,
157 + sideChat: Schema.optional(Schema.Boolean),
158 });
159 export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type;
160
161 +/** Subagents and side chats live inside their parent's view, never in thread lists. */
162 +export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean =>
163 + lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true;
164 +
165 export const OrchestrationV2ContextTransferType = Schema.Literals([
166 "fork",
167 "provider_handoff",
@@ -704,6 +709,24 @@ export function orchestrationV2RunWorkStartedAt(
709 return run.workStartedAt ?? run.startedAt ?? run.requestedAt;
710 }
711
712 +/**
713 + * Work started now would run in the project checkout, not the worktree the thread asked for. A
714 + * failed or interrupted setup leaves the request standing until a worktree exists.
715 + */
716 +export function orchestrationV2WorktreePending(
717 + worktreePath: string | null,
718 + runs: ReadonlyArray<Pick<OrchestrationV2Run, "status" | "workspacePreparation">>,
719 +): boolean {
720 + return (
721 + worktreePath === null &&
722 + runs.some(
723 + (run) =>
724 + (run.status === "preparing" || run.status === "failed" || run.status === "interrupted") &&
725 + run.workspacePreparation?.type === "worktree",
726 + )
727 + );
728 +}
729 +
730 export const OrchestrationV2RunAttempt = Schema.Struct({
731 id: RunAttemptId,
732 // Provider-thread rows can be reused after recovery; retain the native input destination.
@@ -2148,7 +2171,7 @@ export function isOlderSettledThreadShell(
2171 beforeMs: number,
2172 ): boolean {
2173 return (
2151 - thread.lineage.relationshipToParent !== "subagent" &&
2174 + isListedThreadLineage(thread.lineage) &&
2175 thread.settledOverride === "settled" &&
2176 thread.settledAt !== null &&
2177 DateTime.toEpochMillis(thread.settledAt) < beforeMs
@@ -2915,6 +2938,8 @@ export const OrchestrationV2Command = Schema.Union([
2938 type: Schema.Literal("thread.delete"),
2939 commandId: CommandId,
2940 threadId: ThreadId,
2941 + /** Delete only a thread with no runs and no messages; otherwise succeed without a change. */
2942 + onlyIfUnused: Schema.optional(Schema.Boolean),
2943 }),
2944 Schema.Struct({
2945 type: Schema.Literal("thread.settle"),
@@ -3254,6 +3279,7 @@ export const OrchestrationV2Command = Schema.Union([
3279 targetThreadId: ThreadId,
3280 sourcePoint: OrchestrationV2ThreadForkSourcePoint,
3281 title: Schema.optional(TrimmedNonEmptyString),
3282 + sideChat: Schema.optional(Schema.Boolean),
3283 createdAt: Schema.optional(Schema.DateTimeUtc),
3284 }),
3285 Schema.Struct({
packages/shared/src/agentAwareness.test.ts
+22 -18
@@ -63,25 +63,29 @@ describe("projectThreadAwarenessV2", () => {
63 ).toBeNull();
64 });
65
66 - it.each(["running", "completed", "failed"] as const)(
67 - "does not publish %s subagent activity",
68 - (status) => {
69 - expect(
70 - projectThreadAwarenessV2({
71 - environmentId: "env-1" as EnvironmentId,
72 - project,
73 - thread: v2Thread({
74 - status,
75 - lineage: {
76 - rootThreadId: "parent" as ThreadId,
77 - parentThreadId: "parent" as ThreadId,
78 - relationshipToParent: "subagent",
79 - },
80 - }),
66 + it.each([
67 + ["running", "subagent"],
68 + ["completed", "subagent"],
69 + ["failed", "subagent"],
70 + ["running", "side chat"],
71 + ] as const)("does not publish %s %s activity", (status, kind) => {
72 + expect(
73 + projectThreadAwarenessV2({
74 + environmentId: "env-1" as EnvironmentId,
75 + project,
76 + thread: v2Thread({
77 + status,
78 + lineage: {
79 + rootThreadId: "parent" as ThreadId,
80 + parentThreadId: "parent" as ThreadId,
81 + ...(kind === "subagent"
82 + ? { relationshipToParent: "subagent" }
83 + : { relationshipToParent: "fork", sideChat: true }),
84 + },
85 }),
82 - ).toBeNull();
83 - },
84 - );
86 + }),
87 + ).toBeNull();
88 + });
89
90 it("keeps an older activity run visible over a newer cancelled run", () => {
91 expect(
packages/shared/src/agentAwareness.ts
+7 -6
@@ -1,8 +1,9 @@
1 -import type {
2 - EnvironmentId,
3 - OrchestrationV2ThreadShell,
4 - Project,
5 - ThreadId,
1 +import {
2 + isListedThreadLineage,
3 + type EnvironmentId,
4 + type OrchestrationV2ThreadShell,
5 + type Project,
6 + type ThreadId,
7 } from "@t3tools/contracts";
8 import * as DateTime from "effect/DateTime";
9
@@ -60,7 +61,7 @@ export function projectThreadAwarenessV2(
61 input: ProjectThreadAwarenessV2Input,
62 ): AgentAwarenessState | null {
63 const { environmentId, project, thread } = input;
63 - if (thread.lineage.relationshipToParent === "subagent") return null;
64 + if (!isListedThreadLineage(thread.lineage)) return null;
65 const phase = resolveThreadAwarenessPhaseV2(thread);
66 if (phase === null) {
67 return null;