TypeScript
feat: side chats beside the main thread (#26901)
Theo Browne50c1c5dc5364
diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsxindex 88987819ddf..cc9946dded8 100644--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx@@ -8,7 +8,7 @@ import {type EnvironmentThreadSearchMatch,type ShownOrder,} from "@t3tools/client-runtime/state/thread-search";-import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";+import { isListedThreadLineage, THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";import {foldSearchQuery,PALETTE_MESSAGE_LIMIT,@@ -422,10 +422,7 @@ export function CommandPalette(props: {}),}));const threadItems: CommandPaletteItem[] = threads- .filter(- (thread) =>- thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",- )+ .filter((thread) => thread.archivedAt === null && isListedThreadLineage(thread.lineage)).map((thread) => {const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));const environment =diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex eab4d492766..870ab31f000 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -195,6 +195,7 @@ import { useThreadTurnSubagents } from "./ThreadAgentsSheet";import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";import { useThreadQueuedCount } from "./ThreadQueueControl";import { ThreadGuestShareBar } from "./ThreadGuestShareBar";+import { ThreadSideChatsRow } from "./ThreadSideChatsRow";import type { ThreadContentPresentation } from "./threadContentPresentation";import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";import { useOpenLinkedThread } from "./useOpenLinkedThread";@@ -1531,6 +1532,12 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {threadRef={props.selectedThreadDetailRef}canOperateThread={props.canOperateThread}/>+ {props.draftMode ? null : (+ <ThreadSideChatsRow+ environmentId={props.environmentId}+ threadId={props.selectedThread.id}+ />+ )}{props.feedbackSubmissions.map((submission) => (<ComposerFeedbackkey={submission.id}diff --git a/apps/mobile/src/features/threads/ThreadSideChatsRow.tsx b/apps/mobile/src/features/threads/ThreadSideChatsRow.tsxnew file mode 100644index 00000000000..b6c04c21ae4--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadSideChatsRow.tsx@@ -0,0 +1,66 @@+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { Pressable, ScrollView, View } from "react-native";++import { AppText as Text } from "../../components/ui/AppText";+import { SymbolView } from "../../components/ui/AppSymbol";+import { cn } from "../../lib/cn";+import { useSideChats } from "../../state/entities";+import { useOpenLinkedThread } from "./useOpenLinkedThread";++/**+ * The thread's side chats, started on web or desktop. Each opens as a normal thread, so its+ * approvals and questions can be answered from the phone.+ */+export function ThreadSideChatsRow(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+}) {+ const sideChats = useSideChats({ environmentId: props.environmentId, threadId: props.threadId });+ const openLinkedThread = useOpenLinkedThread();+ if (sideChats.length === 0) return null;+ return (+ <View className="flex-row items-center gap-2 pb-2 pl-4">+ <SymbolView+ name="bubble.left.and.bubble.right"+ size={12}+ tintColorClassName="accent-foreground-muted"+ />+ <Text className="text-xs text-foreground-muted">Side chats</Text>+ <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-1">+ <View className="flex-row gap-1 pr-4">+ {sideChats.map((sideChat) => {+ const needs =+ sideChat.hasPendingApprovals || sideChat.pendingSubagentRequest === "approval"+ ? "approval"+ : sideChat.hasPendingUserInput || sideChat.pendingSubagentRequest+ ? "input"+ : null;+ return (+ <Pressable+ key={sideChat.id}+ accessibilityRole="button"+ accessibilityLabel={`Open side chat ${sideChat.title}${needs === null ? "" : `, needs ${needs}`}`}+ className="max-w-48 flex-row items-center gap-1.5 rounded-full bg-subtle px-2.5 py-1"+ onPress={() =>+ openLinkedThread({ environmentId: props.environmentId, threadId: sideChat.id })+ }+ >+ {needs === null ? null : (+ <View+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ needs === "approval" ? "bg-warning-foreground" : "bg-adaptive-indigo-600-300",+ )}+ />+ )}+ <Text className="shrink text-xs text-foreground" numberOfLines={1}>+ {sideChat.title}+ </Text>+ </Pressable>+ );+ })}+ </View>+ </ScrollView>+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.tsindex ad02dd1192d..61280bad84e 100644--- a/apps/mobile/src/features/threads/threadListV2.ts+++ b/apps/mobile/src/features/threads/threadListV2.ts@@ -28,7 +28,7 @@ import {sortPinnedThreadsByOrderKey,sortSettledThreads,} from "@t3tools/client-runtime/state/thread-sort";-import type { EnvironmentId, ProjectId } from "@t3tools/contracts";+import { isListedThreadLineage, type EnvironmentId, type ProjectId } from "@t3tools/contracts";import type { SnoozePresetSetting } from "@t3tools/contracts/settings";import type { ThreadListProvider } from "../../state/thread-list-environments";@@ -265,8 +265,7 @@ export function getThreadListV2OrderedSection(input: {}): EnvironmentThreadShell[] {const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;const threads = input.threads.filter((thread) => {- if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")- return false;+ if (thread.archivedAt !== null || !isListedThreadLineage(thread.lineage)) return false;if ((input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&thread.settledOverride === "settled" &&@@ -647,7 +646,7 @@ export function buildThreadListV2Items(input: {const listedThreads = input.threads.filter((thread) =>thread.archivedAt === null &&- thread.lineage.relationshipToParent !== "subagent" &&+ isListedThreadLineage(thread.lineage) &&(input.environmentId === null || thread.environmentId === input.environmentId) &&(projectKeys === null || projectKeys.has(`${thread.environmentId}:${thread.projectId}`)),);diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.tsindex a376938ffb4..c5c33a5432e 100644--- a/apps/mobile/src/state/entities.ts+++ b/apps/mobile/src/state/entities.ts@@ -198,6 +198,10 @@ export function useChildThreadInputs(ref: ScopedThreadRef) {return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));}+export function useSideChats(ref: ScopedThreadRef) {+ return useAtomValue(environmentThreadShells.sideChatsAtom(ref));+}+export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {const titles = useAtomValue(hasThreadLinks(markdown)diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex b36fa64dc22..c8bf3445130 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -224,6 +224,7 @@ export const make = Effect.gen(function* () {fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },pullRequests: true,pullRequestChecks: true,+ sideChats: true,inlineMessageContext: true,requiredWorktreeBootstrap: true,threadSettlement: true,diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.tsindex ff19634917f..17fe7224773 100644--- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts+++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts@@ -719,4 +719,190 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {assert.deepEqual([...projected.readyCheckpointOrdinals].toSorted(), [0, 1]);}),);++ it.effect("completes a side chat run with a missing checkpoint and never touches git", () =>+ Effect.gen(function* () {+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const now = yield* DateTime.now;+ const sideChatThreadId = ThreadId.make("thread:checkpoint-capture-side-chat");+ const sideChatRunId = RunId.make("run:checkpoint-capture-side-chat");+ const sideChatScopeId = CheckpointScopeId.make("scope:checkpoint-capture-side-chat");+ const sideChatRootNodeId = NodeId.make("node:checkpoint-capture-side-chat-root");+ const sideChatProviderThreadId = ProviderThreadId.make(+ "provider-thread:checkpoint-capture-side-chat",+ );+ const event = { threadId: sideChatThreadId, occurredAt: now };+ const events: ReadonlyArray<OrchestrationV2DomainEvent> = [+ {+ ...event,+ id: EventId.make("event:checkpoint-capture-side-chat:thread"),+ type: "thread.created",+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: sideChatThreadId,+ projectId,+ title: "Side chat",+ providerInstanceId,+ modelSelection,+ runtimeMode: "approval-required",+ interactionMode: "default",+ branch: null,+ worktreePath: "/repo",+ activeProviderThreadId: null,+ lineage: {+ parentThreadId: threadId,+ relationshipToParent: "fork",+ rootThreadId: threadId,+ sideChat: true,+ },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ },+ {+ ...event,+ id: EventId.make("event:checkpoint-capture-side-chat:provider-thread"),+ type: "provider-thread.updated",+ driver,+ providerInstanceId,+ payload: {+ id: sideChatProviderThreadId,+ driver,+ providerInstanceId,+ providerSessionId: null,+ appThreadId: sideChatThreadId,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle",+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ },+ },+ {+ ...event,+ id: EventId.make("event:checkpoint-capture-side-chat:run"),+ type: "run.updated",+ runId: sideChatRunId,+ payload: {+ id: sideChatRunId,+ threadId: sideChatThreadId,+ ordinal: 1,+ providerInstanceId,+ modelSelection,+ providerThreadId: sideChatProviderThreadId,+ userMessageId: MessageId.make("message:checkpoint-capture-side-chat"),+ rootNodeId: sideChatRootNodeId,+ activeAttemptId: null,+ status: "waiting",+ requestedAt: now,+ startedAt: now,+ completedAt: null,+ checkpointId: null,+ contextHandoffId: null,+ },+ },+ {+ ...event,+ id: EventId.make("event:checkpoint-capture-side-chat:node"),+ type: "node.updated",+ runId: sideChatRunId,+ nodeId: sideChatRootNodeId,+ payload: {+ id: sideChatRootNodeId,+ threadId: sideChatThreadId,+ runId: sideChatRunId,+ parentNodeId: null,+ rootNodeId: sideChatRootNodeId,+ kind: "root_turn",+ status: "waiting",+ countsForRun: true,+ providerThreadId: sideChatProviderThreadId,+ providerTurnId: null,+ nativeItemRef: null,+ runtimeRequestId: null,+ checkpointScopeId: sideChatScopeId,+ startedAt: now,+ completedAt: null,+ },+ },+ {+ ...event,+ id: EventId.make("event:checkpoint-capture-side-chat:scope"),+ type: "checkpoint-scope.created",+ runId: sideChatRunId,+ nodeId: sideChatRootNodeId,+ payload: {+ id: sideChatScopeId,+ threadId: sideChatThreadId,+ runId: sideChatRunId,+ nodeId: sideChatRootNodeId,+ parentScopeId: null,+ providerThreadId: sideChatProviderThreadId,+ kind: "root_run",+ ordinalWithinParent: 0,+ advancesAppRunCount: true,+ cwd: "/repo",+ createdAt: now,+ },+ },+ ];+ yield* Effect.forEach(events, (candidate) => projectionStore.apply(candidate));+ const gitUnavailable = () => Effect.die("side chats must not snapshot the shared worktree");+ const layerCapture = CheckpointCaptureService.layer.pipe(+ Layer.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ CheckpointService.layer.pipe(+ Layer.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ NodeCrypto.layer,+ Layer.mock(CheckpointStore.CheckpointStore)({+ isGitRepository: gitUnavailable,+ captureCheckpoint: gitUnavailable,+ hasCheckpointRef: gitUnavailable,+ }),+ ),+ ),+ ),+ Layer.mock(EventSink.EventSinkV2)({+ commitCommand: (input) =>+ Effect.forEach(input.events, (committed) => projectionStore.apply(committed)).pipe(+ Effect.as({ committed: true } as never),+ Effect.orDie,+ ),+ }),+ ),+ ),+ );++ yield* CheckpointCaptureService.CheckpointCaptureServiceV2.use((service) =>+ service.execute({+ threadId: sideChatThreadId,+ runId: sideChatRunId,+ scopeId: sideChatScopeId,+ }),+ ).pipe(Effect.provide(layerCapture));++ const { checkpoints, runs } = yield* projectionStore.getThreadRecords(sideChatThreadId, [+ "runs",+ "checkpoints",+ ]);+ assert.equal(runs[0]?.status, "completed");+ const checkpoint = checkpoints.find((candidate) => candidate.id === runs[0]?.checkpointId);+ assert.equal(checkpoint?.status, "missing");+ }),+ );});diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.tsindex 8924943fda2..9d7d3cfd4ae 100644--- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts+++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts@@ -65,7 +65,7 @@ export const layer: Layer.Layer<readonly runId: RunId;readonly scopeId: CheckpointScopeId;}) {- const { run, rootNode, scope, providerThread, readyCheckpointOrdinals } =+ const { run, rootNode, scope, providerThread, readyCheckpointOrdinals, sideChat } =yield* projections.getCheckpointCaptureContext(input.threadId, input);// Stopped runs remain terminal; their checkpoint is the next message's rollback point.const stopped = run?.status === "interrupted" || run?.status === "cancelled";@@ -109,12 +109,14 @@ export const layer: Layer.Layer<: yield* checkpoints.materializeBaselineCheckpoint({scope,ordinalWithinScope: 0,+ forceMissing: sideChat,});const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)? null: yield* checkpoints.materializeBaselineCheckpoint({scope,ordinalWithinScope: baselineOrdinalWithinScope,+ forceMissing: sideChat,});const checkpoint = yield* checkpoints.capture({scope,@@ -123,6 +125,7 @@ export const layer: Layer.Layer<ordinalWithinScope: run.ordinal,appRunOrdinal: run.ordinal,capturedAt,+ forceMissing: sideChat,});// Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.tsindex f7290faf9c9..145de122f38 100644--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts@@ -64,6 +64,7 @@ it.effect.each([id: otherId,projectId,deletedAt: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: otherId },worktreePath:owner === "ancestor" || owner === "conversation"? parent@@ -202,3 +203,52 @@ it.effect("lets rollback recreate a worktree storage cleanup removed", () =>assert.isTrue(isolated);}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);++it.effect.each([+ { sideChat: "answering questions", running: false, toolItems: 0, isolated: true },+ { sideChat: "running", running: true, toolItems: 0, isolated: false },+ { sideChat: "after running tools", running: false, toolItems: 1, isolated: false },+] as const)(+ "a side chat $sideChat shares the parent's worktree: $isolated",+ ({ running, toolItems, isolated }) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const worktreePath = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-v2-restore-side-chat-",+ });+ const parentId = ThreadId.make("restore-side-chat-parent");+ const sideChat = {+ id: ThreadId.make("restore-side-chat"),+ projectId: ProjectId.make("restore-project"),+ deletedAt: null,+ worktreePath,+ activeRunId: running ? "side-chat-run" : null,+ lineage: {+ parentThreadId: parentId,+ relationshipToParent: "fork",+ rootThreadId: parentId,+ sideChat: true,+ },+ };+ const result = yield* isCheckpointRestoreIsolated(+ { id: parentId, worktreePath },+ { cwd: worktreePath },+ {+ fileSystem,+ path,+ projections: {+ getShellSnapshot: () => Effect.succeed({ threads: [sideChat], archivedThreads: [] }),+ getThreadRecords: () =>+ Effect.succeed({+ turnItems: Array.from({ length: toolItems }, () => ({ type: "command_execution" })),+ }),+ getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] }),+ getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),+ } as never,+ projects: {} as never,+ },+ );+ assert.equal(result, isolated);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.tsindex 268549d7bf7..b7dc08018a8 100644--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts@@ -7,7 +7,7 @@ import type { ProjectionStoreV2 } from "./ProjectionStore.ts";import type * as ProjectStore from "./ProjectStore.ts";export const SHARED_WORKSPACE_RESTORE_MESSAGE =- "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.";+ "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.";// Check isolation at admission and rollback; checkpoints restore whole checkouts, which may become shared.export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(@@ -48,6 +48,21 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoiconst checkedPaths = new Set<string>();for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;+ // An idle side chat that only answered questions never touched the shared worktree.+ if (+ otherThread.lineage.sideChat === true &&+ otherThread.activeRunId === null &&+ otherThread.worktreePath === worktreePath+ ) {+ const { turnItems } = yield* projections.getThreadRecords(+ otherThread.id,+ ["turnItems"],+ {+ turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],+ },+ );+ if (turnItems.length === 0) continue;+ }const other = yield* projections.getCheckpointContext(otherThread.id);const providerContext = yield* projections.getThreadProviderContext(otherThread.id);const paths = [diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.tsindex 2747fcefac7..5990456e64f 100644--- a/apps/server/src/orchestration-v2/CheckpointService.ts+++ b/apps/server/src/orchestration-v2/CheckpointService.ts@@ -118,6 +118,8 @@ export interface CheckpointServiceV2Shape {readonly materializeBaselineCheckpoint: (input: {readonly scope: OrchestrationV2CheckpointScope;readonly ordinalWithinScope: number;+ /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */+ readonly forceMissing?: boolean;}) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;readonly capture: (input: {readonly scope: OrchestrationV2CheckpointScope;@@ -126,6 +128,7 @@ export interface CheckpointServiceV2Shape {readonly ordinalWithinScope: number;readonly appRunOrdinal: number | null;readonly capturedAt: DateTime.Utc;+ readonly forceMissing?: boolean;}) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;readonly restore: (input: {readonly scope: OrchestrationV2CheckpointScope;@@ -299,7 +302,8 @@ export const layer: Layer.Layer<scopeId: input.scope.id,ordinalWithinScope: input.ordinalWithinScope,});- const checkpointable = yield* isGitCheckpointable(input.scope.cwd);+ const checkpointable =+ input.forceMissing !== true && (yield* isGitCheckpointable(input.scope.cwd));const available = checkpointable? yield* checkpointStore.hasCheckpointRef({@@ -364,7 +368,7 @@ export const layer: Layer.Layer<ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),});- if (!(yield* isGitCheckpointable(input.scope.cwd))) {+ if (input.forceMissing === true || !(yield* isGitCheckpointable(input.scope.cwd))) {return makeCheckpoint({id: checkpointId,scope: input.scope,diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.tsindex cf982c9699f..8ed4de3e9de 100644--- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts+++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts@@ -260,9 +260,31 @@ layer("CommandPolicyV2", (it) => {hasStrongNativeSource: true,sourceRunStatus: "completed",fromSpecificTurn: true,+ sourceBusy: false,});assert.equal(result, "portable_context");}),);++ it.effect("forks a busy source through portable context", () =>+ Effect.gen(function* () {+ const policy = yield* CommandPolicy.CommandPolicyV2;+ const decide = (sourceBusy: boolean) =>+ policy.decideForkExecution({+ commandId,+ threadId,+ providerInstanceId: ProviderInstanceId.make("codex"),+ capabilities: CodexProviderCapabilitiesV2,+ sameProvider: true,+ hasStrongNativeSource: true,+ sourceRunStatus: "completed",+ fromSpecificTurn: true,+ sourceBusy,+ });++ assert.equal(yield* decide(false), "native_fork");+ assert.equal(yield* decide(true), "portable_context");+ }),+ );});diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.tsindex 86985179017..02f329e536f 100644--- a/apps/server/src/orchestration-v2/CommandPolicy.ts+++ b/apps/server/src/orchestration-v2/CommandPolicy.ts@@ -115,7 +115,8 @@ export function resolveMessageDispatchIntent(: mode;}-function isActiveRun(run: OrchestrationV2Run): boolean {+/** A run that still owns the thread's provider turn. */+export function isActiveRun(run: OrchestrationV2Run): boolean {return (run.status === "preparing" ||run.status === "starting" ||@@ -210,6 +211,8 @@ export interface CommandPolicyV2Shape {readonly hasStrongNativeSource: boolean;readonly sourceRunStatus: OrchestrationV2Run["status"];readonly fromSpecificTurn: boolean;+ /** Later source runs are still active; providers cannot fork a thread mid-turn. */+ readonly sourceBusy: boolean;},) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;readonly ensureRollback: (@@ -373,6 +376,7 @@ const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input)(input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") &&input.sameProvider &&input.hasStrongNativeSource &&+ !input.sourceBusy &&input.capabilities.threads.canForkThread &&(!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&input.capabilities.identity.nativeThreadIds === "strong";diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.tsindex ff2ca1fbec4..adff6f65d8e 100644--- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts+++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts@@ -12,6 +12,10 @@ import {selectHistory,} from "@t3tools/provider-core/server/handoffBudget";+/** The provider prompt for a turn that carries inline context ahead of the user's text. */+export const withInlineContext = (context: string, userText: string): string =>+ context === "" ? userText : `${context}\n\nUser message:\n${userText}`;+/** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(function* <InjectError = never, PersistError = never, BudgetError = never>(input: {diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.tsindex aa13f23b950..d9005e6b640 100644--- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts+++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts@@ -1,11 +1,13 @@import { assert, it } from "@effect/vitest";import {MessageId,+ ProjectId,ProviderInstanceId,ProviderThreadId,RunId,ThreadId,TurnItemId,+ type OrchestrationV2AppThread,type OrchestrationV2TurnItem,} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";@@ -14,6 +16,7 @@ import * as Layer from "effect/Layer";import * as ContextHandoffService from "./ContextHandoffService.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";+import { ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";const layerTest = ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer));@@ -156,3 +159,91 @@ it.layer(layerTest)("ContextHandoffService legacy import", (it) => {}),);});++it("caps the side chat context block, keeping the newest parent items", () => {+ const parentThreadId = ThreadId.make("thread:side-chat-parent");+ const digest = Array.from({ length: 60 }, (_, index) =>+ ContextHandoffService.summarizeDeltaItem(+ importedItem({+ role: index % 2 === 0 ? "user" : "assistant",+ id: `parent-${index}`,+ text: `item-${index} ${"x".repeat(300)}`,+ ordinal: index,+ }),+ )!,+ );+ const context = ContextHandoffService.makeSideChatContext({ parentThreadId, digest });++ assert.include(context, "- Earlier items truncated.");+ assert.notInclude(context, "item-0 ");+ assert.include(context, "- Assistant: item-59 ");+ assert.isAtMost(context.length, 8_000);+ assert.isTrue(+ context.endsWith(+ `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`,+ ),+ );++ const framingOnly = ContextHandoffService.makeSideChatContext({ parentThreadId, digest: [] });+ assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread."));+ assert.notInclude(framingOnly, "Main thread activity");+});++it("covers the run range of a very long delta", () => {+ const runs = [+ { id: RunId.make("run:long-delta-early"), ordinal: 2 },+ { id: RunId.make("run:long-delta-late"), ordinal: 5 },+ ];+ const items = Array.from({ length: 150_000 }, (_, index) => ({+ runId: runs[index % 2]!.id,+ }));++ assert.deepEqual(+ ContextHandoffService.visibleDeltaRunOrdinals({ runs }, [...items, { runId: null }]),+ { from: 2, to: 5 },+ );+});++it.effect("inherited history stops at a missing fork ancestor", () =>+ Effect.gen(function* () {+ const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");+ const threadId = ThreadId.make("thread:fork-of-missing");+ const thread: OrchestrationV2AppThread = {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId: ProjectId.make("project:fork-of-missing"),+ title: "Fork of a missing thread",+ providerInstanceId: ProviderInstanceId.make("codex"),+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: {+ type: "run",+ threadId: ThreadId.make("thread:missing-ancestor"),+ runId: RunId.make("run:missing-ancestor"),+ },+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ snoozedUntil: null,+ snoozedAt: null,+ deletedAt: null,+ };+ const items = yield* ContextHandoffService.readInheritedHandoffItems(+ {+ getThreadRecords: (missing) =>+ Effect.fail(new ProjectionStoreThreadNotFoundError({ threadId: missing })),+ },+ thread,+ );+ assert.deepEqual(items, []);+ }),+);diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.tsindex 1a1767b4df5..67a474d963b 100644--- a/apps/server/src/orchestration-v2/ContextHandoffService.ts+++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts@@ -1,7 +1,9 @@import {+ type OrchestrationV2AppThread,OrchestrationV2ContextHandoff,type OrchestrationV2TurnItem,type OrchestrationV2Run,+ type OrchestrationV2ThreadProjection,ProviderInstanceId,ProviderThreadId,RunId,@@ -22,6 +24,8 @@ import {selectHistory,} from "@t3tools/provider-core/server/handoffBudget";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";+import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline";+import type { ProjectionStoreV2Shape } from "./ProjectionStore.ts";export class ContextHandoffPrepareError extends Schema.TaggedError<ContextHandoffPrepareError>()("ContextHandoffPrepareError",@@ -80,6 +84,19 @@ export interface ContextHandoffServiceV2Shape {readonly items: ReadonlyArray<OrchestrationV2TurnItem>;readonly createdAt: DateTime.Utc;}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;+ /** Parent activity after the fork point, prepended to a side chat's first provider turn. */+ readonly prepareSideChatContext: (input: {+ readonly threadId: ThreadId;+ readonly parentThreadId: ThreadId;+ readonly targetRunId: RunId;+ readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;+ readonly toProviderThreadId: ProviderThreadId;+ readonly fromProviderInstanceId: ProviderInstanceId;+ readonly toProviderInstanceId: ProviderInstanceId;+ readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];+ readonly parentItems: ReadonlyArray<OrchestrationV2TurnItem>;+ readonly createdAt: DateTime.Utc;+ }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;}export class ContextHandoffServiceV2 extends Context.Service<@@ -95,7 +112,97 @@ function compactText(text: string, maxLength = 240): string {return `${compacted.slice(0, maxLength - 3)}...`;}-function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {+export function visibleDeltaRunOrdinals(+ projection: { readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "ordinal">> },+ items: ReadonlyArray<Pick<OrchestrationV2TurnItem, "runId">>,+): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {+ const ordinalByRunId = new Map(projection.runs.map((run) => [run.id, run.ordinal]));+ let from = Infinity;+ let to = -Infinity;+ for (const item of items) {+ const ordinal = item.runId === null ? undefined : ordinalByRunId.get(item.runId);+ if (ordinal === undefined) continue;+ from = Math.min(from, ordinal);+ to = Math.max(to, ordinal);+ }+ return from === Infinity ? { from: 1, to: 1 } : { from, to };+}++/** Drops rolled-back runs and cancelled queued messages, which are not part of the conversation. */+export function visibleConversationItems(+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts">,+ items: ReadonlyArray<OrchestrationV2TurnItem>,+): ReadonlyArray<OrchestrationV2TurnItem> {+ const visible = createOrchestrationV2TurnItemVisibility({+ runs: projection.runs,+ attempts: projection.attempts,+ items,+ });+ return items.filter(visible);+}++type ForkHistorySource = Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "attempts">;++/** Visible rows of `source`'s own runs through `throughRun`, plus its v1 imported rows. */+const readOwnHistoryItems = Effect.fn("orchestrationV2.contextHandoff.readOwnHistoryItems")(+ function* (+ projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,+ source: ForkHistorySource,+ throughRun: Pick<OrchestrationV2Run, "ordinal">,+ ) {+ const { turnItems } = yield* projectionStore.getThreadRecords(source.thread.id, ["turnItems"], {+ turnItemRunIds: [+ ...source.runs.filter((run) => run.ordinal <= throughRun.ordinal).map((run) => run.id),+ ...(source.thread.historyOrigin === "v1_import" ? [null] : []),+ ],+ });+ return visibleConversationItems(source, turnItems);+ },+);++/** History `thread` shows from its fork ancestors, oldest first. Side chats inherit no rows. */+export const readInheritedHandoffItems = Effect.fn(+ "orchestrationV2.contextHandoff.readInheritedHandoffItems",+)(function* (+ projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,+ thread: OrchestrationV2AppThread,+) {+ const segments: Array<ReadonlyArray<OrchestrationV2TurnItem>> = [];+ const seen = new Set([thread.id]);+ let current = thread;+ while (+ current.forkedFrom?.type === "run" &&+ current.lineage.sideChat !== true &&+ !seen.has(current.forkedFrom.threadId)+ ) {+ const { threadId, runId } = current.forkedFrom;+ seen.add(threadId);+ const source = yield* projectionStore+ .getThreadRecords(threadId, ["runs", "attempts"])+ .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }));+ const forkRun = source?.runs.find((run) => run.id === runId);+ if (source === null || forkRun === undefined) break;+ segments.unshift(yield* readOwnHistoryItems(projectionStore, source, forkRun));+ current = source.thread;+ }+ return segments.flat();+});++/** What a portable fork from `throughRun` of `source` carries: inherited rows, then its own. */+export const readForkHistoryItems = Effect.fn(+ "orchestrationV2.contextHandoff.readForkHistoryItems",+)(function* (+ projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,+ source: ForkHistorySource,+ throughRun: Pick<OrchestrationV2Run, "ordinal">,+) {+ return [+ ...(yield* readInheritedHandoffItems(projectionStore, source.thread)),+ ...(yield* readOwnHistoryItems(projectionStore, source, throughRun)),+ ];+});++export function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {switch (item.type) {case "user_message":return `- User: ${compactText(item.text)}`;@@ -135,6 +242,41 @@ function makeForkDeltaSummary(input: {].join("\n");}+const SIDE_CHAT_CONTEXT_MAX_CHARS = 8_000;++/** `digest` holds `summarizeDeltaItem` lines for parent items after the fork point, oldest first. */+export function makeSideChatContext(input: {+ readonly parentThreadId: ThreadId;+ readonly digest: ReadonlyArray<string>;+}): string {+ const framing =+ "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.";+ const header = "Main thread activity since this side chat's starting point:";+ const truncated = "- Earlier items truncated.";+ const footer = `Use t3_thread_read on thread ${input.parentThreadId} to see the main thread's live state.`;+ const kept: Array<string> = [];+ // The cap covers the whole block, so the fixed lines are reserved before any digest line.+ let remaining =+ SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length;+ for (const line of input.digest.toReversed()) {+ if (line.length + 1 > remaining) break;+ kept.unshift(line);+ remaining -= line.length + 1;+ }+ return [+ framing,+ ...(kept.length === 0+ ? []+ : ["", header, ...(kept.length < input.digest.length ? [truncated] : []), ...kept]),+ "",+ footer,+ ].join("\n");+}++/** Side chat context is prepended to the provider prompt, never replayed as budgeted history. */+export const isSideChatContextHandoff = (handoff: OrchestrationV2ContextHandoff): boolean =>+ handoff.strategy === "manual_context" && handoff.transferId != null;+function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>): string {const sections = items.flatMap((item) => {switch (item.type) {@@ -412,10 +554,56 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi} satisfies OrchestrationV2ContextHandoff;});+ const prepareSideChatContext = Effect.fn(+ "orchestrationV2.contextHandoff.prepareSideChatContext",+ )(function* (input: Parameters<ContextHandoffServiceV2Shape["prepareSideChatContext"]>[0]) {+ const handoffId = yield* idAllocator.allocate+ .contextHandoff({+ threadId: input.threadId,+ fromProviderInstanceId: input.fromProviderInstanceId,+ toProviderInstanceId: input.toProviderInstanceId,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ContextHandoffPrepareError({+ threadId: input.threadId,+ targetRunId: input.targetRunId,+ fromProviderThreadIds: [],+ toProviderThreadId: input.toProviderThreadId,+ cause,+ }),+ ),+ );+ return {+ id: handoffId,+ transferId: input.transferId,+ threadId: input.threadId,+ targetRunId: input.targetRunId,+ fromProviderThreadIds: [],+ toProviderThreadId: input.toProviderThreadId,+ coveredRunOrdinals: input.coveredRunOrdinals,+ strategy: "manual_context",+ status: "ready",+ summaryMessageId: null,+ summaryText: makeSideChatContext({+ parentThreadId: input.parentThreadId,+ digest: input.parentItems.flatMap((item) => {+ const line = summarizeDeltaItem(item);+ return line === null ? [] : [line];+ }),+ }),+ createdByProviderInstanceId: null,+ createdAt: input.createdAt,+ updatedAt: input.createdAt,+ } satisfies OrchestrationV2ContextHandoff;+ });+return ContextHandoffServiceV2.of({prepareLegacyImport,prepareForkDelta,prepareProviderHandoff,+ prepareSideChatContext,});},);diff --git a/apps/server/src/orchestration-v2/IdleCompaction.test.ts b/apps/server/src/orchestration-v2/IdleCompaction.test.tsindex bfa36cd2e51..65360492bd2 100644--- a/apps/server/src/orchestration-v2/IdleCompaction.test.ts+++ b/apps/server/src/orchestration-v2/IdleCompaction.test.ts@@ -148,7 +148,7 @@ function records(}describe("idleCompactionWindow", () => {- it("skips small contexts, unknown expiry, other providers, switched threads, and compactions", () => {+ it("skips small contexts, unknown expiry, other providers, switched threads, compactions, and side chats", () => {const cache = { cacheExpiresInMs: 60 * MINUTE_MS };expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();@@ -166,6 +166,13 @@ describe("idleCompactionWindow", () => {const archived = records(cache);archived.thread = { ...archived.thread, archivedAt: at() };expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();+ const sideChat = records(cache);+ expect(idleCompactionWindow(sideChat, NOW_MS)).not.toBeNull();+ sideChat.thread = {+ ...sideChat.thread,+ lineage: { ...sideChat.thread.lineage, relationshipToParent: "fork", sideChat: true },+ };+ expect(idleCompactionWindow(sideChat, NOW_MS)).toBeNull();});});diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.tsindex b142dd4efb1..a89894045c2 100644--- a/apps/server/src/orchestration-v2/IdleCompaction.ts+++ b/apps/server/src/orchestration-v2/IdleCompaction.ts@@ -1,4 +1,4 @@-import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";+import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction";import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import * as DateTime from "effect/DateTime";@@ -50,7 +50,7 @@ export function idleCompactionWindow(if (thread.settledAt !== null || thread.settledOverride === "settled") return null;if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)return null;- if (thread.lineage.relationshipToParent === "subagent") return null;+ if (!isListedThreadLineage(thread.lineage)) return null;const latestRun = runs.reduce<(typeof runs)[number] | null>((latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),null,diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 6c1ff428400..0a5e56d98d6 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -59,6 +59,7 @@ import {latestProviderTurnForAttempt,parseGoalCommand,orchestrationV2RunWorkStartedAt,+ orchestrationV2WorktreePending,ProviderInstanceId,ProviderInteractionMode,resolveProviderInstanceEnabled,@@ -99,11 +100,18 @@ import { CheckpointServiceV2 } from "./CheckpointService.ts";import {CommandPolicyV2,goalCommandStopsActiveRun,+ isActiveRun,isNativeMaintenanceCommand,resolveMessageDispatchIntent,} from "./CommandPolicy.ts";import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";-import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";+import {+ ContextHandoffServiceV2,+ readForkHistoryItems,+ readInheritedHandoffItems,+ visibleConversationItems,+ visibleDeltaRunOrdinals,+} from "./ContextHandoffService.ts";import { notificationTurnItem } from "@t3tools/provider-core/server/notification";import {cancelledBeforeStart,@@ -637,15 +645,6 @@ function mayStartSubagentFollowup(return command.createdBy === "user" || command.creationSource === "mcp";}-function isBlockingRun(run: OrchestrationV2Run): boolean {- return (- run.status === "preparing" ||- run.status === "starting" ||- run.status === "running" ||- run.status === "waiting"- );-}-/** Waiting runs only drain post-terminal output; their agent turn is over and still needs a wake. */function isLiveRun(run: OrchestrationV2Run): boolean {return run.status === "preparing" || run.status === "starting" || run.status === "running";@@ -919,26 +918,6 @@ function latestContextTransfer(}, undefined);}-function visibleDeltaRunOrdinals(- projection: Pick<OrchestrationV2ThreadProjection, "runs">,- items: ReadonlyArray<OrchestrationV2TurnItem>,-): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {- const ordinals = items.flatMap((item) => {- if (item.runId === null) {- return [];- }- const run = projection.runs.find((candidate) => candidate.id === item.runId);- return run === undefined ? [] : [run.ordinal];- });- if (ordinals.length === 0) {- return { from: 1, to: 1 };- }- return {- from: Math.min(...ordinals),- to: Math.max(...ordinals),- };-}-export function shouldPrepareLegacyImportHandoff(input: {readonly hasCompletedRun: boolean;readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];@@ -1199,6 +1178,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioEffect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),);+ const readInheritedItems = (thread: OrchestrationV2AppThread) =>+ readInheritedHandoffItems(projectionStore, thread).pipe(+ Effect.mapError((cause) => new OrchestratorProjectionError({ threadId: thread.id, cause })),+ );++ /** Includes tombstones, which still reserve their id. */+ const findThread = (threadId: ThreadId) =>+ projectionStore.getThread(threadId).pipe(+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),+ Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),+ );++ /** Side chats live inside their parent, so deleting the parent deletes them too. */+ const liveSideChatIds = Effect.fn("Orchestrator.liveSideChatIds")(+ function* (threadId: ThreadId) {+ const { contextTransfers } = yield* projectionStore+ .getThreadRecords(threadId, ["contextTransfers"])+ .pipe(+ Effect.catchTags({+ ProjectionStoreThreadNotFoundError: () => Effect.succeed({ contextTransfers: [] }),+ }),+ );+ const sideChatIds: Array<ThreadId> = [];+ for (const transfer of contextTransfers) {+ if (transfer.type !== "fork" || transfer.sourceThreadId !== threadId) continue;+ const child = yield* projectionStore+ .getThread(transfer.targetThreadId)+ .pipe(+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),+ );+ if (child?.lineage.sideChat === true && child.deletedAt === null) {+ sideChatIds.push(child.id);+ }+ }+ return sideChatIds;+ },+ (effect, threadId) =>+ effect.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),+ );+const getProjectionWithPendingEvents =/* This helper runs for individual orchestration events; the enclosing operation owns the span. */Effect.fnUntraced(function* (@@ -1527,7 +1546,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (projection.thread.archivedAt !== null ||projection.thread.deletedAt !== null ||- projection.runs.some(isBlockingRun)+ projection.runs.some(isActiveRun)) {return;}@@ -4246,26 +4265,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio}),),);- // The source is unlocked; validate the modes copied here, not an earlier read.+ // Only side chat forks lock the source; validate the modes copied here, not an earlier read.yield* refuseAboveDispatchModeLimit(command, command.sourceThreadId, sourceProjection.thread);+ if (command.sideChat === true && sourceProjection.thread.deletedAt !== null) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Thread ${command.sourceThreadId} was deleted.`,+ });+ }+ // The fork would copy no worktree path and run in the project checkout.+ if (+ command.sideChat === true &&+ orchestrationV2WorktreePending(sourceProjection.thread.worktreePath, sourceProjection.runs)+ ) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Thread ${command.sourceThreadId} has no worktree yet. Start the side chat once its worktree is set up.`,+ });+ }+ if ((yield* findThread(command.targetThreadId)) !== null) {+ return yield* new OrchestratorThreadAlreadyExistsError({+ commandId: command.commandId,+ threadId: command.targetThreadId,+ });+ }const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);- if (sourceRun === null) {+ // A side chat may open during the parent's first turn; it starts from a digest instead.+ if (+ sourceRun === null &&+ !(command.sideChat === true && command.sourcePoint.type === "latest_stable")+ ) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,cause: `No stable source run was found for fork source ${command.sourcePoint.type}.`,});}- if (!isForkableSourceRunStatus(sourceRun.status)) {+ if (sourceRun !== null && !isForkableSourceRunStatus(sourceRun.status)) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,cause: forkableSourceRunStatusError(sourceRun),});}- const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun);+ const sourceProviderThread =+ sourceRun === null ? undefined : providerThreadForRun(sourceProjection, sourceRun);const now = command.createdAt ?? (yield* DateTime.now);const emitEvent = emit(events, command);const transferId = yield* mapDispatchError(command)(@@ -4280,11 +4328,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiosourceProjection,sourceRun,sourceProviderThread,- sourceTokenUsage: providerTurnForRun(sourceProjection, sourceRun)?.tokenUsage,- canonicalSourcePoint: contextSourcePointForRun(sourceProjection, sourceRun),+ sourceTokenUsage:+ sourceRun === null+ ? undefined+ : providerTurnForRun(sourceProjection, sourceRun)?.tokenUsage,+ canonicalSourcePoint:+ sourceRun === null+ ? { threadId: sourceProjection.thread.id }+ : contextSourcePointForRun(sourceProjection, sourceRun),transferId,targetThreadId: command.targetThreadId,...(command.title === undefined ? {} : { title: command.title }),+ ...(command.sideChat ? { sideChat: true } : {}),createdBy: command.createdBy,creationSource: command.creationSource,createdAt: now,@@ -4301,7 +4356,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioyield* emitEvent({type: "context-transfer.created",threadId: command.targetThreadId,- providerInstanceId: sourceRun.providerInstanceId,+ providerInstanceId: transfer.sourceProviderInstanceId ?? targetThread.providerInstanceId,occurredAt: now,payload: transfer,});@@ -4361,6 +4416,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`,});}+ // Queued runs cannot consume merge-back context. Refuse under the target's+ // command lock before a pending transfer can block its ordinary messages.+ if (targetProjection.runs.some((run) => isActiveRun(run) || run.status === "queued")) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause:+ "Finish or stop the target thread's active work and clear its queue before merging back.",+ });+ }+ const otherPendingMergeBack = targetProjection.contextTransfers.some(+ (transfer) =>+ transfer.type === "merge_back" &&+ transfer.status === "pending" &&+ transfer.targetThreadId === command.targetThreadId &&+ transfer.sourceThreadId !== command.sourceThreadId,+ );+ if (otherPendingMergeBack) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Thread ${command.targetThreadId} already has pending context from another side chat or fork. Send a message there first.`,+ });+ }const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint);if (sourceRun === null) {@@ -4392,17 +4471,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio});}- // Queued runs cannot consume merge-back context. Refuse under the target's- // command lock before a pending transfer can block its ordinary messages.- if (targetProjection.runs.some((run) => isBlockingRun(run) || run.status === "queued")) {- return yield* new OrchestratorDispatchError({- commandId: command.commandId,- commandType: command.type,- cause:- "Finish or stop the target thread's active work and clear its queue before merging back.",- });- }-const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun);const now = command.createdAt ?? (yield* DateTime.now);const emitEvent = emit(events, command);@@ -5652,7 +5720,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst activeProviderThread = projection.providerThreads.find((candidate) => candidate.id === projection.thread.activeProviderThreadId,);- const activeRun = projection.runs.find(isBlockingRun);+ const activeRun = projection.runs.find(isActiveRun);// A message queued during worktree setup can arrive after that setup failed// without a worktree. It waits, held, like the messages queued before the// failure, instead of starting in the project checkout.@@ -6432,8 +6500,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiosourceProjection.attempts.find((candidate) => candidate.id === sourceRun.activeAttemptId)?.providerTurnId ??undefined);+ const sideChatFork =+ pendingForkTransfer !== undefined && projection.thread.lineage.sideChat === true;+ // Opened during the parent's first turn: the digest is the whole context.+ const sideChatWithoutSource =+ sideChatFork && pendingForkTransfer.sourcePoint.runId === undefined;if (pendingForkTransfer !== undefined) {- if (sourceRun === null || sourceProviderThread === undefined) {+ if (!sideChatWithoutSource && (sourceRun === null || sourceProviderThread === undefined)) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,@@ -6498,6 +6571,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio}),),);+ const sourceRunsAfterFork =+ sourceProjection === null+ ? []+ : sourceProjection.runs.filter(+ (candidate) => sourceRun === null || candidate.ordinal > sourceRun.ordinal,+ );const forkExecution =pendingForkTransfer === undefined || sourceRun === null? null@@ -6512,6 +6591,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiohasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",sourceRunStatus: sourceRun.status,fromSpecificTurn: sourceRun !== null,+ sourceBusy: sourceRunsAfterFork.some(isActiveRun),}),);const canResolveForkNatively = forkExecution === "native_fork";@@ -6568,12 +6648,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst portableForkItems =!requiresPortableFork || sourceProjection === null || sourceRun === null? []- : yield* readHandoffItems(sourceProjection.thread.id, [- ...sourceProjection.runs- .filter((run) => run.ordinal <= sourceRun.ordinal)- .map((run) => run.id),- ...(sourceProjection.thread.historyOrigin === "v1_import" ? [null] : []),- ]);+ : yield* readForkHistoryItems(projectionStore, sourceProjection, sourceRun).pipe(+ Effect.mapError(+ (cause) =>+ new OrchestratorProjectionError({ threadId: sourceProjection.thread.id, cause }),+ ),+ );const portableForkHandoff =!requiresPortableFork ||pendingForkTransfer === undefined ||@@ -6606,6 +6686,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio}),),);+ // Without a source run the digest covers the parent's whole history: inherited fork rows+ // first, so the cap truncates them first, then imported and run items.+ const sideChatParentRunIds = [+ // Queued messages have not reached the main thread yet.+ ...sourceRunsAfterFork.filter((run) => run.status !== "queued").map((run) => run.id),+ ...(sourceRun === null && sourceProjection?.thread.historyOrigin === "v1_import"+ ? [null]+ : []),+ ];+ const sideChatParentItems =+ !sideChatFork || sourceProjection === null+ ? []+ : [+ ...(sideChatWithoutSource ? yield* readInheritedItems(sourceProjection.thread) : []),+ ...(sideChatParentRunIds.length === 0+ ? []+ : visibleConversationItems(+ sourceProjection,+ yield* readHandoffItems(sourceProjection.thread.id, sideChatParentRunIds),+ )),+ ];+ // The framing note goes in even when the parent has no activity after the fork point.+ const sideChatContextHandoff =+ !sideChatFork || pendingForkTransfer === undefined || sourceProjection === null+ ? null+ : yield* contextHandoffService+ .prepareSideChatContext({+ threadId: command.threadId,+ parentThreadId: sourceProjection.thread.id,+ targetRunId: runId,+ transferId: pendingForkTransfer.id,+ toProviderThreadId: ensuredProviderThread.id,+ fromProviderInstanceId:+ pendingForkTransfer.sourceProviderInstanceId ?? modelSelection.instanceId,+ toProviderInstanceId: modelSelection.instanceId,+ coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, sideChatParentItems),+ parentItems: sideChatParentItems,+ createdAt: now,+ })+ .pipe(mapDispatchError(command));const requiresFullProviderSwitchContext =isProviderSwitch && pendingMergeBackTransfer !== undefined;const targetLastCompletedRun =@@ -6722,9 +6842,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiolastRunOrdinal: ordinal,handoffIds: [...ensuredProviderThread.handoffIds,- ...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(- (handoff) => (handoff === null ? [] : [handoff.id]),- ),+ ...[+ portableForkHandoff,+ sideChatContextHandoff,+ providerSwitchHandoff,+ legacyImportRecoveryHandoff,+ ].flatMap((handoff) => (handoff === null ? [] : [handoff.id])),],updatedAt: now,};@@ -6790,11 +6913,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst mergeBackDeltaItems =mergeBackSourceProjection === null || mergeBackSourceRun === null? []- : yield* readHandoffItems(- mergeBackSourceProjection.thread.id,- mergeBackSourceProjection.runs- .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)- .map((run) => run.id),+ : visibleConversationItems(+ mergeBackSourceProjection,+ yield* readHandoffItems(+ mergeBackSourceProjection.thread.id,+ mergeBackSourceProjection.runs+ .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)+ .map((run) => run.id),+ ),);const mergeBackHandoff =pendingMergeBackTransfer === undefined ||@@ -7027,12 +7153,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiostrategy: "native_fork",providerThreadRef: providerThread.nativeThreadRef,};+ const portableForkContext =+ portableForkHandoff ?? (sideChatWithoutSource ? sideChatContextHandoff : null);const portableForkResolution: OrchestrationV2ContextTransferResolution | null =- pendingForkTransfer === undefined || portableForkHandoff === null+ pendingForkTransfer === undefined || portableForkContext === null? null: {strategy: "portable_context",- contextHandoffId: portableForkHandoff.id,+ contextHandoffId: portableForkContext.id,};const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =pendingMergeBackTransfer === undefined || mergeBackHandoff === null@@ -7095,6 +7223,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiopayload: portableForkHandoff,});}+ if (sideChatContextHandoff !== null) {+ yield* emitEvent({+ type: "context-handoff.updated",+ threadId: command.threadId,+ runId,+ providerInstanceId: modelSelection.instanceId,+ occurredAt: now,+ payload: sideChatContextHandoff,+ });+ }if (legacyImportRecoveryHandoff !== null) {yield* emitEvent({type: "context-handoff.updated",@@ -7354,7 +7492,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst parentRun = parentProjection.runs.find((candidate) => candidate.id === command.parentRunId,);- if (parentRun === undefined || !isBlockingRun(parentRun)) {+ if (parentRun === undefined || !isActiveRun(parentRun)) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,@@ -7658,7 +7796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio);if (original === undefined || original.result === null) return;const owner =- parent.runs.filter(isBlockingRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??+ parent.runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??latestExecutedRun(parent.runs);if (owner === null || owner.rootNodeId === null) return;const now = message.createdAt;@@ -7785,7 +7923,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst parentRun = parentProjection.runs.find((candidate) => candidate.id === command.parentRunId,);- if (parentRun === undefined || !isBlockingRun(parentRun) || parentRun.rootNodeId === null) {+ if (parentRun === undefined || !isActiveRun(parentRun) || parentRun.rootNodeId === null) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,@@ -8507,7 +8645,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio}if (existing === undefined &&- (!isBlockingRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))+ (!isActiveRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))) {return yield* new OrchestratorDispatchError({commandId: command.commandId,@@ -9916,7 +10054,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocause: `Run ${command.runId} has no failed workspace preparation to retry.`,});}- if (projection.runs.some((run) => run.id !== state.run.id && isBlockingRun(run))) {+ if (projection.runs.some((run) => run.id !== state.run.id && isActiveRun(run))) {return yield* new OrchestratorDispatchError({commandId: command.commandId,commandType: command.type,@@ -11416,7 +11554,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocontinue;const idle =idleChildren.get(task.childThreadId) ??- (!child.runs.some((run) => run.status === "queued" || isBlockingRun(run)) &&+ (!child.runs.some((run) => run.status === "queued" || isActiveRun(run)) &&!child.providerThreads.some((thread) =>thread.status === "active" || (thread.pendingBackgroundTasks?.length ?? 0) > 0,@@ -12689,6 +12827,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst dispatchOnce = Effect.fn("orchestrationV2.dispatch.once")(function* (command: OrchestrationV2ServerCommand,+ sideChatIds: ReadonlyArray<ThreadId>,): Effect.fn.Return<{readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;@@ -12755,31 +12894,64 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiobreak;}case "thread.delete": {- const projection = yield* projectionStore- .getThreadRecords(command.threadId, [- "runs",- "attempts",- "nodes",- "runtimeRequests",- "subagents",- "providerSessions",- ])- .pipe(- Effect.mapError(- (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),- ),+ const now = yield* DateTime.now;+ const planDeletion = Effect.fn("Orchestrator.planDeletion")(function* (+ deletion: typeof command,+ ) {+ const projection = yield* projectionStore+ .getThreadRecords(deletion.threadId, [+ "runs",+ "attempts",+ "nodes",+ "runtimeRequests",+ "subagents",+ "providerSessions",+ ])+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: deletion.threadId, cause }),+ ),+ );+ return yield* mapDispatchError(command)(+ planThreadDeletion({+ command: deletion,+ projection,+ attachmentIds: yield* projectionStore+ .getThreadAttachmentIds(deletion.threadId)+ .pipe(mapDispatchError(command)),+ now,+ idAllocator,+ }),);- return yield* mapDispatchError(command)(- planThreadDeletion({- command,- projection,- attachmentIds: yield* projectionStore- .getThreadAttachmentIds(command.threadId)- .pipe(mapDispatchError(command)),- now: yield* DateTime.now,- idAllocator,- }),- );+ });+ // Checked under the thread lock: a message sent since the client looked keeps the thread.+ if (command.onlyIfUnused === true) {+ const usage = yield* projectionStore+ .getThreadRecords(command.threadId, ["runs", "messages"])+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),+ ),+ );+ if (usage.runs.length > 0 || usage.messages.length > 0) {+ return { events: [], effects: [] };+ }+ }+ // The dispatch wrapper holds each side chat's lock, so none can commit after this plan.+ const plans = [+ yield* planDeletion(command),+ ...(yield* Effect.forEach(sideChatIds, (threadId) =>+ planDeletion({+ ...command,+ commandId: CommandId.make(`${command.commandId}:side-chat:${threadId}`),+ threadId,+ }),+ )),+ ];+ return {+ events: plans.flatMap((plan) => plan.events),+ effects: plans.flatMap((plan) => plan.effects),+ };}case "thread.archive":case "thread.unarchive":@@ -12943,7 +13115,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioselectedMessage === undefined ||selectedMessage.delegatedCompletion !== undefined ||selectedMessage.notification !== undefined ||- projection.runs.some(isBlockingRun)+ projection.runs.some(isActiveRun)) {return yield* new OrchestratorDispatchError({commandId: command.commandId,@@ -13067,8 +13239,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio};});+ /** `sideChatIds` are the live side chats a `thread.delete` cascades to, read under their locks. */const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* (command: OrchestrationV2ServerCommand,+ sideChatIds: ReadonlyArray<ThreadId> = [],): Effect.fn.Return<OrchestratorV2DispatchResult, OrchestratorV2Error> {yield* Effect.annotateCurrentSpan({"orchestration_v2.command_id": command.commandId,@@ -13144,7 +13318,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (shell !== null) yield* refuseAboveDispatchModeLimit(command, threadId, shell);}- const plan = yield* dispatchOnce(command).pipe(+ const plan = yield* dispatchOnce(command, sideChatIds).pipe(Effect.filterOrFail((planned) =>planned.events.length > 0 ||@@ -13153,7 +13327,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocommand.type === "thread.stop" ||command.type === "subagent.stop" ||// Closing a share again, or after it ended, is not an error.- command.type === "thread.guest-share.close",+ command.type === "thread.guest-share.close" ||+ (command.type === "thread.delete" && command.onlyIfUnused === true),(_planned) =>new OrchestratorDispatchError({commandId: command.commandId,@@ -13295,6 +13470,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocommandThreadId(command),dispatchWithReceiptEffect(command),);+ // A parent's lock comes before its side chats' locks, so a delete cascade and a side chat+ // fork or command never interleave. A fork from a side chat or onto an existing thread would+ // invert that order; dispatch rejects both, so they skip the source lock.+ if (+ command.type === "thread.fork" &&+ command.sideChat === true &&+ command.sourceThreadId !== command.targetThreadId+ ) {+ const source = yield* findThread(command.sourceThreadId);+ const target = yield* findThread(command.targetThreadId);+ return yield* source === null || source.lineage.sideChat === true || target !== null+ ? dispatch+ : threadDispatch.withLock(command.sourceThreadId, dispatch);+ }+ if (command.type === "thread.delete")+ return yield* threadDispatch.withLock(+ command.threadId,+ liveSideChatIds(command.threadId).pipe(+ Effect.flatMap((sideChatIds) =>+ sideChatIds.reduce(+ (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked),+ dispatchWithReceiptEffect(command, sideChatIds),+ ),+ ),+ ),+ );// Answering a message-mode question can also start a follow-up.if (command.type !== "runtime-request.respond" &&diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex cfe57ab2c0c..a29d698d76d 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -5086,13 +5086,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {}),);- it.effect("counts imported runless history inherited by fork shells", () =>+ it.effect("counts history inherited by fork shells, but not by side chats", () =>Effect.gen(function* () {const projectionStore = yield* ProjectionStore.ProjectionStoreV2;const now = yield* DateTime.now;const projectId = ProjectId.make("project:projection-imported-fork-shell");const sourceThreadId = ThreadId.make("thread:projection-imported-fork-shell:source");const targetThreadId = ThreadId.make("thread:projection-imported-fork-shell:target");+ const sideChatThreadId = ThreadId.make("thread:projection-imported-fork-shell:side-chat");const sourceRunId = RunId.make("run:projection-imported-fork-shell:source");const rootNodeId = NodeId.make("node:projection-imported-fork-shell:source");@@ -5130,43 +5131,49 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {deletedAt: null,},});- yield* projectionStore.apply({- id: EventId.make("event:projection-imported-fork-shell:target-thread"),- type: "thread.created",- threadId: targetThreadId,- occurredAt: now,- payload: {- createdBy: "user",- creationSource: "web",- id: targetThreadId,- projectId,- title: "Imported fork target",- providerInstanceId,- modelSelection,- runtimeMode: "full-access",- interactionMode: "default",- branch: null,- worktreePath: null,- activeProviderThreadId: null,- lineage: {- parentThreadId: sourceThreadId,- relationshipToParent: "fork",- rootThreadId: sourceThreadId,- },- forkedFrom: {- type: "run",- threadId: sourceThreadId,- runId: sourceRunId,+ for (const [threadId, sideChat] of [+ [targetThreadId, false],+ [sideChatThreadId, true],+ ] as const) {+ yield* projectionStore.apply({+ id: EventId.make(`event:projection-imported-fork-shell:created:${threadId}`),+ type: "thread.created",+ threadId,+ occurredAt: now,+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId,+ title: "Imported fork target",+ providerInstanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: {+ parentThreadId: sourceThreadId,+ relationshipToParent: "fork",+ rootThreadId: sourceThreadId,+ sideChat,+ },+ forkedFrom: {+ type: "run",+ threadId: sourceThreadId,+ runId: sourceRunId,+ },+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,},- createdAt: now,- updatedAt: now,- archivedAt: null,- settledOverride: null,- settledAt: null,- lastVisitedAt: null,- deletedAt: null,- },- });+ });+ }yield* projectionStore.apply({id: EventId.make("event:projection-imported-fork-shell:source-run"),type: "run.created",@@ -5235,6 +5242,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {assert.equal(targetShell.itemCount, 0);assert.equal(targetShell.visibleItemCount, 4);assert.equal(targetProjection.visibleTurnItems.length, 4);++ const sideChatShell = shell.threads.find((thread) => thread.id === sideChatThreadId);+ assert.equal(sideChatShell?.visibleItemCount, 0);+ const sideChatProjection = yield* projectionStore.getThreadProjection(sideChatThreadId);+ assert.deepEqual(sideChatProjection.visibleTurnItems, []);+ const sideChatTimeline = yield* projectionStore.getTimelinePage(sideChatThreadId, {+ limit: 20,+ view: "activity",+ });+ assert.equal(sideChatTimeline.totalItems, 0);}),);diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 84c650f75fe..2e88fdc1190 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -256,6 +256,8 @@ export interface ProjectionCheckpointCaptureContext {readonly scope: OrchestrationV2CheckpointScope | undefined;readonly providerThread: OrchestrationV2ProviderThread | undefined;readonly readyCheckpointOrdinals: ReadonlyArray<number>;+ /** Side chats share their parent's worktree and never snapshot it. */+ readonly sideChat: boolean;}const RollbackTargetAttempts = Schema.Array(@@ -1335,14 +1337,21 @@ function visibleTurnItemsThroughRun(input: {return [...inheritedPrefix, ...localPrefix];}+// Side chats show only their own rows; the fork transfer carries the parent's context to the model.+function inheritedRunFork(thread: Pick<OrchestrationV2AppThread, "forkedFrom" | "lineage">) {+ return thread.forkedFrom?.type === "run" && thread.lineage.sideChat !== true+ ? thread.forkedFrom+ : null;+}+function buildVisibleTurnItems(input: {readonly projection: OrchestrationV2ThreadProjection;readonly sourceProjection: OrchestrationV2ThreadProjection | null;readonly inheritedRowCount?: number;}): Array<OrchestrationV2ProjectedTurnItem> {- const forkedFrom = input.projection.thread.forkedFrom;+ const forkedFrom = inheritedRunFork(input.projection.thread);if (- forkedFrom?.type !== "run" ||+ forkedFrom === null ||(input.sourceProjection === null && input.inheritedRowCount === undefined)) {return localVisibleTurnItems(input.projection);@@ -1721,8 +1730,8 @@ function visibleItemCountForShell(input: {return 0;}- const forkedFrom = state.thread.forkedFrom;- if (forkedFrom?.type !== "run") {+ const forkedFrom = inheritedRunFork(state.thread);+ if (forkedFrom === null) {return state.itemCount;}@@ -1736,9 +1745,8 @@ function visibleItemCountForShell(input: {return state.itemCount;}- const sourceForkedFrom = sourceState.thread.forkedFrom;const inheritedPrefixCount =- sourceForkedFrom?.type === "run"+ inheritedRunFork(sourceState.thread) !== null? visibleItemCountForShell({threadId: sourceState.thread.id,statesByThreadId: input.statesByThreadId,@@ -3628,8 +3636,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =? ["runs", "attempts", "turnItems"]: undefined,);- const forkedFrom = projection.thread.forkedFrom;- if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {+ const forkedFrom = inheritedRunFork(projection.thread);+ if (forkedFrom === null || seenThreadIds.has(forkedFrom.threadId)) {return withLocalVisibleTurnItems(projection);}@@ -4305,6 +4313,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =message_id IN (SELECT json_extract(payload_json, '$.userMessageId') FROM orchestration_v2_projection_runsWHERE thread_id = ${threadId} AND run_id = ${runId})OR (role = 'user' AND lower(trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace})) = '/compact')+ -- Earlier /goal turns defer context too; parseGoalCommand narrows this prefix match.+ OR (role = 'user' AND trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace}) GLOB '/goal*')) ORDER BY created_at ASC, message_id ASC`.pipe(Effect.flatMap(decodeRows(decodeMessagePayload, threadId)));const conversation = yield* sql<{ present: number }>`@@ -5064,7 +5074,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =sql.withTransaction(Effect.gen(function* () {- yield* requireThread(threadId);+ const threadRows = yield* sql<{ readonly side_chat: number | null }>`+ SELECT json_extract(payload_json, '$.lineage.sideChat') AS side_chat+ FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1`;+ if (threadRows[0] === undefined) {+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ }const runRows = yield* sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_runsWHERE thread_id = ${threadId} AND run_id = ${target.runId}`;@@ -5101,6 +5116,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =? undefined: yield* decodeProviderThreadPayload(providerRows[0].payload_json),readyCheckpointOrdinals: readyRows.map(({ ordinal }) => ordinal),+ sideChat: threadRows[0].side_chat === 1,};}),)@@ -5504,8 +5520,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =items,});const visible = local.filter((row) => isVisible(row.item));- const fork = records.thread.forkedFrom;- if (fork?.type !== "run" || seen.has(fork.threadId)) return { records, local, visible };+ const fork = inheritedRunFork(records.thread);+ if (fork === null || seen.has(fork.threadId)) return { records, local, visible };const source = yield* readTimelineIndex(fork.threadId,new Set([...seen, threadId]),@@ -5865,6 +5881,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =t.payload_json,CASEWHEN json_extract(t.payload_json, '$.forkedFrom.type') = 'run'+ AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1THEN json_extract(t.payload_json, '$.forkedFrom.threadId')ELSE NULLEND AS forked_from_run_source_thread_id,@@ -6749,6 +6766,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =readonly relationship_to_parent: string | null;readonly parent_thread_id: string | null;readonly root_thread_id: string;+ readonly side_chat: number | null;readonly settled_override: string | null;readonly settled_at: string | null;readonly pinned_at: string | null;@@ -6761,6 +6779,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =json_extract(t.payload_json, '$.lineage.relationshipToParent') AS relationship_to_parent,json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id,json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id,+ json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat,json_extract(t.payload_json, '$.settledOverride') AS settled_override,json_extract(t.payload_json, '$.settledAt') AS settled_at,json_extract(t.payload_json, '$.pinnedAt') AS pinned_at,@@ -6815,6 +6834,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =? row.relationship_to_parent: null,rootThreadId: ThreadId.make(row.root_thread_id),+ ...(row.side_chat === null ? {} : { sideChat: row.side_chat === 1 }),},settledOverride:row.settled_override === "settled" || row.settled_override === "active"@@ -6850,6 +6870,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =WHERE t.deleted_at IS NULLAND json_extract(t.payload_json, '$.archivedAt') IS NULLAND json_extract(t.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent'+ AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1AND json_extract(t.payload_json, '$.settledOverride') = 'settled'AND json_extract(t.payload_json, '$.settledAt') IS NOT NULL${projectIds === undefined ? sql`` : sql` AND t.project_id IN ${sql.in(projectIds)}`diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.tsindex d9287644be8..05fc1b8545b 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts@@ -3,6 +3,8 @@ import { expect, it, vi } from "vite-plus/test";import { it as effectIt } from "@effect/vitest";import {CheckpointScopeId,+ ContextHandoffId,+ ContextTransferId,GitCommandError,MessageId,NodeId,@@ -40,6 +42,7 @@ import * as ProjectService from "../project/ProjectService.ts";import * as ProviderAuthService from "../provider/ProviderAuthService.ts";import * as ServerSettings from "../serverSettings.ts";import * as ContextHandoffService from "./ContextHandoffService.ts";+import { withInlineContext } from "./ContextHandoffDelivery.ts";import * as EventSink from "./EventSink.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";@@ -96,6 +99,7 @@ function startWithMissingWorktree(projectId: ProjectId.make("project_provider_turn_start_projection_failure"),branch: "feature/restore",worktreePath,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },},runs: [{@@ -286,6 +290,16 @@ function makeLocalCommandHarness(input: {readonly interruptFailure?: boolean;readonly interruptCurrentRun?: boolean;};+ /**+ * A side chat whose context targets this run, an earlier run that failed or was cancelled before+ * the provider, or an earlier run that delivered it. `nativeForkFrom` plans a native fork of the+ * parent. `switchedProvider` puts the earlier run and its context on another provider thread.+ */+ readonly sideChat?: {+ readonly contextRun: "current" | "failed" | "cancelled" | "delivered";+ readonly nativeForkFrom?: "idle" | "busy";+ readonly switchedProvider?: boolean;+ };}) {const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");const threadId = ThreadId.make("thread-native-account-command");@@ -354,6 +368,7 @@ function makeLocalCommandHarness(input: {projectId: ProjectId.make("project-native-account-command"),branch: input.worktreePath === undefined ? null : "feature/restore",worktreePath: input.worktreePath ?? null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },} as OrchestrationV2ThreadProjection["thread"],runs: [...(input.previousNativeSession@@ -458,6 +473,139 @@ function makeLocalCommandHarness(input: {checkpoints: [],updatedAt: now,};+ const parentThreadId = ThreadId.make("side-chat-parent");+ const parentRunId = RunId.make("side-chat-parent-run");+ const parentProviderThread = {+ ...providerThread,+ id: ProviderThreadId.make("side-chat-parent-provider-thread"),+ appThreadId: parentThreadId,+ nativeThreadRef: {+ driver: providerThread.driver,+ nativeId: "side-chat-parent-native",+ strength: "strong" as const,+ },+ };+ const parentRecords = {+ ...projection,+ thread: { ...projection.thread, id: parentThreadId },+ runs: [+ {+ ...run,+ id: parentRunId,+ threadId: parentThreadId,+ ordinal: 1,+ providerThreadId: parentProviderThread.id,+ activeAttemptId: null,+ status: "completed" as const,+ completedAt: now,+ },+ ...(input.sideChat?.nativeForkFrom === "busy"+ ? [+ {+ ...run,+ id: RunId.make("side-chat-parent-busy-run"),+ threadId: parentThreadId,+ ordinal: 2,+ providerThreadId: parentProviderThread.id,+ status: "running" as const,+ },+ ]+ : []),+ ],+ providerThreads: [parentProviderThread],+ attempts: [],+ providerTurns: [],+ turnItems: [],+ };+ if (input.sideChat !== undefined) {+ const earlierRunId = RunId.make("side-chat-earlier-run");+ projection = {+ ...projection,+ thread: {+ ...projection.thread,+ runtimeMode: "full-access",+ lineage: {+ parentThreadId,+ relationshipToParent: "fork",+ rootThreadId: parentThreadId,+ sideChat: true,+ },+ },+ runs:+ input.sideChat.contextRun === "current"+ ? projection.runs+ : [+ {+ ...run,+ id: earlierRunId,+ ordinal: 1,+ userMessageId: MessageId.make("side-chat-earlier-message"),+ activeAttemptId: RunAttemptId.make("side-chat-earlier-attempt"),+ ...(input.sideChat.switchedProvider+ ? { providerThreadId: oldProviderThreadId }+ : {}),+ status:+ input.sideChat.contextRun === "delivered"+ ? "completed"+ : input.sideChat.contextRun,+ completedAt: now,+ },+ run,+ ],+ contextTransfers:+ input.sideChat.nativeForkFrom === undefined+ ? []+ : [+ {+ id: ContextTransferId.make("side-chat-fork"),+ type: "fork",+ sourceThreadId: parentThreadId,+ targetThreadId: threadId,+ sourcePoint: { threadId: parentThreadId, runId: parentRunId },+ basePoint: null,+ sourceProviderInstanceId: newInstanceId,+ targetProviderInstanceId: newInstanceId,+ targetRunId: runId,+ status: "pending",+ resolution: null,+ createdBy: "user",+ error: null,+ createdAt: now,+ updatedAt: now,+ consumedAt: null,+ },+ ],+ contextHandoffs: [+ {+ id: ContextHandoffId.make("side-chat-context"),+ transferId: ContextTransferId.make("side-chat-fork"),+ threadId,+ targetRunId: input.sideChat.contextRun === "current" ? runId : earlierRunId,+ fromProviderThreadIds: [],+ toProviderThreadId: input.sideChat.switchedProvider+ ? oldProviderThreadId+ : providerThreadId,+ coveredRunOrdinals: { from: 1, to: 1 },+ strategy: "manual_context",+ status: "ready",+ summaryMessageId: null,+ summaryText: "SIDE_CHAT_CONTEXT",+ createdByProviderInstanceId: null,+ createdAt: now,+ updatedAt: now,+ ...(input.sideChat.contextRun === "delivered"+ ? {+ delivery: {+ nativeThreadId: "side-chat-native",+ status: "inline" as const,+ itemIds: [],+ },+ }+ : {}),+ },+ ],+ };+ }if ("historyReadFailureAfterFallback" in input) {const nativeThreadRef = {driver: providerThread.driver,@@ -577,55 +725,78 @@ function makeLocalCommandHarness(input: {),ensureThread: () => Effect.succeed(providerThread),};+ const providerSession = {+ id: providerSessionId,+ driver: providerThread.driver,+ providerInstanceId: newInstanceId,+ status: "ready",+ cwd: "/tmp/native-account-command",+ model: null,+ capabilities: CodexProviderCapabilitiesV2,+ createdAt: now,+ updatedAt: now,+ lastError: null,+ };+ const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void);+ const sideChatThread = {+ ...providerThread,+ nativeThreadRef: {+ driver: providerThread.driver,+ nativeId: "side-chat-native",+ strength: "strong" as const,+ },+ };+ const forkThread = vi.fn(() => Effect.succeed(sideChatThread));+ const sideChatSession = {+ driver: providerThread.driver,+ providerSession,+ ensureThread: () => Effect.succeed(sideChatThread),+ resumeThread: () => Effect.succeed(sideChatThread),+ forkThread,+ startTurn,+ };const open = vi.fn(() =>- input.interruptOpen === true- ? Effect.interrupt- : "historyReadFailureAfterFallback" in input- ? Effect.succeed(resumeFallbackSession as never)- : "ensureThreadFailure" in input- ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)- : "openFailure" in input- ? Effect.sync(() => {- if (input.interruptRunBeforeOpenFailure === true) interruptRun();- }).pipe(- Effect.andThen(- Effect.fail(- new ProviderSessionManager.ProviderSessionOpenError({- instanceId: newInstanceId,- providerSessionId,- cause: input.openFailure,- }),+ input.sideChat !== undefined+ ? Effect.succeed(sideChatSession as never)+ : input.interruptOpen === true+ ? Effect.interrupt+ : "historyReadFailureAfterFallback" in input+ ? Effect.succeed(resumeFallbackSession as never)+ : "ensureThreadFailure" in input+ ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)+ : "openFailure" in input+ ? Effect.sync(() => {+ if (input.interruptRunBeforeOpenFailure === true) interruptRun();+ }).pipe(+ Effect.andThen(+ Effect.fail(+ new ProviderSessionManager.ProviderSessionOpenError({+ instanceId: newInstanceId,+ providerSessionId,+ cause: input.openFailure,+ }),+ ),),- ),- )- : input.failReadsAfterRunning === true || input.previousTurn !== undefined- ? Effect.succeed({- driver: providerThread.driver,- providerSession: {- id: providerSessionId,+ )+ : input.failReadsAfterRunning === true || input.previousTurn !== undefined+ ? Effect.succeed({driver: providerThread.driver,- providerInstanceId: newInstanceId,- status: "ready",- cwd: "/tmp/native-account-command",- model: null,- capabilities: CodexProviderCapabilitiesV2,- createdAt: now,- updatedAt: now,- lastError: null,- },- ensureThread: () => Effect.succeed(providerThread),- resumeThread: () => Effect.succeed(projection.providerThreads[0]),- } as never)- : Effect.die("A local command must not open a native session."),+ providerSession,+ ensureThread: () => Effect.succeed(providerThread),+ resumeThread: () => Effect.succeed(projection.providerThreads[0]),+ } as never)+ : Effect.die("A local command must not open a native session."),);const startRootRun = vi.fn<(input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>- >(() =>- input.failReadsAfterRunning === true || input.previousTurn !== undefined- ? Effect.suspend(() =>- providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,- )- : Effect.die("A local command must not start a native turn."),+ >((runInput) =>+ input.sideChat !== undefined+ ? runInput.session.startTurn(runInput as never).pipe(Effect.orDie)+ : input.failReadsAfterRunning === true || input.previousTurn !== undefined+ ? Effect.suspend(() =>+ providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,+ )+ : Effect.die("A local command must not start a native turn."),);const failReadIfRunning = Effect.suspend(() =>input.failReadsAfterRunning === true &&@@ -672,13 +843,16 @@ function makeLocalCommandHarness(input: {);const resolveRuntimePolicy = vi.fn(({ thread }: Parameters<RuntimePolicy.RuntimePolicyV2Shape["resolve"]>[0]) =>- Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command" } as never),+ Effect.succeed({+ cwd: thread.worktreePath ?? "/tmp/native-account-command",+ runtimeMode: thread.runtimeMode,+ } as never),);const createWorktree = vi.fn<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>(() =>Effect.succeed({} as never),);- const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(() =>- Effect.succeed(projection),+ const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>((id) =>+ Effect.succeed(id === parentThreadId ? parentRecords : projection),);const getTurnStartContext = vi.fn(() =>Effect.succeed({@@ -694,9 +868,30 @@ function makeLocalCommandHarness(input: {Layer.provide(Layer.mergeAll(Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({- prepareProviderHandoff: () => Effect.die("history read must fail first"),+ prepareProviderHandoff: (handoff) =>+ input.sideChat?.nativeForkFrom === undefined+ ? Effect.die("history read must fail first")+ : Effect.succeed({+ ...handoff,+ id: ContextHandoffId.make("side-chat-fork-context"),+ createdByProviderInstanceId: handoff.toProviderInstanceId,+ status: "ready",+ summaryMessageId: null,+ summaryText: "PARENT_HISTORY",+ updatedAt: handoff.createdAt,+ }),+ }),+ Layer.mock(EventSink.EventSinkV2)({+ writeIfRunCurrent,+ write: ({ events: incoming }) =>+ Effect.sync(() => {+ for (const event of incoming) {+ events.push(event);+ projection = ProjectionStore.applyToProjection(projection, event);+ }+ return [];+ }),}),- Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),IdAllocator.layer,layerWorktreeLocation(input.worktreesDir),input.fileSystem === undefined@@ -728,12 +923,14 @@ function makeLocalCommandHarness(input: {),}),getTurnStartHistory: () =>- Effect.fail(- new ProjectionStore.ProjectionStoreReadError({- threadId,- cause: input.historyReadFailureAfterFallback,- }),- ),+ input.sideChat !== undefined+ ? Effect.succeed([])+ : Effect.fail(+ new ProjectionStore.ProjectionStoreReadError({+ threadId,+ cause: input.historyReadFailureAfterFallback,+ }),+ ),}),Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({open,@@ -767,6 +964,8 @@ function makeLocalCommandHarness(input: {open,writeIfRunCurrent,startRootRun,+ startTurn,+ forkThread,interruptTurn,tryHandlePromptCommand,events,@@ -1006,6 +1205,75 @@ effectIt.effect("recovers an abandoned failed turn before continuing its native}),);+effectIt.effect.each([+ { contextRun: "current", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },+ { contextRun: "failed", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },+ { contextRun: "cancelled", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT" },+ {+ contextRun: "failed",+ switchedProvider: true,+ runtimeMode: "approval-required",+ context: "SIDE_CHAT_CONTEXT",+ },+ { contextRun: "delivered", runtimeMode: "full-access", context: "" },+] as const)(+ "sends side chat context inline once, for the first turn that reaches the provider: %j",+ ({ runtimeMode, context, ...sideChat }) =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "What is the main thread doing?",+ sideChat,+ });++ yield* harness.start;++ // The turn that delivers the context is clamped; a later one follows the thread's mode.+ expect(harness.open).toHaveBeenCalledWith(+ expect.objectContaining({ runtimePolicy: expect.objectContaining({ runtimeMode }) }),+ );+ expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([+ withInlineContext(context, "What is the main thread doing?"),+ ]);+ expect(harness.projection().contextHandoffs).toMatchObject([+ {+ id: "side-chat-context",+ toProviderThreadId: "new-provider-thread",+ delivery: { nativeThreadId: "side-chat-native", status: "inline" },+ },+ ]);+ }),+);++effectIt.effect.each([+ { nativeForkFrom: "idle", forks: true, transferStatus: "consumed", handoffIds: [] },+ {+ nativeForkFrom: "busy",+ forks: false,+ transferStatus: "resolved_portable",+ handoffIds: ["side-chat-fork-context"],+ },+] as const)(+ "runs a planned native side chat fork when the parent is $nativeForkFrom",+ ({ nativeForkFrom, forks, transferStatus, handoffIds }) =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "What is the main thread doing?",+ sideChat: { contextRun: "current", nativeForkFrom },+ });++ yield* harness.start;++ expect(harness.forkThread).toHaveBeenCalledTimes(forks ? 1 : 0);+ expect(harness.projection().contextTransfers).toMatchObject([+ { id: "side-chat-fork", status: transferStatus },+ ]);+ expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("PARENT_HISTORY")).toBe(+ !forks,+ );+ expect(harness.projection().providerThreads[0]?.handoffIds).toEqual(handoffIds);+ }),+);+effectIt.effect.each([{ runStatus: "failed", turnStatus: "completed" },{ runStatus: "completed", turnStatus: "completed" },diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.tsindex 14c93a31ea0..402b2eaf3e0 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts@@ -34,6 +34,7 @@ import * as ServerSettings from "../serverSettings.ts";import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";import * as EventSink from "./EventSink.ts";import * as ContextHandoffService from "./ContextHandoffService.ts";+import { isActiveRun } from "./CommandPolicy.ts";import {DEFAULT_HANDOFF_TOKEN_CAP,handoffTokenCapConfig,@@ -43,7 +44,7 @@ import {historicalMessage,latestNativeContextUsage,} from "@t3tools/provider-core/server/handoffBudget";-import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";+import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProjectionStore from "./ProjectionStore.ts";@@ -363,27 +364,40 @@ export const layer: Layer.Layer<.filter((transfer) => transfer.type === "subagent_result").map((transfer) => transfer.id),);+ const isPendingForRun = (handoff: OrchestrationV2ContextHandoff, anyProviderThread = false) =>+ handoff.status === "ready" &&+ (handoff.targetRunId === run.id ||+ ((anyProviderThread || handoff.toProviderThreadId === run.providerThreadId) &&+ projection.runs.some(+ (source) =>+ source.id === handoff.targetRunId &&+ (source.status === "failed" ||+ source.status === "interrupted" ||+ source.status === "cancelled" ||+ (source.status === "completed" &&+ handoff.delivery === undefined &&+ // Compaction and /goal turns defer history to the next turn.+ projection.messages.some(+ (message) =>+ message.id === source.userMessageId &&+ (isCompactionCommandMessage(message) || parseGoalCommand(message) !== null),+ ))),+ )));+ const isSideChatHandoff = (handoff: OrchestrationV2ContextHandoff) =>+ projection.thread.lineage.sideChat === true &&+ ContextHandoffService.isSideChatContextHandoff(handoff);const handoffs = projection.contextHandoffs.filter((handoff) =>+ !isSideChatHandoff(handoff) &&(handoff.transferId == null || !subagentResultTransfers.has(handoff.transferId)) &&- handoff.status === "ready" &&- (handoff.targetRunId === run.id ||- (handoff.toProviderThreadId === run.providerThreadId &&- projection.runs.some(- (source) =>- source.id === handoff.targetRunId &&- (source.status === "failed" ||- source.status === "interrupted" ||- (source.status === "completed" &&- handoff.delivery === undefined &&- // Compaction and /goal turns defer history to the next turn.- projection.messages.some(- (message) =>- message.id === source.userMessageId &&- (isCompactionCommandMessage(message) ||- parseGoalCommand(message) !== null),- ))),- ))),+ isPendingForRun(handoff),+ );+ // Carried forward until a provider turn accepts it, also after a provider switch.+ const sideChatHandoff = projection.contextHandoffs.find(+ (handoff) =>+ isSideChatHandoff(handoff) &&+ handoff.delivery === undefined &&+ isPendingForRun(handoff, true),);const nativeForkTransfer = projection.contextTransfers.find((transfer) =>@@ -675,8 +689,14 @@ export const layer: Layer.Layer<});const { isCurrentAttemptInStatus } = runControls;+ // A side chat shares its parent's worktree; the turn that gets its context asks before acting.const resolvedRuntimePolicy = yield* runtimePolicy.resolve({- thread: projection.thread,+ thread:+ projection.thread.lineage.sideChat === true &&+ (sideChatHandoff !== undefined ||+ !projection.runs.some((previous) => previous.ordinal < run.ordinal))+ ? { ...projection.thread, runtimeMode: "approval-required" }+ : projection.thread,modelSelection: run.modelSelection,});if (!(yield* isCurrentAttemptInStatus("starting"))) return;@@ -1072,6 +1092,7 @@ export const layer: Layer.Layer<};let resumedRetryHandoff: ReadonlyArray<OrchestrationV2ContextHandoff> | undefined;let resumedHandoffContext: ReturnType<typeof handoffContextForThread> | undefined;+ let portableForkFallback: OrchestrationV2ContextHandoff | undefined;const loadedProviderThread = yield* Effect.gen(function* () {if (nativeForkTransfer !== undefined) {const sourceProjection = yield* projectionStore.getThreadRecords(@@ -1098,18 +1119,91 @@ export const layer: Layer.Layer<cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,});}- return yield* loadFromProvider(- session.forkThread({- sourceProviderThread,- sourceProviderTurns: sourceProjection.providerTurns,- targetThreadId: projection.thread.id,+ // Providers refuse to fork a busy thread, so a source that started a turn after+ // dispatch planned this fork gets the portable context dispatch gives a busy source.+ const sourceBusy = sourceProjection.runs.some(+ (candidate) => candidate.ordinal > sourceRun.ordinal && isActiveRun(candidate),+ );+ if (!sourceBusy) {+ return yield* loadFromProvider(+ session.forkThread({+ sourceProviderThread,+ sourceProviderTurns: sourceProjection.providerTurns,+ targetThreadId: projection.thread.id,+ modelSelection: run.modelSelection,+ runtimePolicy: resolvedRuntimePolicy,+ ...(sourceProviderTurn === undefined+ ? {}+ : { providerTurnId: sourceProviderTurn.id }),+ }),+ );+ }+ const sourceItems = yield* ContextHandoffService.readForkHistoryItems(+ projectionStore,+ sourceProjection,+ sourceRun,+ );+ const createdAt = yield* DateTime.now;+ const handoff = yield* contextHandoffService.prepareProviderHandoff({+ threadId: projection.thread.id,+ targetRunId: run.id,+ transferId: nativeForkTransfer.id,+ fromProviderThreadIds: [sourceProviderThread.id],+ toProviderThreadId: providerThread.id,+ fromProviderInstanceId: sourceRun.providerInstanceId,+ toProviderInstanceId: run.providerInstanceId,+ coveredRunOrdinals: ContextHandoffService.visibleDeltaRunOrdinals(+ sourceProjection,+ sourceItems,+ ),+ strategy: "full_thread_summary",+ items: sourceItems,+ runs: sourceProjection.runs,+ createdAt,+ });+ const loaded = yield* loadFromProvider(+ session.ensureThread({+ threadId: projection.thread.id,+ title: projection.thread.title,modelSelection: run.modelSelection,runtimePolicy: resolvedRuntimePolicy,- ...(sourceProviderTurn === undefined- ? {}- : { providerTurnId: sourceProviderTurn.id }),+ providerSessionId,+ existingProviderThread: { ...providerThread, forkedFrom: null },}),);+ if (loaded === undefined) return undefined;+ portableForkFallback = handoff;+ effectiveHandoffs = [handoff, ...effectiveHandoffs];+ yield* eventSink.write({+ events: [+ {+ id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),+ type: "context-handoff.updated",+ threadId: projection.thread.id,+ runId: run.id,+ providerInstanceId: run.providerInstanceId,+ occurredAt: createdAt,+ payload: handoff,+ },+ {+ id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),+ type: "context-transfer.updated",+ threadId: projection.thread.id,+ runId: run.id,+ providerInstanceId: run.providerInstanceId,+ occurredAt: createdAt,+ payload: {+ ...nativeForkTransfer,+ targetProviderInstanceId: run.providerInstanceId,+ status: "resolved_portable",+ resolution: { strategy: "portable_context", contextHandoffId: handoff.id },+ error: null,+ updatedAt: createdAt,+ },+ },+ ],+ });+ return loaded;}if (providerThread.nativeThreadRef === null) {// Pass the stored provider row for adoption; adapter-minted duplicates make activeProviderThreadId flap.@@ -1299,8 +1393,11 @@ export const layer: Layer.Layer<ownerNodeId: providerThread.ownerNodeId,firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,lastRunOrdinal: run.ordinal,- handoffIds: providerThread.handoffIds,- forkedFrom: providerThread.forkedFrom,+ handoffIds:+ portableForkFallback === undefined+ ? providerThread.handoffIds+ : [...providerThread.handoffIds, portableForkFallback.id],+ forkedFrom: portableForkFallback === undefined ? providerThread.forkedFrom : null,status: "active",createdAt: providerThread.createdAt,updatedAt: now,@@ -1345,7 +1442,9 @@ export const layer: Layer.Layer<occurredAt: now,payload: runningProviderThread,},- ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null+ ...(nativeForkTransfer === undefined ||+ portableForkFallback !== undefined ||+ runningProviderThread.nativeThreadRef === null? []: [{@@ -1415,6 +1514,26 @@ export const layer: Layer.Layer<const routableSubagents = projection.subagents.filter((subagent) =>RunExecutionService.canRouteRelatedSubagent(subagent.status),);+ const persistHandoff = Effect.fn("ProviderTurnStartService.persist")(function* (+ handoff: OrchestrationV2ContextHandoff,+ ) {+ const updatedAt = yield* DateTime.now;+ yield* eventSink.write({+ events: [+ {+ id: yield* idAllocator.allocate.event({+ threadId: projection.thread.id,+ }),+ type: "context-handoff.updated",+ threadId: projection.thread.id,+ runId: run.id,+ providerInstanceId: run.providerInstanceId,+ occurredAt: updatedAt,+ payload: { ...handoff, updatedAt },+ },+ ],+ });+ });const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")(function* (turnInput: Parameters<typeof session.startTurn>[0], compact = false) {const delivery = yield* deliverContextHandoffs({@@ -1432,28 +1551,16 @@ export const layer: Layer.Layer<...history,}),}),- persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) {- const updatedAt = yield* DateTime.now;- yield* eventSink.write({- events: [- {- id: yield* idAllocator.allocate.event({- threadId: projection.thread.id,- }),- type: "context-handoff.updated",- threadId: projection.thread.id,- runId: run.id,- providerInstanceId: run.providerInstanceId,- occurredAt: updatedAt,- payload: { ...handoff, updatedAt },- },- ],- });- }),+ persist: persistHandoff,});if (!(yield* isCurrentAttemptInStatus("running"))) return;const start = compact ? session.compactThread! : session.startTurn;- const context = [delivery.context, restartNote]+ // Like history, the side chat context waits for a turn that sends a prompt.+ const sideChatContext =+ sideChatHandoff === undefined || compact || goalCommand+ ? ""+ : sideChatHandoff.summaryText;+ const context = [delivery.context, sideChatContext, restartNote].filter((part) => part !== "").join("\n\n");const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput;@@ -1461,10 +1568,7 @@ export const layer: Layer.Layer<...(noteContinuation ? promptedInput : turnInput),message: {...turnInput.message,- text:- context === "" || goalCommand- ? userText- : `${context}\n\nUser message:\n${userText}`,+ text: goalCommand ? userText : withInlineContext(context, userText),},}).pipe(// Clear pending handoff markers for refused prompts so the next turn retains the native session.@@ -1481,13 +1585,30 @@ export const layer: Layer.Layer<),);// After provider acceptance, failed delivery bookkeeping must not stop live ingestion.- yield* delivery.delivered.pipe(- Effect.catchCause(() =>- Effect.logWarning("Failed to record accepted context handoff delivery", {- runId: run.id,- deliveryStatus: "pending",- }),- ),+ const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId;+ yield* Effect.forEach(+ [+ delivery.delivered,+ ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null+ ? []+ : [+ persistHandoff({+ ...sideChatHandoff,+ toProviderThreadId: runningProviderThread.id,+ delivery: { nativeThreadId, status: "inline" as const, itemIds: [] },+ }),+ ]),+ ],+ (record) =>+ record.pipe(+ Effect.catchCause(() =>+ Effect.logWarning("Failed to record accepted context handoff delivery", {+ runId: run.id,+ deliveryStatus: "pending",+ }),+ ),+ ),+ { discard: true },);},Effect.mapError((cause) =>@@ -1505,6 +1626,7 @@ export const layer: Layer.Layer<const deliverySession =effectiveHandoffs.length === 0 &&retryHandoff.length === 0 &&+ sideChatHandoff === undefined &&restartNote === "" &&!noteContinuation? sessiondiff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 22d5b8b879a..b9b2b09bd22 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -920,21 +920,24 @@ export const layer: Layer.Layer<.responseStreamingMode,),);- yield* checkpointService- .captureBaseline({- scope: input.checkpointScope,- ordinalWithinScope: Math.max(0, input.run.ordinal - 1),- })- .pipe(- Effect.catchCauseIf(- (cause) => !Cause.hasInterruptsOnly(cause),- (_cause) =>- Effect.logWarning(- "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",- { runId: input.run.id },- ),- ),- );+ // Side chats share the parent's worktree; a snapshot would capture the parent's edits.+ yield* (+ input.appThread.lineage.sideChat === true+ ? Effect.void+ : checkpointService.captureBaseline({+ scope: input.checkpointScope,+ ordinalWithinScope: Math.max(0, input.run.ordinal - 1),+ })+ ).pipe(+ Effect.catchCauseIf(+ (cause) => !Cause.hasInterruptsOnly(cause),+ (_cause) =>+ Effect.logWarning(+ "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",+ { runId: input.run.id },+ ),+ ),+ );if (input.shouldStartProviderTurn !== undefined &&!(yield* input.shouldStartProviderTurn())diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.tsindex e308c74a00f..336f9b12f96 100644--- a/apps/server/src/orchestration-v2/ShellStream.test.ts+++ b/apps/server/src/orchestration-v2/ShellStream.test.ts@@ -235,9 +235,24 @@ describe("omitOlderSettledShells", () => {omitOlderSettledShells({ threads, snapshotSequence: 7, now });it("keeps the 25 newest settled threads and counts the rest per project", () => {- const result = omit([...newest, row("old", 30), row("b-old", 40), row("unsettled", null)]);+ const sideChat = row("side-chat", 0, {+ lineage: {+ parentThreadId: ThreadId.make("new-0"),+ relationshipToParent: "fork",+ rootThreadId: ThreadId.make("new-0"),+ sideChat: true,+ },+ });+ const result = omit([+ ...newest,+ sideChat,+ row("old", 30),+ row("b-old", 40),+ row("unsettled", null),+ ]);expect(result.threads.map((thread) => thread.id)).toEqual([...newest.map((thread) => thread.id),+ "side-chat","unsettled",]);expect(result.olderSettled).toEqual({@@ -262,7 +277,7 @@ describe("omitOlderSettledShells", () => {expect(result.olderSettled.counts).toEqual([]);});- it("keeps older rows that are snoozed, live, or above a kept subagent, and still counts them", () => {+ it("keeps older rows that are snoozed, live, or above a kept subagent or side chat, and still counts them", () => {const threads = [...newest,row("snoozed", 30, { snoozedUntil: DateTime.makeUnsafe(101 * DAY) }),@@ -280,6 +295,15 @@ describe("omitOlderSettledShells", () => {settledOverride: null,settledAt: null,}),+ row("side-chat-parent", 30),+ row("side-chat", null, {+ lineage: {+ parentThreadId: ThreadId.make("side-chat-parent"),+ relationshipToParent: "fork",+ rootThreadId: ThreadId.make("side-chat-parent"),+ sideChat: true,+ },+ }),];const result = omit(threads);expect(result.threads.map((thread) => thread.id).slice(25)).toEqual([@@ -287,8 +311,10 @@ describe("omitOlderSettledShells", () => {"running","parent","child",+ "side-chat-parent",+ "side-chat",]);- expect(result.olderSettled.counts).toEqual([{ projectId: "project-a", count: 4 }]);+ expect(result.olderSettled.counts).toEqual([{ projectId: "project-a", count: 5 }]);});});diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.tsindex 67d07d6684c..0fa5251a7ef 100644--- a/apps/server/src/orchestration-v2/ShellStream.ts+++ b/apps/server/src/orchestration-v2/ShellStream.ts@@ -12,6 +12,7 @@ import type {ThreadId,} from "@t3tools/contracts";import {+ isListedThreadLineage,isLiveSubagentShell,isOlderSettledThreadShell,OrchestrationProjectShell as ProjectShellSchema,@@ -98,7 +99,11 @@ function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {if (row.lineage.relationshipToParent === "subagent") {subagentThreadIds.add(row.id);if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId);- } else if (row.settledOverride === "settled" && row.settledAt !== null) {+ } else if (+ isListedThreadLineage(row.lineage) &&+ row.settledOverride === "settled" &&+ row.settledAt !== null+ ) {settledTimes.push(DateTime.toEpochMillis(row.settledAt));}}@@ -121,10 +126,12 @@ function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {};}-function subagentAncestorIds(threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>) {+function hiddenChildAncestorIds(+ threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>,+) {const ancestorIds = new Set<string>();for (const thread of threads) {- if (thread.lineage.relationshipToParent !== "subagent") continue;+ if (isListedThreadLineage(thread.lineage)) continue;if (thread.lineage.parentThreadId !== null) ancestorIds.add(thread.lineage.parentThreadId);ancestorIds.add(thread.lineage.rootThreadId);}@@ -156,7 +163,7 @@ function omitOlderSettledShellsWith(} {const nowMs = DateTime.toEpochMillis(input.now);const beforeMs = facts.olderSettledBeforeMs ?? nowMs;- const ancestorIds = subagentAncestorIds(input.threads);+ const ancestorIds = hiddenChildAncestorIds(input.threads);const threads = input.threads.filter((thread) =>!isOlderSettledThreadShell(thread, beforeMs) ||@@ -207,7 +214,8 @@ export function activeShellRowsForSubscriber(/*** Opted-in snapshots keep the 25 newest settled top-level threads (and ties) and count the rest per* project in `olderSettled`; clients page them with `getOlderSettledThreads`. Older rows stay while- * pinned, snoozed, live, or above a kept subagent, so walks over shell rows still find them.+ * pinned, snoozed, live, or above a kept subagent or side chat, so walks over shell rows still find+ * them.*/export function omitOlderSettledShells(input: {readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;@@ -255,7 +263,10 @@ function shellSubscriberThreadIds(entry.lineage.relationshipToParent === "subagent" &&(!options.omitIdleSubagents || entry.mayBeLive || facts.subagentParentIds.has(entry.id)),);- const ancestorIds = subagentAncestorIds(subagents);+ const ancestorIds = hiddenChildAncestorIds([+ ...subagents,+ ...index.filter((entry) => entry.lineage.sideChat === true),+ ]);const keptSubagentIds = new Set(subagents.map((entry) => entry.id));const beforeMs = facts.olderSettledBeforeMs;return index.flatMap((entry) =>diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.tsindex 1015e44694c..d4867a264ec 100644--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts@@ -1547,3 +1547,82 @@ it.effect("stops the running turn when a goal clear ends the goal driving it", (}),),);++it.effect("a side chat that opens with /goal gets its context on the next question", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { events, layer, started, startFirstTurn } = yield* goalHarness("side-chat-goal");+ yield* Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ const parentId = yield* startFirstTurn;+ const sideChatId = ThreadId.make("thread:side-chat-goal-child");+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("side-chat"),+ sourceThreadId: parentId,+ targetThreadId: sideChatId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });+ const ask = (id: string, text: string) =>+ orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make(id),+ threadId: sideChatId,+ messageId: MessageId.make(`message:${id}`),+ text,+ attachments: [],+ modelSelection: runSelection,+ dispatchMode: { type: "start_immediately" },+ createdBy: "user",+ creationSource: "web",+ });+ const sideChatEvent = (matches: (event: OrchestrationV2DomainEvent) => boolean) =>+ orchestrator.streamDomainEvents.pipe(+ Stream.filter((event) => event.threadId === sideChatId && matches(event)),+ Stream.take(1),+ Stream.runDrain,+ Effect.forkScoped({ startImmediately: true }),+ );+ const running = yield* sideChatEvent(+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",+ );+ const settled = yield* sideChatEvent(+ (event) => event.type === "run.updated" && event.payload.status === "waiting",+ );+ yield* ask("goal", "/goal clear");+ yield* worker.drain();+ yield* Fiber.join(running);+ const turn = (yield* orchestrator.getThreadProjection(sideChatId)).providerTurns[0]!;+ yield* Queue.offer(events, {+ type: "provider_turn.updated",+ driver,+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },+ });+ yield* Queue.offer(events, {+ type: "turn.terminal",+ driver,+ providerThreadId: turn.providerThreadId,+ providerTurnId: turn.id,+ runOrdinal: started[1]!.runOrdinal,+ status: "completed",+ failure: null,+ threadDisposition: "reusable",+ });+ yield* Fiber.join(settled);+ yield* worker.drain();+ yield* ask("question", "What is the main thread doing?");+ yield* worker.drain();++ const [first, goal, question] = started.map((turn) => turn.message.text);+ assert.deepEqual([first, goal], ["first", "/goal clear"]);+ assert.include(question, "You are in a side chat beside the main thread.");+ assert.include(question, "- User: first");+ assert.isTrue(question?.endsWith("What is the main thread doing?"));+ }).pipe(Effect.provide(layer));+ }),+ ),+);diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.tsindex 3350d31fb70..71d40332f2d 100644--- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts+++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts@@ -1,5 +1,6 @@import { assert, it } from "@effect/vitest";import {+ CheckpointId,CommandId,EventId,MessageId,@@ -214,13 +215,15 @@ it.effect.each(forkCases)(const attemptId = RunAttemptId.make("interrupted-source-attempt");const providerTurnId = ProviderTurnId.make("interrupted-source-turn");const rootNodeId = NodeId.make("interrupted-source-root");+ const grandparentThreadId = ThreadId.make("fork-boundary-grandparent");+ const grandparentRunId = RunId.make("fork-boundary-grandparent-run");yield* orchestrator.dispatch({type: "thread.create",- commandId: CommandId.make("create-source"),- threadId: sourceThreadId,+ commandId: CommandId.make("create-grandparent"),+ threadId: grandparentThreadId,projectId: ProjectId.make("fork-boundary-project"),- title: "Fork boundary source",+ title: "Fork boundary grandparent",modelSelection,runtimeMode: "full-access",interactionMode: "default",@@ -229,6 +232,29 @@ it.effect.each(forkCases)(createdBy: "user",creationSource: "web",});+ yield* writeParentRun({+ threadId: grandparentThreadId,+ runId: RunId.make("fork-boundary-grandparent-rolled-back-run"),+ ordinal: 1,+ status: "rolled_back",+ text: "ROLLED_BACK_MARKER",+ });+ yield* writeParentRun({+ threadId: grandparentThreadId,+ runId: grandparentRunId,+ ordinal: 2,+ status: "completed",+ text: "GRANDPARENT_MARKER",+ });+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("fork-grandparent"),+ sourceThreadId: grandparentThreadId,+ targetThreadId: sourceThreadId,+ sourcePoint: { type: "run", runId: grandparentRunId },+ createdBy: "user",+ creationSource: "web",+ });yield* eventSink.write({events: [{@@ -246,8 +272,8 @@ it.effect.each(forkCases)(nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },nativeConversationHeadRef: null,status: "idle",- firstRunOrdinal: 1,- lastRunOrdinal: 2,+ firstRunOrdinal: 2,+ lastRunOrdinal: 3,handoffIds: [],forkedFrom: null,createdAt: now,@@ -299,8 +325,15 @@ it.effect.each(forkCases)(],});}- for (const ordinal of [1, 2]) {- const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");+ yield* writeParentRun({+ threadId: sourceThreadId,+ runId: RunId.make("fork-boundary-source-rolled-back-run"),+ ordinal: 1,+ status: "rolled_back",+ text: "SOURCE_ROLLED_BACK_MARKER",+ });+ for (const ordinal of [2, 3]) {+ const runId = ordinal === 2 ? sourceRunId : RunId.make("later-run");const messageId = MessageId.make(`source-message-${ordinal}`);yield* eventSink.write({events: [@@ -319,8 +352,8 @@ it.effect.each(forkCases)(providerThreadId,userMessageId: messageId,rootNodeId: null,- activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,- status: ordinal === 1 ? status : "completed",+ activeAttemptId: ordinal === 2 && status === "interrupted" ? attemptId : null,+ status: ordinal === 2 ? status : "completed",queuePosition: null,requestedAt: now,startedAt: now,@@ -355,7 +388,7 @@ it.effect.each(forkCases)(creationSource: "web",inputIntent: "turn_start",messageId,- text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",+ text: ordinal === 2 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",attachments: [],},},@@ -388,6 +421,9 @@ it.effect.each(forkCases)(assert.lengthOf(target.contextHandoffs, 1);const handoff = target.contextHandoffs[0]!;const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";+ assert.include(`${handoff.summaryText}\n${history}`, "GRANDPARENT_MARKER");+ assert.notInclude(`${handoff.summaryText}\n${history}`, "SOURCE_ROLLED_BACK_MARKER");+ assert.notInclude(`${handoff.summaryText}\n${history}`, "ROLLED_BACK_MARKER");assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");assert.isNull(target.providerThreads[0]?.forkedFrom);@@ -607,3 +643,561 @@ it.effect.each([);},);++const writeParentRun = (input: {+ readonly threadId: ThreadId;+ readonly runId: RunId;+ readonly ordinal: number;+ /** Preparing, failed, and interrupted runs asked for a new worktree. */+ readonly status:+ | "preparing"+ | "running"+ | "queued"+ | "completed"+ | "rolled_back"+ | "failed"+ | "interrupted";+ readonly text: string;+ /** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */+ readonly stable?: boolean;+}) =>+ Effect.gen(function* () {+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const { driver, instanceId, modelSelection } = forkCases[0]!;+ const messageId = MessageId.make(`${input.runId}:message`);+ const providerThreadId = input.stable+ ? ProviderThreadId.make(`${input.runId}:provider-thread`)+ : null;+ yield* eventSink.write({+ events: [+ ...(providerThreadId === null+ ? []+ : [+ {+ id: EventId.make(`${input.runId}:provider-thread`),+ type: "provider-thread.updated" as const,+ threadId: input.threadId,+ occurredAt: now,+ payload: {+ id: providerThreadId,+ driver,+ providerInstanceId: instanceId,+ providerSessionId: null,+ appThreadId: input.threadId,+ ownerNodeId: null,+ nativeThreadRef: {+ driver,+ nativeId: `${input.runId}:native`,+ strength: "strong" as const,+ },+ nativeConversationHeadRef: null,+ status: "idle" as const,+ firstRunOrdinal: input.ordinal,+ lastRunOrdinal: input.ordinal,+ handoffIds: [],+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ },+ },+ ]),+ {+ id: EventId.make(`${input.runId}:created`),+ type: "run.created",+ threadId: input.threadId,+ runId: input.runId,+ occurredAt: now,+ payload: {+ id: input.runId,+ threadId: input.threadId,+ ordinal: input.ordinal,+ providerInstanceId: instanceId,+ modelSelection,+ providerThreadId,+ userMessageId: messageId,+ rootNodeId: null,+ activeAttemptId: null,+ status: input.status,+ queuePosition: null,+ requestedAt: now,+ startedAt: now,+ completedAt: input.status === "completed" ? now : null,+ checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,+ contextHandoffId: null,+ ...(input.status === "preparing" ||+ input.status === "failed" ||+ input.status === "interrupted"+ ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }+ : {}),+ },+ },+ {+ id: EventId.make(`${input.runId}:item`),+ type: "turn-item.updated",+ threadId: input.threadId,+ runId: input.runId,+ occurredAt: now,+ payload: {+ id: TurnItemId.make(`${input.runId}:item`),+ threadId: input.threadId,+ runId: input.runId,+ nodeId: null,+ providerThreadId,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: input.ordinal * 100,+ status: "completed",+ title: null,+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ inputIntent: "turn_start",+ messageId,+ text: input.text,+ attachments: [],+ },+ },+ ],+ });+ });++/** Marks `threadId` as imported from V1 and gives it one runless imported user message. */+const writeImportedHistory = (threadId: ThreadId, text: string) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const { thread } = yield* orchestrator.getThreadProjection(threadId);+ yield* eventSink.write({+ events: [+ {+ id: EventId.make(`${threadId}:imported`),+ type: "thread.metadata-updated",+ threadId,+ occurredAt: now,+ payload: { ...thread, historyOrigin: "v1_import" },+ },+ {+ id: EventId.make(`${threadId}:imported-item`),+ type: "turn-item.updated",+ threadId,+ occurredAt: now,+ payload: {+ id: TurnItemId.make(`${threadId}:imported-item`),+ threadId,+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "completed",+ title: null,+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ inputIntent: "turn_start",+ messageId: MessageId.make(`${threadId}:imported-message`),+ text,+ attachments: [],+ },+ },+ ],+ });+ });++const createParent = (threadId: ThreadId) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make(`${threadId}:create`),+ threadId,+ projectId: ProjectId.make("side-chat-project"),+ title: "Side chat parent",+ modelSelection: forkCases[0]!.modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdBy: "user",+ creationSource: "web",+ });+ });++const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ return yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make(commandId),+ sourceThreadId,+ targetThreadId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });+ });++const askSideChat = (threadId: ThreadId, commandId: string) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make(commandId),+ threadId,+ messageId: MessageId.make(commandId),+ text: "What is the main thread doing?",+ attachments: [],+ dispatchMode: { type: "start_immediately" },+ createdBy: "user",+ creationSource: "web",+ });+ });++it.effect("a side chat of an idle parent still starts with the framing note", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const parentId = ThreadId.make("side-chat-idle-parent");+ const sideChatId = ThreadId.make("side-chat-idle-child");+ yield* createParent(parentId);+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make("side-chat-idle-parent-run"),+ ordinal: 1,+ status: "completed",+ text: "Parent work",+ stable: true,+ });++ yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId);+ yield* askSideChat(sideChatId, "side-chat-idle-first-message");++ const started = yield* orchestrator.getThreadProjection(sideChatId);+ assert.isNotNull(started.providerThreads[0]?.forkedFrom);+ assert.lengthOf(started.contextHandoffs, 1);+ const [handoff] = started.contextHandoffs;+ assert.isTrue(+ handoff!.summaryText.startsWith("You are in a side chat beside the main thread."),+ );+ assert.notInclude(handoff!.summaryText, "Main thread activity");+ }).pipe(Effect.provide(forkCases[0]!.layer)),+);++it.effect("a side chat waits for the parent's new worktree, also after its setup ended", () =>+ Effect.gen(function* () {+ for (const status of ["preparing", "failed", "interrupted"] as const) {+ const parentId = ThreadId.make(`side-chat-worktree-parent-${status}`);+ yield* createParent(parentId);+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make(`side-chat-worktree-parent-run-${status}`),+ ordinal: 1,+ status,+ text: "Parent work",+ });++ const rejected = yield* forkSideChat(+ `side-chat-worktree-fork-${status}`,+ parentId,+ ThreadId.make(`side-chat-worktree-child-${status}`),+ ).pipe(Effect.flip);+ assert.include(String(rejected.cause), "has no worktree yet", status);+ }+ }).pipe(Effect.provide(forkCases[0]!.layer)),+);++it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const parentId = ThreadId.make("side-chat-close-parent");+ const unused = ThreadId.make("side-chat-close-unused");+ const used = ThreadId.make("side-chat-close-used");+ yield* createParent(parentId);+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make("side-chat-close-parent-run"),+ ordinal: 1,+ status: "completed",+ text: "Parent work",+ stable: true,+ });+ yield* forkSideChat("side-chat-close-fork-unused", parentId, unused);+ yield* forkSideChat("side-chat-close-fork-used", parentId, used);+ yield* askSideChat(used, "side-chat-close-used-message");+ const close = (threadId: ThreadId) =>+ orchestrator.dispatch({+ type: "thread.delete",+ commandId: CommandId.make(`side-chat-close:${threadId}`),+ threadId,+ onlyIfUnused: true,+ });++ yield* close(unused);+ yield* close(used);+ assert.isNotNull((yield* orchestrator.getThreadProjection(unused)).thread.deletedAt);+ assert.isNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);++ yield* orchestrator.dispatch({+ type: "thread.delete",+ commandId: CommandId.make("side-chat-close-delete-parent"),+ threadId: parentId,+ });+ assert.isNotNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);+ const orphan = yield* forkSideChat(+ "side-chat-close-orphan",+ parentId,+ ThreadId.make("side-chat-close-orphan"),+ ).pipe(Effect.flip);+ assert.include(String(orphan.cause), "was deleted");+ }).pipe(Effect.provide(forkCases[0]!.layer)),+);++it.effect("a side chat opened during the parent's first turn starts from a digest", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const grandparentId = ThreadId.make("side-chat-busy-grandparent");+ const grandparentRunId = RunId.make("side-chat-busy-grandparent-run");+ const parentId = ThreadId.make("side-chat-busy-parent");+ const sideChatId = ThreadId.make("side-chat-busy-child");+ yield* createParent(grandparentId);+ yield* writeParentRun({+ threadId: grandparentId,+ runId: grandparentRunId,+ ordinal: 1,+ status: "completed",+ text: "GRANDPARENT_MARKER",+ stable: true,+ });+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("side-chat-busy-parent-fork"),+ sourceThreadId: grandparentId,+ targetThreadId: parentId,+ sourcePoint: { type: "run", runId: grandparentRunId },+ createdBy: "user",+ creationSource: "web",+ });+ yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make("side-chat-rewound-parent-run"),+ ordinal: 1,+ status: "rolled_back",+ text: "PARENT_ROLLED_BACK_MARKER",+ });+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make("side-chat-busy-parent-run"),+ ordinal: 2,+ status: "running",+ text: "PARENT_RUNNING_MARKER",+ });+ yield* writeParentRun({+ threadId: parentId,+ runId: RunId.make("side-chat-queued-parent-run"),+ ordinal: 3,+ status: "queued",+ text: "PARENT_QUEUED_MARKER",+ });+ const fork = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>+ orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make(commandId),+ sourceThreadId,+ targetThreadId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });++ yield* fork("side-chat-busy-fork", parentId, sideChatId);+ const created = yield* orchestrator.getThreadProjection(sideChatId);+ assert.isTrue(created.thread.lineage.sideChat);+ assert.equal(created.thread.runtimeMode, "approval-required");+ assert.isNull(created.thread.forkedFrom);+ assert.deepEqual(created.contextTransfers[0]?.sourcePoint, { threadId: parentId });++ const nested = yield* fork(+ "side-chat-busy-nested",+ sideChatId,+ ThreadId.make("side-chat-busy-nested"),+ ).pipe(Effect.flip);+ assert.equal(nested._tag, "OrchestratorDispatchError");+ // Either would take the side chat's lock before the parent's, against the delete cascade.+ const ontoParent = yield* fork("side-chat-busy-onto-parent", sideChatId, parentId).pipe(+ Effect.flip,+ );+ assert.equal(ontoParent._tag, "OrchestratorThreadAlreadyExistsError");+ const ontoExisting = yield* fork("side-chat-busy-onto-existing", parentId, sideChatId).pipe(+ Effect.flip,+ );+ assert.equal(ontoExisting._tag, "OrchestratorThreadAlreadyExistsError");+ const plainOntoExisting = yield* orchestrator+ .dispatch({+ type: "thread.fork",+ commandId: CommandId.make("side-chat-busy-plain-onto-existing"),+ sourceThreadId: parentId,+ targetThreadId: sideChatId,+ sourcePoint: { type: "latest_stable" },+ createdBy: "user",+ creationSource: "web",+ })+ .pipe(Effect.flip);+ assert.equal(plainOntoExisting._tag, "OrchestratorThreadAlreadyExistsError");+ const busyMergeBack = yield* orchestrator+ .dispatch({+ type: "thread.merge_back",+ commandId: CommandId.make("side-chat-busy-merge-back"),+ sourceThreadId: sideChatId,+ targetThreadId: parentId,+ sourcePoint: { type: "latest_stable" },+ createdBy: "user",+ creationSource: "web",+ })+ .pipe(Effect.flip);+ assert.include(String(busyMergeBack.cause), "active work");++ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("side-chat-busy-first-message"),+ threadId: sideChatId,+ messageId: MessageId.make("side-chat-busy-first-message"),+ text: "What is the main thread doing?",+ attachments: [],+ dispatchMode: { type: "start_immediately" },+ createdBy: "user",+ creationSource: "web",+ });+ const started = yield* orchestrator.getThreadProjection(sideChatId);+ const [handoff] = started.contextHandoffs;+ assert.lengthOf(started.contextHandoffs, 1);+ assert.deepEqual(started.contextTransfers[0]?.resolution, {+ strategy: "portable_context",+ contextHandoffId: handoff!.id,+ });+ assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");+ // Inherited rows come first, so the cap truncates them first.+ assert.isAbove(+ handoff!.summaryText.indexOf("- User: PARENT_IMPORTED_MARKER"),+ handoff!.summaryText.indexOf("- User: GRANDPARENT_MARKER"),+ );+ assert.include(handoff!.summaryText, "- User: GRANDPARENT_MARKER");+ assert.notInclude(handoff!.summaryText, "PARENT_ROLLED_BACK_MARKER");+ assert.notInclude(handoff!.summaryText, "PARENT_QUEUED_MARKER");+ assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");+ assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");+ assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);+ assert.equal(+ started.messages.find((message) => message.role === "user")?.text,+ "What is the main thread doing?",+ );++ yield* orchestrator.dispatch({+ type: "thread.delete",+ commandId: CommandId.make("side-chat-busy-delete-parent"),+ threadId: parentId,+ });+ assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);+ }).pipe(Effect.provide(forkCases[0]!.layer)),+);++it.effect("merge-back rejects a second fork's context until the first is consumed", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const parentId = ThreadId.make("merge-back-guard-parent");+ const parentRunId = RunId.make("merge-back-guard-parent-run");+ yield* createParent(parentId);+ yield* writeParentRun({+ threadId: parentId,+ runId: parentRunId,+ ordinal: 1,+ status: "completed",+ text: "Parent work",+ });+ const forkAndRun = (name: string) =>+ Effect.gen(function* () {+ const threadId = ThreadId.make(`merge-back-guard-${name}`);+ const runId = RunId.make(`merge-back-guard-${name}-run`);+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make(`merge-back-guard-fork-${name}`),+ sourceThreadId: parentId,+ targetThreadId: threadId,+ sourcePoint: { type: "run", runId: parentRunId },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });+ yield* writeParentRun({ threadId, runId, ordinal: 1, status: "completed", text: name });+ return { threadId, runId };+ });+ const mergeBack = (commandId: string, fork: { threadId: ThreadId; runId: RunId }) =>+ orchestrator.dispatch({+ type: "thread.merge_back",+ commandId: CommandId.make(commandId),+ sourceThreadId: fork.threadId,+ targetThreadId: parentId,+ sourcePoint: { type: "run", runId: fork.runId },+ createdBy: "user",+ creationSource: "web",+ });+ const first = yield* forkAndRun("first");+ const second = yield* forkAndRun("second");++ yield* mergeBack("merge-back-guard-first", first);+ const rejected = yield* mergeBack("merge-back-guard-second", second).pipe(Effect.flip);+ assert.include(String(rejected.cause), "pending context from another side chat or fork");+ yield* mergeBack("merge-back-guard-first-again", first);+ // That pending merge-back targets the parent, so it does not block one into `first`.+ const nested = { threadId: ThreadId.make("merge-back-guard-nested") };+ const nestedRunId = RunId.make("merge-back-guard-nested-run");+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("merge-back-guard-fork-nested"),+ sourceThreadId: first.threadId,+ targetThreadId: nested.threadId,+ sourcePoint: { type: "run", runId: first.runId },+ createdBy: "user",+ creationSource: "web",+ });+ yield* writeParentRun({+ threadId: nested.threadId,+ runId: nestedRunId,+ ordinal: 1,+ status: "completed",+ text: "nested",+ });+ yield* orchestrator.dispatch({+ type: "thread.merge_back",+ commandId: CommandId.make("merge-back-guard-nested"),+ sourceThreadId: nested.threadId,+ targetThreadId: first.threadId,+ sourcePoint: { type: "run", runId: nestedRunId },+ createdBy: "user",+ creationSource: "web",+ });++ const parent = yield* orchestrator.getThreadProjection(parentId);+ assert.deepEqual(+ parent.contextTransfers+ .filter((transfer) => transfer.type === "merge_back")+ .map((transfer) => [transfer.sourceThreadId, transfer.status]),+ [+ [first.threadId, "superseded"],+ [first.threadId, "pending"],+ ],+ );+ }).pipe(Effect.provide(forkCases[0]!.layer)),+);diff --git a/apps/server/src/orchestration-v2/ThreadForkService.test.ts b/apps/server/src/orchestration-v2/ThreadForkService.test.tsindex e1bf75dd128..6d401d96849 100644--- a/apps/server/src/orchestration-v2/ThreadForkService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadForkService.test.ts@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";import {CommandId,ContextTransferId,+ EnvironmentId,MessageId,type ModelSelection,type OrchestrationV2AppThread,@@ -111,6 +112,7 @@ function makeSourceProjection(sourceRun: OrchestrationV2Run): OrchestrationV2Thrconst planFork = (sourceRun: OrchestrationV2Run,sourceProjection = makeSourceProjection(sourceRun),+ options: { readonly sideChat?: boolean } = {},) =>Effect.gen(function* () {const service = yield* ThreadForkService.ThreadForkServiceV2;@@ -125,6 +127,7 @@ const planFork = (transferId: ContextTransferId.make("context-transfer:fork-snoozed-source"),targetThreadId,title: "Awake fork",+ ...options,createdBy: "user",creationSource: "mobile",createdAt: forkCreatedAt,@@ -261,3 +264,63 @@ it.effect("rejects in-progress and rolled-back fork sources", () =>}}),);++it.effect("marks only requested forks as supervised side chats", () =>+ Effect.gen(function* () {+ const sourceRun = makeSourceRun("completed");+ const sideChat = yield* planFork(sourceRun, makeSourceProjection(sourceRun), {+ sideChat: true,+ });+ assert.isTrue(sideChat.targetThread.lineage.sideChat);+ assert.equal(sideChat.targetThread.runtimeMode, "approval-required");++ const sideChatSource = makeSourceProjection(sourceRun);+ const sideChatProjection = {+ ...sideChatSource,+ thread: {+ ...sideChatSource.thread,+ lineage: { ...sideChatSource.thread.lineage, sideChat: true },+ },+ };+ const forkOfSideChat = yield* planFork(sourceRun, sideChatProjection);+ assert.isUndefined(forkOfSideChat.targetThread.lineage.sideChat);+ assert.equal(forkOfSideChat.targetThread.runtimeMode, "full-access");++ const nested = yield* planFork(sourceRun, sideChatProjection, { sideChat: true }).pipe(+ Effect.flip,+ );+ assert.equal(nested.cause, "A side chat cannot start another side chat.");++ const subagentSource = makeSourceProjection(sourceRun);+ const fromSubagent = yield* planFork(+ sourceRun,+ {+ ...subagentSource,+ thread: {+ ...subagentSource.thread,+ lineage: { ...subagentSource.thread.lineage, relationshipToParent: "subagent" },+ },+ },+ { sideChat: true },+ ).pipe(Effect.flip);+ assert.equal(fromSubagent.cause, "A subagent cannot start a side chat.");++ const delegatedSource = makeSourceProjection(sourceRun);+ const fromDelegated = yield* planFork(+ sourceRun,+ {+ ...delegatedSource,+ thread: {+ ...delegatedSource.thread,+ delegatedFrom: {+ environmentId: EnvironmentId.make("linked-environment"),+ threadId: ThreadId.make("linked-parent"),+ title: "Linked parent",+ },+ },+ },+ { sideChat: true },+ ).pipe(Effect.flip);+ assert.equal(fromDelegated.cause, "A subagent cannot start a side chat.");+ }),+);diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.tsindex 71ff9764868..4717daf75e3 100644--- a/apps/server/src/orchestration-v2/ThreadForkService.ts+++ b/apps/server/src/orchestration-v2/ThreadForkService.ts@@ -51,13 +51,15 @@ export function forkableSourceRunStatusError(export interface ThreadForkServiceV2Shape {readonly plan: (input: {readonly sourceProjection: Pick<OrchestrationV2ThreadProjection, "thread">;- readonly sourceRun: OrchestrationV2Run;+ /** Null only for a side chat whose parent has no stable run yet. */+ readonly sourceRun: OrchestrationV2Run | null;readonly sourceProviderThread: OrchestrationV2ProviderThread | undefined;readonly sourceTokenUsage?: OrchestrationV2ProviderTurnTokenUsage | undefined;readonly canonicalSourcePoint: OrchestrationV2ContextSourcePoint;readonly transferId: ContextTransferId;readonly targetThreadId: ThreadId;readonly title?: string;+ readonly sideChat?: boolean;readonly createdBy: OrchestrationV2Actor;readonly creationSource: OrchestrationV2CreationSource;readonly createdAt: DateTime.Utc;@@ -73,11 +75,28 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(ThreadForkServiceV2,ThreadForkServiceV2.of({plan: Effect.fn("ThreadForkService.plan")(function* (input) {- if (!isForkableSourceRunStatus(input.sourceRun.status)) {+ const { sourceRun } = input;+ const sourceLineage = input.sourceProjection.thread.lineage;+ // A task a linked environment delegated here is a subagent of a remote thread.+ if (+ input.sideChat &&+ (sourceLineage.sideChat ||+ sourceLineage.relationshipToParent === "subagent" ||+ input.sourceProjection.thread.delegatedFrom !== undefined)+ ) {return yield* new ThreadForkPlanError({sourceThreadId: input.sourceProjection.thread.id,targetThreadId: input.targetThreadId,- cause: forkableSourceRunStatusError(input.sourceRun),+ cause: sourceLineage.sideChat+ ? "A side chat cannot start another side chat."+ : "A subagent cannot start a side chat.",+ });+ }+ if (sourceRun !== null && !isForkableSourceRunStatus(sourceRun.status)) {+ return yield* new ThreadForkPlanError({+ sourceThreadId: input.sourceProjection.thread.id,+ targetThreadId: input.targetThreadId,+ cause: forkableSourceRunStatusError(sourceRun),});}const targetThread: OrchestrationV2AppThread = {@@ -92,17 +111,19 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(title: input.title ?? `${input.sourceProjection.thread.title} fork`,// The source's title job completes only on the source thread.titleRegeneration: null,+ // Side chats share the parent's worktree, so they start supervised.+ ...(input.sideChat ? { runtimeMode: "approval-required" as const } : {}),activeProviderThreadId: null,lineage: {parentThreadId: input.sourceProjection.thread.id,relationshipToParent: "fork",rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,+ ...(input.sideChat ? { sideChat: true } : {}),},- forkedFrom: {- type: "run",- threadId: input.sourceProjection.thread.id,- runId: input.sourceRun.id,- },+ forkedFrom:+ sourceRun === null+ ? null+ : { type: "run", threadId: input.sourceProjection.thread.id, runId: sourceRun.id },createdAt: input.createdAt,updatedAt: input.createdAt,archivedAt: null,@@ -124,10 +145,11 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(targetThreadId: input.targetThreadId,sourcePoint: input.canonicalSourcePoint,basePoint: null,- sourceProviderInstanceId: input.sourceRun.providerInstanceId,+ sourceProviderInstanceId:+ sourceRun?.providerInstanceId ?? input.sourceProjection.thread.providerInstanceId,// Only native forks retain this context; portable handoffs rebuild it.sourceTokenUsage:- (input.sourceRun.status === "completed" || input.sourceRun.status === "waiting") &&+ (sourceRun?.status === "completed" || sourceRun?.status === "waiting") &&input.sourceProviderThread?.nativeThreadRef?.strength === "strong"? input.sourceTokenUsage: undefined,diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex 15417783cd7..276d673a39d 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -11,6 +11,7 @@ import type {import {type ChatAttachment,CommandId,+ isListedThreadLineage,MessageId,OrchestrationV2StopWorkflowError,type OrchestrationV2StopWorkflowInput,@@ -418,7 +419,7 @@ export interface ThreadManagementServiceShape {Orchestrator.OrchestratorV2Error>;readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];- /** Omit `projectId` to list every project's threads. */+ /** Omit `projectId` to list every project's threads. Side chats are never listed. */readonly listProjectThreads: (input: {readonly projectId?: ProjectId | undefined;readonly includeSubagents: boolean;@@ -793,9 +794,10 @@ const make = Effect.gen(function* () {),Effect.map((snapshot) =>snapshot.threads- .filter(- (thread) =>- input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",+ .filter((thread) =>+ input.includeSubagents+ ? thread.lineage.sideChat !== true+ : isListedThreadLineage(thread.lineage),).toSorted((left, right) =>diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.tsindex 5d816133c89..b8d75340ec6 100644--- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts+++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts@@ -66,6 +66,7 @@ const thread = (readonly archivedAt?: DateTime.Utc;readonly deletedAt?: DateTime.Utc;readonly subagentOf?: ThreadId;+ readonly sideChatOf?: ThreadId;readonly title?: string;readonly settledAt?: DateTime.Utc;readonly linkedPullRequest?: ThreadLinkedPullRequest;@@ -98,7 +99,14 @@ const thread = (relationshipToParent: "subagent",rootThreadId: overrides.subagentOf,}- : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ : overrides.sideChatOf+ ? {+ parentThreadId: overrides.sideChatOf,+ relationshipToParent: "fork",+ rootThreadId: overrides.sideChatOf,+ sideChat: true,+ }+ : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },forkedFrom: null,createdAt: at(0),updatedAt: at(0),@@ -366,13 +374,14 @@ it.layer(layerTest)("ThreadSearch", (it) => {}),);- it.effect("matches inside identifiers and skips subagent threads and short tokens", () =>+ it.effect("matches inside identifiers and skips hidden threads and short tokens", () =>Effect.gen(function* () {const projections = yield* ProjectionStore.ProjectionStoreV2;const search = yield* ThreadSearch.ThreadSearch;const project = ProjectId.make("project:search-tokens");const parent = ThreadId.make("thread:tokens-parent");const subagent = ThreadId.make("thread:tokens-subagent");+ const sideChat = ThreadId.make("thread:tokens-side-chat");yield* createProject(project);yield* Effect.forEach([@@ -380,6 +389,8 @@ it.layer(layerTest)("ThreadSearch", (it) => {message(parent, "parent", "user", "Rename ThreadSearchService before shipping"),thread(subagent, project, { subagentOf: parent }),message(subagent, "subagent", "assistant", "ThreadSearchService renamed"),+ thread(sideChat, project, { sideChatOf: parent, title: "ThreadSearchService question" }),+ message(sideChat, "side-chat", "user", "Why rename ThreadSearchService?"),],projections.apply,{ discard: true },diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.tsindex 62c7f4eed45..3c97122c1c6 100644--- a/apps/server/src/orchestration-v2/ThreadSearch.ts+++ b/apps/server/src/orchestration-v2/ThreadSearch.ts@@ -154,7 +154,7 @@ export function buildSearchSnippet(text: string, matchStart: number): string {return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;}-// Hidden subagent threads must be filtered before the hit limit so visible matches aren't lost.+// Filter hidden subagents and side chats before the hit limit so visible matches aren't lost.// Word starts and ranking follow the title rules in JS.// Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages.// The scan folds ASCII case only, so accent variants and non-ASCII case variants may not match.@@ -174,6 +174,7 @@ export const messageHitsQuery = (AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')IS NOT 'subagent'+ AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1)${match === null@@ -332,6 +333,7 @@ export const make = Effect.gen(function* () {AND projects.deleted_at IS NULLAND json_extract(threads.payload_json, '$.lineage.relationshipToParent')IS NOT 'subagent'+ AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1AND (${projectId} IS NULL OR threads.project_id = ${projectId})`,});@@ -362,6 +364,7 @@ export const make = Effect.gen(function* () {AND projects.deleted_at IS NULLAND json_extract(threads.payload_json, '$.lineage.relationshipToParent')IS NOT 'subagent'+ AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'AND json_extract(threads.payload_json, '$.settledAt') < ${before}AND (${projectIds} IS NULL@@ -384,6 +387,7 @@ export const make = Effect.gen(function* () {AND json_extract(threads.payload_json, '$.archivedAt') IS NULLAND json_extract(threads.payload_json, '$.lineage.relationshipToParent')IS NOT 'subagent'+ AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'AND json_extract(threads.payload_json, '$.settledAt') < ${before}AND (${projectIds} IS NULLdiff --git a/apps/server/src/orchestration-v2/ThreadStream.test.ts b/apps/server/src/orchestration-v2/ThreadStream.test.tsindex a5059eada44..5c9fd310e93 100644--- a/apps/server/src/orchestration-v2/ThreadStream.test.ts+++ b/apps/server/src/orchestration-v2/ThreadStream.test.ts@@ -1,8 +1,13 @@import {+ ContextHandoffId,+ ContextTransferId,EventId,OrchestrationV2ThreadStreamItem,+ ProviderThreadId,+ RunId,ThreadId,TurnItemId,+ type OrchestrationV2ContextHandoff,type OrchestrationV2ProjectedTurnItem,type OrchestrationV2ThreadProjection,type OrchestrationV2TurnItem,@@ -149,11 +154,31 @@ describe("decideThreadResume", () => {});it("builds socket fallback snapshots with a bounded timeline and history cursor", () => {+ const projection = timelineProjection(80);+ // A delivered side chat digest stays "ready", which bounded snapshots keep.+ const sideChatHandoff = {+ id: ContextHandoffId.make("side-chat-handoff"),+ transferId: ContextTransferId.make("side-chat-transfer"),+ threadId: THREAD_ID,+ targetRunId: RunId.make("side-chat-run"),+ fromProviderThreadIds: [],+ toProviderThreadId: ProviderThreadId.make("side-chat-provider-thread"),+ coveredRunOrdinals: { from: 1, to: 1 },+ strategy: "manual_context",+ status: "ready",+ summaryMessageId: null,+ summaryText: "x".repeat(8_000),+ delivery: { nativeThreadId: "native", status: "inline", itemIds: [] },+ createdByProviderInstanceId: null,+ createdAt: NOW,+ updatedAt: NOW,+ } satisfies OrchestrationV2ContextHandoff;const snapshot = buildBoundedThreadStreamSnapshot({snapshotSequence: 44,- projection: timelineProjection(80),+ projection: { ...projection, contextHandoffs: [sideChatHandoff] },});+ expect(snapshot.projection.contextHandoffs.map((handoff) => handoff.summaryText)).toEqual([""]);expect(snapshot.kind).toBe("snapshot");expect(snapshot.snapshotSequence).toBe(44);expect(snapshot.projection.visibleTurnItems).toHaveLength(75);diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.tsindex a04fe4c7c13..037f2a394f2 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts@@ -595,6 +595,220 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i);}),);++ it.effect(+ "deletes a side chat with its parent only after the side chat's in-flight command",+ () =>+ Effect.gen(function* () {+ const projects = yield* ProjectService.ProjectService;+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;+ const projectId = ProjectId.make("runtime-side-chat-delete");+ const parentId = ThreadId.make("runtime-side-chat-delete-parent");+ const sideChatId = ThreadId.make("runtime-side-chat-delete-child");+ const updateCommandId = CommandId.make("runtime-side-chat-delete-update");+ yield* projects.create({+ commandId: CommandId.make("runtime-side-chat-delete-project"),+ projectId,+ title: "Side chat deletion",+ workspaceRoot: "/work/side-chat-deletion",+ });+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make("runtime-side-chat-delete-create"),+ createdBy: "user",+ creationSource: "web",+ threadId: parentId,+ projectId,+ title: "Parent",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ });+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("runtime-side-chat-delete-fork"),+ sourceThreadId: parentId,+ targetThreadId: sideChatId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });++ const updateReady = yield* Deferred.make<void>();+ const releaseUpdate = yield* Deferred.make<void>();+ const deletionQueued = yield* Deferred.make<void>();+ const commitCommand = eventSink.commitCommand;+ const withLock = executor.withLock;+ let sideChatLockRequests = 0;+ const commitSpy = vi+ .spyOn(eventSink, "commitCommand")+ .mockImplementation((input) =>+ input.commandId === updateCommandId+ ? Deferred.succeed(updateReady, undefined).pipe(+ Effect.andThen(Deferred.await(releaseUpdate)),+ Effect.andThen(commitCommand(input)),+ )+ : commitCommand(input),+ );+ const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (+ key,+ effect,+ ) => {+ if (key !== sideChatId || ++sideChatLockRequests !== 2) return withLock(key, effect);+ return Deferred.succeed(deletionQueued, undefined).pipe(+ Effect.andThen(withLock(key, effect)),+ );+ };+ const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);+ yield* Effect.gen(function* () {+ const updateFiber = yield* orchestrator+ .dispatch({+ type: "thread.metadata.update",+ commandId: updateCommandId,+ threadId: sideChatId,+ title: "Updated before deletion",+ })+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Effect.raceFirst(+ Deferred.await(updateReady),+ Fiber.join(updateFiber).pipe(+ Effect.andThen(+ Effect.die("The update completed before reaching its commit barrier."),+ ),+ ),+ );+ const deleteFiber = yield* orchestrator+ .dispatch({+ type: "thread.delete",+ commandId: CommandId.make("runtime-side-chat-delete-parent"),+ threadId: parentId,+ })+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Effect.raceFirst(+ Deferred.await(deletionQueued),+ Fiber.join(deleteFiber).pipe(+ Effect.andThen(Effect.die("Parent deletion bypassed the side chat's command.")),+ ),+ );+ yield* Deferred.succeed(releaseUpdate, undefined);+ yield* Fiber.join(updateFiber);+ yield* Fiber.join(deleteFiber);+ const sideChat = yield* orchestrator.getThreadProjection(sideChatId);+ assert.isNotNull(sideChat.thread.deletedAt);+ assert.equal(sideChat.thread.title, "Updated before deletion");+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => {+ commitSpy.mockRestore();+ lockSpy.mockRestore();+ }),+ ),+ );+ }),+ );++ // A fork from a side chat onto its parent used to lock the side chat, then the parent: the+ // reverse of the parent delete's order.+ it.effect("a parent delete and a fork from its side chat onto the parent do not deadlock", () =>+ Effect.gen(function* () {+ const projects = yield* ProjectService.ProjectService;+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;+ const projectId = ProjectId.make("runtime-side-chat-lock-order");+ const parentId = ThreadId.make("runtime-side-chat-lock-order-parent");+ const sideChatId = ThreadId.make("runtime-side-chat-lock-order-child");+ yield* projects.create({+ commandId: CommandId.make("runtime-side-chat-lock-order-project"),+ projectId,+ title: "Side chat lock order",+ workspaceRoot: "/work/side-chat-lock-order",+ });+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make("runtime-side-chat-lock-order-create"),+ createdBy: "user",+ creationSource: "web",+ threadId: parentId,+ projectId,+ title: "Parent",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ });+ yield* orchestrator.dispatch({+ type: "thread.fork",+ commandId: CommandId.make("runtime-side-chat-lock-order-fork"),+ sourceThreadId: parentId,+ targetThreadId: sideChatId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ });++ const deleteHoldsParent = yield* Deferred.make<void>();+ const releaseDelete = yield* Deferred.make<void>();+ const forkWaitsForParent = yield* Deferred.make<void>();+ const withLock = executor.withLock;+ let parentLockRequests = 0;+ const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (+ key,+ effect,+ ) => {+ if (key !== parentId) return withLock(key, effect);+ // Dispatch builds locks it may not run, so count when one runs.+ return Effect.suspend(() =>+ ++parentLockRequests === 1+ ? withLock(+ key,+ Deferred.succeed(deleteHoldsParent, undefined).pipe(+ Effect.andThen(Deferred.await(releaseDelete)),+ Effect.andThen(effect),+ ),+ )+ : Deferred.succeed(forkWaitsForParent, undefined).pipe(+ Effect.andThen(withLock(key, effect)),+ ),+ );+ };+ const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);+ yield* Effect.gen(function* () {+ const deleteFiber = yield* orchestrator+ .dispatch({+ type: "thread.delete",+ commandId: CommandId.make("runtime-side-chat-lock-order-delete"),+ threadId: parentId,+ })+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(deleteHoldsParent);+ const forkFiber = yield* orchestrator+ .dispatch({+ type: "thread.fork",+ commandId: CommandId.make("runtime-side-chat-lock-order-fork-back"),+ sourceThreadId: sideChatId,+ targetThreadId: parentId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ createdBy: "user",+ creationSource: "web",+ })+ .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(forkWaitsForParent);+ yield* Deferred.succeed(releaseDelete, undefined);+ yield* Fiber.join(deleteFiber);+ yield* Fiber.join(forkFiber);+ assert.isNotNull((yield* orchestrator.getThreadProjection(parentId)).thread.deletedAt);+ assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);+ }).pipe(Effect.ensuring(Effect.sync(() => lockSpy.mockRestore())));+ }),+ );});const layerSharedApplicationDataPlaneTest = Layer.mergeAll(diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.tsindex 230758714b3..161cb05f8e9 100644--- a/apps/server/src/pullRequest/linkedThreads.test.ts+++ b/apps/server/src/pullRequest/linkedThreads.test.ts@@ -9,7 +9,7 @@ import { listLinkedPullRequestThreads } from "./linkedThreads.ts";const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));it.effect(- "finds active and archived threads for exactly one pull request, excluding deleted and dismissed links",+ "finds active and archived threads for exactly one pull request, excluding deleted, dismissed, and side chat links",() =>Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;@@ -55,6 +55,13 @@ it.effect(source: "created",},{ id: "deleted", host: "github.com", repository: "acme/web", number: 7, source: "manual" },+ {+ id: "side-chat",+ host: "github.com",+ repository: "acme/web",+ number: 7,+ source: "manual",+ },{id: "dismissed",host: "github.com",@@ -87,6 +94,7 @@ it.effect(for (const fixture of fixtures) {const payload = yield* encodePayload({linkedPullRequest: null,+ ...(fixture.id === "side-chat" ? { lineage: { sideChat: true } } : {}),pullRequests: [{ ...fixture, linkedAt: createdAt, snapshot: null, stack: null }],});yield* sql`diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.tsindex c7a2b01946a..b140714531a 100644--- a/apps/server/src/pullRequest/linkedThreads.ts+++ b/apps/server/src/pullRequest/linkedThreads.ts@@ -39,6 +39,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreWHERE json_extract(link.value, '$.number') = ${key.number}AND json_extract(link.value, '$.source') != 'stack-dismissed'AND t.deleted_at IS NULL+ AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1ORDER BY "updatedAt" DESC, id ASC`.pipe(NodeSqliteClient.readOnly);const threads = rowsdiff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex 54742a0af7d..bad5b0d20d2 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -1,10 +1,11 @@-import type {- EnvironmentId,- OrchestrationV2DomainEvent,- OrchestrationV2ThreadShell,- OrchestrationV2TurnItem,- Project,- ThreadId,+import {+ isListedThreadLineage,+ type EnvironmentId,+ type OrchestrationV2DomainEvent,+ type OrchestrationV2ThreadShell,+ type OrchestrationV2TurnItem,+ type Project,+ type ThreadId,} from "@t3tools/contracts";import {RelayApi,@@ -514,10 +515,11 @@ export const make = Effect.gen(function* () {// Read only this thread; full shell reads would make each activity event scale with all threads.const threadShell = yield* threads.getThreadShell(threadId);if (- threadShell?.lineage.relationshipToParent === "subagent" &&+ threadShell !== null &&+ !isListedThreadLineage(threadShell.lineage) &&!(yield* Ref.get(publishedStateByThreadRef)).has(threadId)) {- // Subagents have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.+ // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.return;}const thread =@@ -727,9 +729,9 @@ export const make = Effect.gen(function* () {}const environmentId = yield* serverEnvironment.getEnvironmentId;const projectSnapshot = yield* projects.snapshot;- // Subagents never publish awareness, and they are most threads.+ // Subagents and side chats never publish awareness, and subagents are most threads.const topLevelThreadIds = (yield* threads.listActiveShellIndex()).flatMap((thread) =>- thread.lineage.relationshipToParent === "subagent" ? [] : [thread.id],+ isListedThreadLineage(thread.lineage) ? [thread.id] : [],);const shellSnapshot = yield* threads.getShellSnapshot({location: "active",diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.tsindex b812ad07fa6..54fef56e311 100644--- a/apps/server/src/serverRuntimeStartup.ts+++ b/apps/server/src/serverRuntimeStartup.ts@@ -3,6 +3,7 @@ import {DEFAULT_MODEL,DEFAULT_PROVIDER_INTERACTION_MODE,DEFAULT_SERVER_SETTINGS,+ isListedThreadLineage,type ModelSelection,type Project,ProjectId,@@ -280,8 +281,7 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {workspaceRoot: serverConfig.cwd,});const existingThread = (yield* threads.listActiveShellIndex()).find(- (thread) =>- thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",+ (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),);if (existingThread === undefined) {const serverSettings = yield* ServerSettings.ServerSettingsService;diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.tsindex c1293e33064..e18cdc4320c 100644--- a/apps/server/src/storageCleanup.test.ts+++ b/apps/server/src/storageCleanup.test.ts@@ -721,6 +721,7 @@ describe("subagent worktree ownership", () => {"pending","unrelated","fork",+ "side-chat","recent-activity","recent-inactive","recent-grace",@@ -774,7 +775,12 @@ describe("subagent worktree ownership", () => {rootThreadId:scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId,relationshipToParent:- scenario === "fork" ? "fork" : scenario === "unrelated" ? null : "subagent",+ scenario === "fork" || scenario === "side-chat"+ ? "fork"+ : scenario === "unrelated"+ ? null+ : "subagent",+ ...(scenario === "side-chat" ? { sideChat: true } : {}),},status: scenario === "running" ? "running" : "completed",pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [],@@ -808,7 +814,9 @@ describe("subagent worktree ownership", () => {root,]);const report = yield* fixture.service.runNow;- const removed = ["idle", "grandchild", "isolated-owner", "fork-owner"].includes(scenario);+ const removed = ["idle", "grandchild", "isolated-owner", "fork-owner", "side-chat"].includes(+ scenario,+ );const shared = ["unrelated","fork",diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.tsindex b9f1e1f8395..580d520e318 100644--- a/apps/server/src/storageCleanup.ts+++ b/apps/server/src/storageCleanup.ts@@ -144,7 +144,7 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu);}-/** Only a complete subagent chain within this worktree shares ownership. */+/** Only a complete subagent or side chat chain within this worktree shares ownership. */function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineage">>(threads: ReadonlyArray<T>,) {@@ -159,7 +159,8 @@ function worktreeOwner<T extends Pick<OrchestrationV2ThreadShell, "id" | "lineagwhile (current.id !== owner.id) {if (seen.has(current.id) ||- current.lineage.relationshipToParent !== "subagent" ||+ (current.lineage.relationshipToParent !== "subagent" &&+ current.lineage.sideChat !== true) ||current.lineage.rootThreadId !== owner.lineage.rootThreadId)return undefined;diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.tsindex 109776a091e..9c4a6c803ff 100644--- a/apps/web/src/browser/openFileInPreview.ts+++ b/apps/web/src/browser/openFileInPreview.ts@@ -24,7 +24,11 @@ import {setActivePreviewTab,updatePreviewServerSnapshot,} from "~/previewStateStore";-import { selectSelectedRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";+import {+ rightPanelHostRef,+ selectSelectedRightPanelSurface,+ useRightPanelStore,+} from "~/rightPanelStore";import { resolveBrowserDefaults } from "./browserDefaults";@@ -57,23 +61,25 @@ export async function openUrlInPreview<E>(input: {readonly profileId?: PreviewOpenInput["profileId"];readonly background?: boolean;}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {+ // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping.+ const threadRef = rightPanelHostRef(input.threadRef);const defaults = await resolveBrowserDefaults().catch((cause: unknown) => new BrowserSettingsReadError({ cause }),);if (defaults instanceof BrowserSettingsReadError) {return AsyncResult.failure(Cause.fail(defaults));}- const runtime = previewRuntimeFor(input.threadRef.environmentId);- const previousActiveTabId = readThreadPreviewState(input.threadRef).activeTabId;+ const runtime = previewRuntimeFor(threadRef.environmentId);+ const previousActiveTabId = readThreadPreviewState(threadRef).activeTabId;// The server changes the active tab, not panel selection; selection changes come from the user.const selectedSurface = () =>- selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, input.threadRef)- ?.id ?? null;+ selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.id ??+ null;const surfaceBeforeOpen = selectedSurface();const result = await input.openPreview({- environmentId: input.threadRef.environmentId,+ environmentId: threadRef.environmentId,input: {- threadId: input.threadRef.threadId,+ threadId: threadRef.threadId,url: input.url,viewport: defaults.viewport,profileId: input.profileId ?? defaults.profileId,@@ -81,21 +87,21 @@ export async function openUrlInPreview<E>(input: {},});return mapAtomCommandResult(result, (snapshot) => {- rememberPreviewUrl(input.threadRef, input.url);+ rememberPreviewUrl(threadRef, input.url);if (input.background) {- updatePreviewServerSnapshot(input.threadRef, snapshot);+ updatePreviewServerSnapshot(threadRef, snapshot);// Restore focus unless the user picked a tab while opening this one.if (previousActiveTabId &&- readThreadPreviewState(input.threadRef).activeTabId === snapshot.tabId &&+ readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&selectedSurface() === surfaceBeforeOpen) {- setActivePreviewTab(input.threadRef, previousActiveTabId);+ setActivePreviewTab(threadRef, previousActiveTabId);}return;}- applyPreviewServerSnapshot(input.threadRef, snapshot);- useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);+ applyPreviewServerSnapshot(threadRef, snapshot);+ useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);});}@@ -124,6 +130,7 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {),);}+ const hostRef = rightPanelHostRef(input.threadRef);const insideWorkspace =mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;const assetResult = await input.createAssetUrl({@@ -146,7 +153,7 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {);}return openUrlInPreview({- threadRef: input.threadRef,+ threadRef: hostRef,url: assetUrl,openPreview: input.openPreview,});diff --git a/apps/web/src/closedViewStore.test.ts b/apps/web/src/closedViewStore.test.tsindex 0223dfb9d5b..3e2cacc57e7 100644--- a/apps/web/src/closedViewStore.test.ts+++ b/apps/web/src/closedViewStore.test.ts@@ -54,6 +54,12 @@ describe("closedViewStore", () => {threadRef: refA,surface: { kind: "pull-request", id: "pull-request:x", repository: "owner/repo", number: 1 },},+ {+ id: "bad",+ kind: "panel-tab",+ threadRef: refA,+ surface: { kind: "side-chat", id: "side-chat:x" },+ },])("discards incomplete saved views %j while retaining valid history", async (entry) => {const id = useClosedViewStore.getState().remember(diff(refA));const { storage, name } = useClosedViewStore.persist.getOptions();@@ -85,6 +91,11 @@ describe("closedViewStore", () => {it("removes private metadata and malformed entries from history saved by earlier versions", async () => {const store = useClosedViewStore.getState();+ const sideChatId = store.remember({+ kind: "panel-tab",+ threadRef: refA,+ surface: { id: "side-chat:side", kind: "side-chat", threadId: ThreadId.make("side") },+ });const publicId = store.remember(diff(refA));const browserId = store.remember({kind: "browser",@@ -115,6 +126,7 @@ describe("closedViewStore", () => {expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([browserId,publicId,+ sideChatId,]);const saved = JSON.stringify(await storage!.getItem(name!));expect(saved).not.toContain("private.example");diff --git a/apps/web/src/closedViewStore.ts b/apps/web/src/closedViewStore.tsindex 76fee83a83d..b5db7bd741b 100644--- a/apps/web/src/closedViewStore.ts+++ b/apps/web/src/closedViewStore.ts@@ -83,6 +83,8 @@ const isClosedViewEntry = (entry: unknown): entry is ClosedViewEntry => {typeof surface.target.name === "string" &&(surface.target.platform === "ios" || surface.target.platform === "android"))));+ case "side-chat":+ return typeof surface.threadId === "string" && surface.id === `side-chat:${surface.threadId}`;case "pull-request":return (typeof surface.projectId === "string" &&diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsxindex 82c280e6e56..3176c8132ee 100644--- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx+++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx@@ -1,5 +1,6 @@import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";+import { isListedThreadLineage } from "@t3tools/contracts";import type { AnyRouter } from "@tanstack/react-router";import type { AtomRegistry } from "effect/reactivity";@@ -42,9 +43,8 @@ export function startBackgroundThreadAnnouncements(const now = new Date().toISOString();const snapshots: BackgroundThreadSnapshot[] = [];for (const thread of threads) {- // Subagents have no row of their own; their requests surface on the parent.- if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")- continue;+ // Subagents and side chats have no row of their own; their requests surface on the parent.+ if (thread.archivedAt !== null || !isListedThreadLineage(thread.lineage)) continue;if (!liveEnvironmentIds.has(thread.environmentId)) continue;snapshots.push({key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 63ff8b8463e..22ccaaaf807 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -61,6 +61,7 @@ import {type AssistantCitation,type ChatFileAttachment,isProviderNativeSubagentThread,+ orchestrationV2WorktreePending,type EnvironmentId,type MessageId,type ModelSelection,@@ -187,6 +188,7 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";import { toastManager } from "./ui/toast";import { projectScriptIdFromCommand } from "~/projectScripts";import { newMessageId } from "~/lib/utils";+import { isInSideChatPane, type SideChatParentPanel } from "~/lib/sideChatPane";import {NO_PROVIDER_MODEL_SELECTION,providerInstanceEntriesFor,@@ -273,6 +275,7 @@ import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";import { getTriggerDisplayModelName } from "./chat/providerIconUtils";import { resolveScrollToEndClearance } from "./composerFooterLayout";import { ChatHeader } from "./chat/ChatHeader";+import { useSideChat } from "./chat/useSideChat";import { useRemoteOpenState } from "~/remoteOpen";import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic";import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut";@@ -390,6 +393,8 @@ type ChatViewProps =onDiffPanelOpen?: () => void;reserveTitleBarControlInset?: boolean;forceExpandedMobileComposer?: boolean;+ /** A side chat in its parent's right panel; the parent keeps the keyboard and workspace UI. */+ embedded?: SideChatParentPanel;routeKind: "server";draftId?: never;}@@ -399,6 +404,7 @@ type ChatViewProps =onDiffPanelOpen?: () => void;reserveTitleBarControlInset?: boolean;forceExpandedMobileComposer?: boolean;+ embedded?: never;routeKind: "draft";draftId: DraftId;};@@ -413,7 +419,9 @@ export default function ChatView(props: ChatViewProps) {onDiffPanelOpen,reserveTitleBarControlInset = true,forceExpandedMobileComposer = false,+ embedded: parentPanel,} = props;+ const embedded = parentPanel !== undefined;const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);const draftId = routeKind === "draft" ? props.draftId : null;@@ -866,7 +874,29 @@ export default function ChatView(props: ChatViewProps) {: scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);// The title it had at delegation, until this client sees the parent itself.const delegatedFromThread = useQuietThreadShell(delegatedFromRef);+ const sideChatParentRef =+ activeThread?.lineage.sideChat === true && activeThread.lineage.parentThreadId !== null+ ? scopeThreadRef(activeThread.environmentId, activeThread.lineage.parentThreadId)+ : null;+ const sideChatParent = useQuietThreadShell(sideChatParentRef);const parentThreadLink = (() => {+ if (sideChatParentRef !== null) {+ return {+ title: sideChatParent?.title ?? "Parent thread",+ sideChat: true,+ // Embedded, the parent is the view around it.+ ...(embedded+ ? {}+ : {+ open: (): void => {+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(sideChatParentRef),+ });+ },+ }),+ };+ }if (parentSubagentThreadRef !== null) {return {title: parentSubagentThread?.title ?? "Parent thread",@@ -1066,7 +1096,9 @@ export default function ChatView(props: ChatViewProps) {renderedRightPanelSurface,);const canMaximizeRightPanel = rightPanelOpen;- const rightPanelMaximized = canMaximizeRightPanel && rightPanelState.maximized === true;+ // An embedded side chat has no panel; a stale maximized flag would hide its own column.+ const rightPanelMaximized =+ !embedded && canMaximizeRightPanel && rightPanelState.maximized === true;const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;const [threadPanelPopoverHandle] = useState(PopoverCreateHandle);const [chatCanvasStore] = useState(createChatCanvasStore);@@ -1720,13 +1752,15 @@ export default function ChatView(props: ChatViewProps) {providerSubagentModels,reportedModelSelection,);- const showComposerContextStrip = shouldShowComposerContextStrip({- isDraftHeroState,- persistInActiveThreads: settings.persistComposerContextStrip,- hasActiveProject: activeProject !== null && !showProviderSubagentBar,- isGitRepo,- showEnvironmentIndicator: showComposerEnvironmentIndicator,- });+ const showComposerContextStrip =+ !embedded &&+ shouldShowComposerContextStrip({+ isDraftHeroState,+ persistInActiveThreads: settings.persistComposerContextStrip,+ hasActiveProject: activeProject !== null && !showProviderSubagentBar,+ isGitRepo,+ showEnvironmentIndicator: showComposerEnvironmentIndicator,+ });const terminalShortcutLabelOptions = {context: {terminalFocus: true,@@ -1807,7 +1841,10 @@ export default function ChatView(props: ChatViewProps) {};const onInterruptStable = useStableCallback(onInterrupt);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window listener for the desktop snapshot event that focuses the composer- useEffect(() => subscribeSnapShotComposerFocus(focusComposerStable), [focusComposerStable]);+ useEffect(+ () => (embedded ? undefined : subscribeSnapShotComposerFocus(focusComposerStable)),+ [embedded, focusComposerStable],+ );const scheduleComposerFocus = () => {window.requestAnimationFrame(() => {focusComposer();@@ -1968,8 +2005,8 @@ export default function ChatView(props: ChatViewProps) {: linkedThreadPullRequestKey;const activeRunningTurnId = activeRuntime?.activeRunId ?? null;useProactivePanels({- threadRef: isServerThread ? activeThreadRef : null,- enabled: settings.proactivePanelsEnabled && !shouldUsePlanSidebarSheet,+ threadRef: isServerThread && !embedded ? activeThreadRef : null,+ enabled: settings.proactivePanelsEnabled && !shouldUsePlanSidebarSheet && !embedded,settingsHydrated: clientSettingsHydrated,threadDetailLoading,runningTurnId: activeRunningTurnId,@@ -2100,18 +2137,18 @@ export default function ChatView(props: ChatViewProps) {// 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 closeduseEffect(() => {- if (!activeThread?.id || terminalUiState.terminalOpen) return;+ if (embedded || !activeThread?.id || terminalUiState.terminalOpen) return;const frame = window.requestAnimationFrame(() => {focusComposerStable();});return () => {window.cancelAnimationFrame(frame);};- }, [activeThread?.id, focusComposerStable, terminalUiState.terminalOpen]);+ }, [activeThread?.id, embedded, focusComposerStable, terminalUiState.terminalOpen]);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focususeEffect(() => {- if (!activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;+ if (embedded || !activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;let frame: number | null = null;const onWindowFocus = () => {if (frame !== null) window.cancelAnimationFrame(frame);@@ -2120,7 +2157,12 @@ export default function ChatView(props: ChatViewProps) {frame = window.requestAnimationFrame(() => {frame = null;if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return;- if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposerStable();+ if (+ !isInSideChatPane(document.activeElement) &&+ shouldRefocusComposerOnWindowFocus(document.activeElement)+ ) {+ focusComposerStable();+ }});});};@@ -2129,7 +2171,13 @@ export default function ChatView(props: ChatViewProps) {window.removeEventListener("focus", onWindowFocus);if (frame !== null) window.cancelAnimationFrame(frame);};- }, [activeThread?.id, focusComposerStable, isMobileViewport, terminalUiState.terminalOpen]);+ }, [+ activeThread?.id,+ embedded,+ focusComposerStable,+ isMobileViewport,+ terminalUiState.terminalOpen,+ ]);// Promotion drops draftId while a send may still be dispatching, so key by thread.const [localDispatchThreadId, setLocalDispatchThreadId] = useState(threadId);@@ -2334,6 +2382,7 @@ export default function ChatView(props: ChatViewProps) {pullRequestPanelTarget,threadPanelPresentation,isServerThread,+ embedded,isGitRepo,browserAvailable,canOperatePreview,@@ -2619,8 +2668,8 @@ export default function ChatView(props: ChatViewProps) {// composer effect above.// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the open drawer terminal when entering a threaduseEffect(() => {- if (activeThreadRef) return focusTerminalOnThreadEnter(activeThreadRef);- }, [activeThreadRef]);+ if (activeThreadRef && !embedded) return focusTerminalOnThreadEnter(activeThreadRef);+ }, [activeThreadRef, embedded]);const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({terminalFocus: getTerminalFocusOwner() !== null,@@ -2629,7 +2678,9 @@ export default function ChatView(props: ChatViewProps) {previewOpen: previewPanelOpen,editableFocus: isEditableFocused(eventTarget),modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,- composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor",+ composerFocus:+ document.activeElement?.getAttribute("data-testid") === "composer-editor" &&+ isInSideChatPane(document.activeElement) === embedded,draftThreadRoute: routeKind === "draft",turnRunning: phase === "running",composerRequiresModifier: composerRequiresModifier(settings.sendShortcut, promptRef.current),@@ -2650,6 +2701,8 @@ export default function ChatView(props: ChatViewProps) {useChatShortcuts({enabled: activeThreadId !== null && !backgroundThread,+ embedded,+ composerElement: composerOverlayElement,keybindings,scriptKeybindings,getShortcutContext,@@ -2704,13 +2757,56 @@ export default function ChatView(props: ChatViewProps) {// A focused desktop browser page forwards these chords as menu actions.// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle the right paneluseEffect(() => {+ if (embedded) return;return window.desktopBridge?.onMenuAction((action) => {if (action === "rightPanel.toggle") toggleRightPanelStable();else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable();});- }, [toggleRightPanelStable, toggleRightPanelMaximizedStable]);+ }, [embedded, toggleRightPanelStable, toggleRightPanelMaximizedStable]);- usePasteToFocusComposer(activeThreadId, composerRef);+ usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef);+ // A delegated task is a remote thread's subagent.+ const isSubagentThread =+ activeThread?.lineage.relationshipToParent === "subagent" || delegatedFrom !== null;+ // Side chats do not nest or start from subagents, and older servers would fork a listed thread.+ const sideChatsOffered =+ !embedded &&+ canOperateThread &&+ activeThread?.lineage.sideChat !== true &&+ !isSubagentThread &&+ serverConfig?.environment.capabilities.sideChats === true;+ const sideChat = useSideChat({+ threadRef: sideChatsOffered && isServerThread ? activeThreadRef : null,+ onError: (message) => {+ if (activeThread) setThreadError(activeThread.id, message);+ },+ });+ // A maximized panel covers the terminal drawer the command runs in.+ const runSideChatShellCommandStable = useStableCallback((command: string) => {+ if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false);+ runShellCommandStable(command);+ });+ // Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast.+ const sideChatDisabledReason =+ activeThread?.lineage.sideChat === true+ ? "Side chats cannot start side chats."+ : isSubagentThread+ ? "Subagent threads cannot start side chats."+ : serverConfig === null+ ? "Side chats are not ready yet. Try again in a moment."+ : serverConfig.environment.capabilities.sideChats !== true+ ? "Update this environment's T3 Code server to use side chats."+ : sideChatsOffered && !isServerThread+ ? "Side chats start after the first message."+ : sideChat.available &&+ orchestrationV2WorktreePending(+ activeThread?.worktreePath ?? null,+ serverProjection?.runs ?? [],+ )+ ? "Available once the thread's worktree is set up."+ : null;+ const openSideChatStable = useStableCallback(() => void sideChat.open());+ const sendSideChatStable = useStableCallback((prompt: string) => sideChat.open(prompt));const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } =useTimelineRewind({environmentId,@@ -2873,6 +2969,8 @@ export default function ChatView(props: ChatViewProps) {anchorNewTurn,acknowledgeActiveThreadWoke,handleInteractionModeChange,+ onSideChat: sideChat.available ? sendSideChatStable : undefined,+ sideChatDisabledReason,handleNewThreadInActiveProject,persistThreadSettingsForNextTurn,});@@ -3011,10 +3109,7 @@ export default function ChatView(props: ChatViewProps) {!serverProjection?.messages.some((committed) => committed.id === message.id),);const scrollToEndSummary =- [- childInputNow === null ? null : "Subagent waiting",- queuedRunCount === 0 ? null : `${queuedRunCount} queued`,- ]+ [childInputNow?.waitingLabel ?? null, queuedRunCount === 0 ? null : `${queuedRunCount} queued`].filter((part) => part !== null).join(" · ") || null;// 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) {);if (!activeThread) {- return <NoActiveThreadState />;+ return embedded ? null : <NoActiveThreadState />;}const rightPanelContent = activeThreadRef ? (@@ -3116,6 +3211,10 @@ export default function ChatView(props: ChatViewProps) {getShortcutContext={getShortcutContextStable}onSendAnnotation={sendPreviewAnnotationStable}onCloseSurface={closeRightPanelSurface}+ sideChatParentPanel={{+ openToolDiff: onOpenToolDiffStable,+ runShellCommand: runSideChatShellCommandStable,+ }}terminal={{launchContext: activeTerminalLaunchContext ?? null,keybindings,@@ -3196,12 +3295,14 @@ export default function ChatView(props: ChatViewProps) {ref={setWorkspaceLayoutElement}className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">- <DeviceSetupDialogHost- threadKey={activeThreadKey}- threadRef={activeThreadRef}- state={deviceState}- />- {rightPanelControlsAtRoot ? panelLayoutControls : null}+ {embedded ? null : (+ <DeviceSetupDialogHost+ threadKey={activeThreadKey}+ threadRef={activeThreadRef}+ state={deviceState}+ />+ )}+ {rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}<divclassName={cn("flex min-h-0 min-w-0 flex-col overflow-x-hidden",@@ -3211,47 +3312,49 @@ export default function ChatView(props: ChatViewProps) {data-chat-columninert={rightPanelMaximized}>- <header- ref={threadPanelPopoverAnchorRef}- data-chat-header- className={cn(- "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",- isElectron- ? cn(- "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",- reserveTitleBarControlInset &&- !inlineRightPanelOwnsTitleBar &&- "wco:pr-(--workspace-native-controls-inset)",- )- : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-(--workspace-gutter-start) pr-(--workspace-gutter-end)",- COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,- )}- >- {isElectron && rightPanelControlsAtRoot ? (- <span- aria-hidden- 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]"+ {embedded ? null : (+ <header+ ref={threadPanelPopoverAnchorRef}+ data-chat-header+ className={cn(+ "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",+ isElectron+ ? cn(+ "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",+ reserveTitleBarControlInset &&+ !inlineRightPanelOwnsTitleBar &&+ "wco:pr-(--workspace-native-controls-inset)",+ )+ : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-(--workspace-gutter-start) pr-(--workspace-gutter-end)",+ COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,+ )}+ >+ {isElectron && rightPanelControlsAtRoot ? (+ <span+ aria-hidden+ 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]"+ />+ ) : null}+ {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}+ {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}+ <ChatHeader+ activeThreadEnvironmentId={activeThread.environmentId}+ activeThreadId={activeThread.id}+ isServerThread={isServerThread}+ activeThreadTitle={activeThread.title}+ activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}+ activeProject={activeProject ?? null}+ parentThreadLink={headerParentThreadLink}+ onOpenThread={onOpenRelatedThreadStable}+ rightPanelOpen={inlineRightPanelOwnsTitleBar}+ onNewThreadInProject={handleNewThreadInActiveProjectStable}+ {...(activeDraftLogicalProjectKey+ ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }+ : {})}+ {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}/>- ) : null}- {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}- {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}- <ChatHeader- activeThreadEnvironmentId={activeThread.environmentId}- activeThreadId={activeThread.id}- isServerThread={isServerThread}- activeThreadTitle={activeThread.title}- activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}- activeProject={activeProject ?? null}- parentThreadLink={headerParentThreadLink}- onOpenThread={onOpenRelatedThreadStable}- rightPanelOpen={inlineRightPanelOwnsTitleBar}- onNewThreadInProject={handleNewThreadInActiveProjectStable}- {...(activeDraftLogicalProjectKey- ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }- : {})}- {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}- />- </header>+ </header>+ )}<div className="relative flex min-h-0 min-w-0 flex-1"><ThreadFindCanvas@@ -3310,7 +3413,9 @@ export default function ChatView(props: ChatViewProps) {citationRequest={citationRequest}citationHistory={citationHistory}onCiteAssistantText={citeAssistantTextStable}- {...(activeProject ? { onRunShellCommand: runShellCommandStable } : {})}+ {...(activeProject+ ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }+ : {})}isWorking={isWorking}runlessWorkActive={runlessWorkStartedAt !== null}isCompacting={isCompacting}@@ -3353,12 +3458,14 @@ export default function ChatView(props: ChatViewProps) {routeThreadKey={displayedTimelineKey}displayThreadKey={displayedTimelineKey}announceTurnStatus={!isProviderSubagent}- onOpenToolDiff={onOpenToolDiffStable}- onOpenTurnDiff={onOpenTurnDiffStable}+ onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}+ // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.+ {...(embedded+ ? {}+ : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}onOpenThread={onOpenRelatedThreadStable}parentThreadLink={parentThreadLink}workflowOpening={workflowOpening}- onForkFromRun={onForkFromRunStable}supportsConversationRollback={supportsConversationRollback}threadStartCheckpointReady={threadStartCheckpointReady}availableRevertTurnCounts={availableRevertTurnCounts}@@ -3529,6 +3636,8 @@ export default function ChatView(props: ChatViewProps) {resumeCompactionTokens={resumeCompactionTokens}keepFullHistory={keepFullHistory}onToggleKeepFullHistory={toggleKeepFullHistoryStable}+ sideChatAvailable={sideChat.available}+ sideChatDisabledReason={sideChatDisabledReason}onUsageLimitsCommand={usageLimitsOffered &&usageLimitsKey !== null &&@@ -3707,10 +3816,10 @@ export default function ChatView(props: ChatViewProps) {</div></div>- {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser ? (+ {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser && !embedded ? (<PreviewSessionSync threadRef={activeThreadRef} />) : null}- {activeThreadRef && shownPreviewMiniPlayer ? (+ {activeThreadRef && shownPreviewMiniPlayer && !embedded ? (<ThreadPreviewMiniPlayerkey={`${activeThreadKey}:${previewMiniPlayerSourceKey(shownPreviewMiniPlayer.source)}`}threadRef={activeThreadRef}@@ -3718,106 +3827,114 @@ export default function ChatView(props: ChatViewProps) {/>) : null}- <BranchRestoreConfirmHost- threadKey={activeThreadKey}- threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}- canWriteSourceControl={canWriteSourceControl}- onConfirm={handleSwitchCheckoutToThreadStable}- />+ {embedded ? null : (+ <>+ <BranchRestoreConfirmHost+ threadKey={activeThreadKey}+ threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}+ canWriteSourceControl={canWriteSourceControl}+ onConfirm={handleSwitchCheckoutToThreadStable}+ />- <ThreadDetailsPanel- anchor={threadPanelPopoverAnchorRef}- handle={threadPanelPopoverHandle}- forceNewWorktree={multipleModelSelections !== null}- environmentId={activeThread.environmentId}- threadId={activeThread.id}- projectId={activeThread.projectId}- worktreePath={activeThread.worktreePath}- isServerThread={isServerThread}- {...(draftId ? { draftId } : {})}- activeProjectName={activeProject?.title}- activeProjectScripts={activeProject ? activeProjectScripts : undefined}- preferredScriptId={- activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null- }- keybindings={keybindings}- availableEditors={availableEditors}- showOpenInPicker={showOpenInPicker}- openInShortcutEnabled={- !(- rightPanelOpen &&- renderedRightPanelSurface?.kind === "file" &&- renderedRightPanelSurface.attachment === undefined- )- }- gitCwd={gitCwd}- isGitRepo={isGitRepo}- envLocked={envLocked}- availableEnvironments={logicalProjectEnvironments}- autoEnvironmentLabel={autoEnvironmentLabel}- onAutoEnvironment={- draftId &&- !envLocked &&- canAutoBalanceEnvironments &&- loadBalancingSettings.loadBalancingEnabled- ? onAutoEnvironmentStable- : undefined- }- {...(canChangeEnvironment ? { onEnvironmentChange: onEnvironmentChangeStable } : {})}- onEnvModeChange={onEnvModeChangeStable}- envMode={envMode}- {...(canOverrideServerThreadEnvMode- ? {- activeThreadBranchOverride: activeThreadBranch,- onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,+ <ThreadDetailsPanel+ anchor={threadPanelPopoverAnchorRef}+ handle={threadPanelPopoverHandle}+ forceNewWorktree={multipleModelSelections !== null}+ environmentId={activeThread.environmentId}+ threadId={activeThread.id}+ projectId={activeThread.projectId}+ worktreePath={activeThread.worktreePath}+ isServerThread={isServerThread}+ {...(draftId ? { draftId } : {})}+ activeProjectName={activeProject?.title}+ activeProjectScripts={activeProject ? activeProjectScripts : undefined}+ preferredScriptId={+ activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null}- : {})}- startFromOrigin={startFromOrigin}- onStartFromOriginChange={onStartFromOriginChange}- {...(canCheckoutPullRequestIntoThread- ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }- : {})}- onComposerFocusRequest={scheduleComposerFocusStable}- {...(isServerThread && isGitRepo- ? { onOpenChanges: openChangesFromThreadPanelStable }- : {})}- onRunProjectScript={runProjectScriptStable}- onAddProjectScript={saveProjectScriptStable}- onUpdateProjectScript={updateProjectScriptStable}- onDeleteProjectScript={deleteProjectScriptStable}- usage={{- providerInstanceId: activeProviderInstanceId,- providers: providerStatuses,- sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,- contextWindow: activeContextWindow,- }}- />+ keybindings={keybindings}+ availableEditors={availableEditors}+ showOpenInPicker={showOpenInPicker}+ openInShortcutEnabled={+ !(+ rightPanelOpen &&+ renderedRightPanelSurface?.kind === "file" &&+ renderedRightPanelSurface.attachment === undefined+ )+ }+ gitCwd={gitCwd}+ isGitRepo={isGitRepo}+ envLocked={envLocked}+ availableEnvironments={logicalProjectEnvironments}+ autoEnvironmentLabel={autoEnvironmentLabel}+ onAutoEnvironment={+ draftId &&+ !envLocked &&+ canAutoBalanceEnvironments &&+ loadBalancingSettings.loadBalancingEnabled+ ? onAutoEnvironmentStable+ : undefined+ }+ {...(canChangeEnvironment+ ? { onEnvironmentChange: onEnvironmentChangeStable }+ : {})}+ onEnvModeChange={onEnvModeChangeStable}+ envMode={envMode}+ {...(canOverrideServerThreadEnvMode+ ? {+ activeThreadBranchOverride: activeThreadBranch,+ onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,+ }+ : {})}+ startFromOrigin={startFromOrigin}+ onStartFromOriginChange={onStartFromOriginChange}+ {...(canCheckoutPullRequestIntoThread+ ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }+ : {})}+ onComposerFocusRequest={scheduleComposerFocusStable}+ {...(isServerThread && isGitRepo+ ? { onOpenChanges: openChangesFromThreadPanelStable }+ : {})}+ onRunProjectScript={runProjectScriptStable}+ onAddProjectScript={saveProjectScriptStable}+ onUpdateProjectScript={updateProjectScriptStable}+ onDeleteProjectScript={deleteProjectScriptStable}+ usage={{+ providerInstanceId: activeProviderInstanceId,+ providers: providerStatuses,+ sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,+ contextWindow: activeContextWindow,+ }}+ />- <PullRequestThreadDialogHost- threadKey={activeThreadKey}- environmentId={activeThread.environmentId}- threadId={activeThread.id}- cwd={activeProject?.workspaceRoot ?? null}- onPrepared={handlePreparedPullRequestThreadStable}- />+ <PullRequestThreadDialogHost+ threadKey={activeThreadKey}+ environmentId={activeThread.environmentId}+ threadId={activeThread.id}+ cwd={activeProject?.workspaceRoot ?? null}+ onPrepared={handlePreparedPullRequestThreadStable}+ />+ </>+ )}</ThreadFindCanvas></div>- <ChatTerminalDrawers- activeThreadKey={activeThreadKey}- activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}- composerHeight={composerReservedHeight}- launchContext={activeTerminalLaunchContext ?? null}- splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}- splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}- newShortcutLabel={newTerminalShortcutLabel ?? undefined}- closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}- keybindings={keybindings}- onAddTerminalContext={addTerminalContextToDraftStable}- />+ {embedded ? null : (+ <ChatTerminalDrawers+ activeThreadKey={activeThreadKey}+ activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}+ composerHeight={composerReservedHeight}+ launchContext={activeTerminalLaunchContext ?? null}+ splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}+ splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}+ newShortcutLabel={newTerminalShortcutLabel ?? undefined}+ closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}+ keybindings={keybindings}+ onAddTerminalContext={addTerminalContextToDraftStable}+ />+ )}</div>- {rightPanelPresent && activeThreadRef ? (+ {rightPanelPresent && activeThreadRef && !embedded ? (<ChatRightPanelsheet={shouldUsePlanSidebarSheet}workspaceLayoutElement={workspaceLayoutElement}@@ -3866,6 +3983,7 @@ export default function ChatView(props: ChatViewProps) {onAddPullRequest={addPullRequestSurfaceStable}onAddPullRequests={addPullRequestsSurfaceStable}onAddDevice={addDeviceSurfaceStable}+ onAddSideChat={sideChatsOffered ? openSideChatStable : undefined}browserAvailable={canOperatePreview && browserAvailable}terminalAvailable={activeProject !== null && canOperateTerminal}diffAvailable={isServerThread && isGitRepo}@@ -3873,13 +3991,15 @@ export default function ChatView(props: ChatViewProps) {pullRequestAvailable={pullRequestSurfaceAvailable}pullRequestsAvailable={pullRequestsSurfaceAvailable}deviceAvailable={activeThreadRef !== null}+ sideChatAvailable={sideChat.available}+ sideChatDisabledReason={sideChatDisabledReason}>{rightPanelContent}</ChatRightPanel>) : null}<RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />- <LinkPullRequestDialogHost />+ {embedded ? null : <LinkPullRequestDialogHost />}<ThreadVisitWatermark threadRef={routeThreadRef} /><ExpandedImageDialogHost threadKey={routeThreadKey} /></div>diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.tsindex 96d439252ac..f9b47f75180 100644--- a/apps/web/src/components/CommandPalette.logic.ts+++ b/apps/web/src/components/CommandPalette.logic.ts@@ -32,7 +32,7 @@ import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filimport { type ReactNode } from "react";import { formatRelativeTimeLabel } from "../timestampFormat";import { type Project, type SidebarThreadSummary, type Thread } from "../types";-import { isSidebarSubagentThread } from "./Sidebar.logic";+import { isSidebarHiddenThread } from "./Sidebar.logic";export const RECENT_THREAD_LIMIT = 12;export const ITEM_ICON_CLASS = "size-4 text-icon-muted";@@ -421,7 +421,7 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr}): CommandPaletteActionItem[] {// Callers order these: recents by last use, search results by rank.const visibleThreads = input.threads.filter(- (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread),+ (thread) => thread.archivedAt === null && !isSidebarHiddenThread(thread),);return visibleThreads.map((thread) => {diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsxindex f1b5520d421..ce187f5db5e 100644--- a/apps/web/src/components/ReopenClosedViewShortcut.tsx+++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx@@ -91,6 +91,7 @@ export function ReopenClosedViewShortcut() {environmentKnown: true,catalogReady: true,ownerExists: true,+ sideChatExists: true,shellLive: true,panel,};@@ -99,6 +100,10 @@ export function ReopenClosedViewShortcut() {environmentKnown: catalog.entries.has(ref.environmentId),catalogReady: catalog.isReady,ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null,+ sideChatExists:+ entry.kind !== "panel-tab" ||+ entry.surface.kind !== "side-chat" ||+ readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null,shellLive:appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live",panel,diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex d74e03ea842..596bdee96ad 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -1,6 +1,15 @@import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";-import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import {+ threadRuntimeIsActive,+ type EnvironmentThreadShell,+} from "@t3tools/client-runtime/state/shell";+import {+ useProjects,+ useQuietThreadShell,+ useServerConfigs,+ useThreadShells,+} from "~/state/entities";import {threadPullRequestKeysEqual,visibleThreadPullRequests,@@ -12,6 +21,7 @@ import type {ProjectId,PullRequestState,ResolvedKeybindingsConfig,+ ThreadId,} from "@t3tools/contracts";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import {@@ -33,6 +43,7 @@ import {FileDiff,Files,Globe2,+ MessagesSquare,Plus,TerminalSquare,} from "lucide-react";@@ -130,6 +141,8 @@ export interface RightPanelTabsProps {onAddPullRequest: () => void;onAddPullRequests: () => void;onAddDevice: () => void;+ /** Absent where side chats are not offered. */+ onAddSideChat?: (() => void) | undefined;browserAvailable: boolean;terminalAvailable: boolean;diffAvailable: boolean;@@ -137,6 +150,9 @@ export interface RightPanelTabsProps {pullRequestAvailable: boolean;pullRequestsAvailable: boolean;deviceAvailable: boolean;+ sideChatAvailable?: boolean;+ /** Overrides the default reason while side chats are available but cannot start. */+ sideChatDisabledReason?: string | null;pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;children: ReactNode;}@@ -163,6 +179,7 @@ const SURFACE_DISABLED_REASONS = {pullRequest: "This thread's branch has no pull request yet.",pullRequests: "No linked pull requests are available for this thread.",device: "Devices are only available from a thread.",+ sideChat: "Side chats start after the first message.",} as const;// Closed keepMounted popups must stop blocking shortcuts once their exit transition ends.@@ -187,6 +204,7 @@ const SURFACE_UNAVAILABLE_HINTS = {pullRequest: "No pull request on this branch yet.",pullRequests: "No linked pull requests available.",device: "Available from a thread.",+ sideChat: "Available after the first message.",} as const;type TabContextMenuAction =@@ -304,6 +322,8 @@ function RightPanelEmptyState(props: {onAddPullRequest: () => void;onAddPullRequests: () => void;onAddDevice: () => void;+ /** Absent where side chats are not offered. */+ onAddSideChat?: (() => void) | undefined;browserAvailable: boolean;terminalAvailable: boolean;diffAvailable: boolean;@@ -311,6 +331,8 @@ function RightPanelEmptyState(props: {pullRequestAvailable: boolean;pullRequestsAvailable: boolean;deviceAvailable: boolean;+ sideChatAvailable: boolean;+ sideChatDisabledReason: string | null;}) {const [highlight, setHighlight] = useState(-1);@@ -372,6 +394,19 @@ function RightPanelEmptyState(props: {disabledReason: SURFACE_UNAVAILABLE_HINTS.device,onClick: props.onAddDevice,},+ ...(props.onAddSideChat+ ? [+ {+ label: "Side chat",+ description: "Ask a side question while this thread keeps working.",+ icon: MessagesSquare,+ shortcut: "S",+ available: props.sideChatAvailable && !props.sideChatDisabledReason,+ disabledReason: props.sideChatDisabledReason ?? SURFACE_UNAVAILABLE_HINTS.sideChat,+ onClick: props.onAddSideChat,+ },+ ]+ : []),] as const;type SurfaceAction = (typeof actions)[number];@@ -557,6 +592,8 @@ function surfaceTitle(return "Pull requests";case "device":return surface.title ?? surface.target?.name ?? "Device";+ case "side-chat":+ return "Side chat";case "preview": {const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";@@ -645,6 +682,8 @@ function SurfaceIcon({);case "pull-requests":return <PullRequestGlyph.link className="size-3 shrink-0" />;+ case "side-chat":+ return <SideChatTabIcon environmentId={environmentId} threadId={surface.threadId} />;case "device":return surface.target?.platform === "ios" ? (<AppleIcon className="size-3 shrink-0" />@@ -656,6 +695,41 @@ function SurfaceIcon({}}+/** What a side chat tab's dot shows and its title's accessible name says. */+function sideChatTabState(shell: EnvironmentThreadShell | null) {+ if (shell === null) return null;+ if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") {+ return "needs approval";+ }+ if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") {+ return "needs input";+ }+ return threadRuntimeIsActive(shell.runtime) ? "running" : null;+}++// Static dots: a side chat tab can stay open for a whole run.+function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) {+ const state = sideChatTabState(+ useQuietThreadShell(+ props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId),+ ),+ );+ return (+ <>+ <MessagesSquare className="size-3 shrink-0" />+ {state === null ? null : (+ <span+ className={cn(+ "absolute -top-0.5 -right-0.5 size-1.5 rounded-full",+ state === "running" ? "bg-muted-foreground" : "bg-info",+ )}+ aria-hidden+ />+ )}+ </>+ );+}+export function resolvePullRequestTabLink(threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],environmentId: EnvironmentId | null,@@ -813,7 +887,6 @@ function RightPanelTab() {const {surface,- title,audio,audioRuntimeTabId,onActivate,@@ -827,6 +900,13 @@ function RightPanelTab(id: surface.id,disabled: props.dragDisabled,});+ const sideChatShell = useQuietThreadShell(+ surface.kind === "side-chat" && props.environmentId !== null+ ? scopeThreadRef(props.environmentId, surface.threadId)+ : null,+ );+ const title = sideChatShell?.title ?? props.title;+ const sideChatState = sideChatTabState(sideChatShell);const content = (<><PanelTabCloseButton label={`Close ${title}`} onClick={() => onClose(surface)}>@@ -896,6 +976,7 @@ function RightPanelTab(if (surface.kind === "device" && props.canRename) onStartRename(surface.id);}}className="cursor-pointer flex min-w-0 items-center"+ aria-label={sideChatState === null ? undefined : `${title}, ${sideChatState}`}onClick={() => onActivate(surface)}><span className="truncate">{title}</span>@@ -1066,6 +1147,18 @@ export function RightPanelTabs(props: RightPanelTabsProps) {disabledReason: SURFACE_DISABLED_REASONS.device,onClick: props.onAddDevice,},+ ...(props.onAddSideChat+ ? [+ {+ label: "Side chat",+ icon: MessagesSquare,+ shortcut: "S",+ available: props.sideChatAvailable === true && !props.sideChatDisabledReason,+ disabledReason: props.sideChatDisabledReason ?? SURFACE_DISABLED_REASONS.sideChat,+ onClick: props.onAddSideChat,+ },+ ]+ : []),] as const;const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {@@ -1440,6 +1533,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {onAddPullRequest={props.onAddPullRequest}onAddPullRequests={props.onAddPullRequests}onAddDevice={props.onAddDevice}+ onAddSideChat={props.onAddSideChat}browserAvailable={props.browserAvailable}terminalAvailable={props.terminalAvailable}diffAvailable={props.diffAvailable}@@ -1447,6 +1541,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {pullRequestAvailable={props.pullRequestAvailable}pullRequestsAvailable={props.pullRequestsAvailable}deviceAvailable={props.deviceAvailable}+ sideChatAvailable={props.sideChatAvailable === true}+ sideChatDisabledReason={props.sideChatDisabledReason ?? null}/>) : (props.childrendiff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 43c87f530e4..6648ab93d51 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -16,7 +16,12 @@ import {type ThreadSearchShell,} from "@t3tools/client-runtime/state/thread-search";import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";-import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";+import {+ isListedThreadLineage,+ type ContextMenuItem,+ type EnvironmentId,+ type ThreadId,+} from "@t3tools/contracts";import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";import type { AsyncResult } from "effect/reactivity";import {@@ -590,12 +595,12 @@ export async function archiveSelectedThreadEntries<return { archivedThreadKeys, mutationFailure: null, followupFailures };}-export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {- return thread.lineage.relationshipToParent === "subagent";+export function isSidebarHiddenThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {+ return !isListedThreadLineage(thread.lineage);}-// Subagent threads have no sidebar row, so an open subagent is represented by-// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,+// Subagent and side-chat threads have no sidebar row, so an open one is represented by+// its nearest listed ancestor. A broken chain (missing parent, cycle,// other environment) resolves to the thread itself, which then matches no row.export function resolveSidebarRowThreadId(threadId: ThreadId,@@ -606,7 +611,7 @@ export function resolveSidebarRowThreadId(threads.find((thread) => thread.id === id && thread.environmentId === environmentId);const visited = new Set<ThreadId>();let thread = findThread(threadId);- while (thread !== undefined && isSidebarSubagentThread(thread)) {+ while (thread !== undefined && isSidebarHiddenThread(thread)) {if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;visited.add(thread.id);thread = findThread(thread.lineage.parentThreadId);diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsxindex 9280b9cbc06..6eed862ed7a 100644--- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx+++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx@@ -5,7 +5,7 @@ import {type ScopedThreadRef,} from "@t3tools/contracts";import { QuoteIcon } from "lucide-react";-import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { use, useEffect, useLayoutEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import {captureAssistantTextSelection,@@ -18,6 +18,7 @@ import {type SelectionActionPoint,} from "~/lib/selectionActions";import { Button } from "../ui/button";+import { BackgroundThreadContext } from "./backgroundThread";export function AssistantSelectionToolbar({viewport,@@ -35,6 +36,7 @@ export function AssistantSelectionToolbar({} | null>(null);const toolbarRef = useRef<HTMLButtonElement>(null);const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);+ const backgroundThread = use(BackgroundThreadContext);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paintuseLayoutEffect(() => {@@ -163,7 +165,8 @@ export function AssistantSelectionToolbar({event.stopPropagation();toolbar.focus({ preventScroll: true });};- document.addEventListener("keydown", focusActions, true);+ // Tab belongs to the foreground chat; a background timeline only follows its selection.+ if (!backgroundThread) document.addEventListener("keydown", focusActions, true);document.addEventListener("selectionchange", actions.selectionChanged);return () => {document.removeEventListener("keydown", focusActions, true);@@ -171,7 +174,7 @@ export function AssistantSelectionToolbar({actions.dispose();actionsRef.current = null;};- }, [threadRef, viewport]);+ }, [backgroundThread, threadRef, viewport]);if (!selection) return null;const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex c4963ad73ba..6e2455bb340 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -1,6 +1,7 @@import { useComposerTypingGuard } from "./useComposerTypingGuard";import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences";import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";+import { BackgroundThreadContext } from "./backgroundThread";import {resolveCompatibleRuntimeMode,runtimeModeConfig,@@ -52,6 +53,7 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";import {memo,+ use,useEffect,useEffectEvent,useId,@@ -381,6 +383,8 @@ export interface ChatComposerProps {keepFullHistory: boolean;onToggleKeepFullHistory: () => void;onUsageLimitsCommand?: (() => void) | undefined;+ sideChatAvailable?: boolean;+ sideChatDisabledReason?: string | null;environmentUnavailable: {readonly label: string;readonly connection: EnvironmentConnectionPresentation;@@ -1045,14 +1049,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isRevertingCheckpointRef.current = isRevertingCheckpoint;});- // 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+ const backgroundThread = use(BackgroundThreadContext);+ // 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 pasteuseEffect(() => {+ // A background composer listens on its own form, so it never hears the main composer's keys.+ const target: EventTarget | null = backgroundThread ? composerFormRef.current : window;+ if (target === null) return;const armPasteAsTextShortcut = () => {// Electron's menu action can precede paste; browsers deliver keydown first.pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;};- const onKeyDown = (event: KeyboardEvent) => {+ const onKeyDown = (event: Event) => {if (+ event instanceof KeyboardEvent &&event.target instanceof Node &&composerFormRef.current?.contains(event.target) &&isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))@@ -1070,22 +1079,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)activeElement.closest('input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]',) !== null;+ // A background composer takes no paste-to-focus, so it arms only for its own focus.if ((activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) ||- !blocksPasteToFocus+ (!blocksPasteToFocus && !backgroundThread)) {armPasteAsTextShortcut();}};- window.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);- window.addEventListener("keydown", onKeyDown, true);- window.addEventListener("blur", onBlur);+ target.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);+ target.addEventListener("keydown", onKeyDown, true);+ // An arm lasts a second, so a background composer can skip the window blur reset.+ if (!backgroundThread) window.addEventListener("blur", onBlur);return () => {- window.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);- window.removeEventListener("keydown", onKeyDown, true);+ target.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);+ target.removeEventListener("keydown", onKeyDown, true);window.removeEventListener("blur", onBlur);};- }, []);+ }, [backgroundThread]);const composerSendState = deriveComposerSendState({prompt,@@ -1120,6 +1131,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)pullRequestRepository,threadPullRequests,planModeUiEnabled,+ sideChatAvailable: props.sideChatAvailable === true,+ sideChatDisabledReason: props.sideChatDisabledReason ?? null,compactSlashCommandAvailable,selectedProvider,selectedProviderSkills,@@ -1848,6 +1861,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)}return;}+ if (item.command === "side" || item.command === "btw") {+ if (props.sideChatDisabledReason) return;+ const applied = applyPromptReplacement(+ trigger.rangeStart,+ trigger.rangeEnd,+ `/${item.command} `,+ { expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd) },+ );+ if (applied) setComposerHighlightedItemId(null);+ return;+ }if (!planModeUiEnabled) return;void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsxindex 60ee931fe5f..37a002e2c27 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx@@ -9,6 +9,7 @@ import { CheckboxMark } from "../ui/checkbox";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";import { Kbd } from "../ui/kbd";import { cn } from "~/lib/utils";+import { isInSideChatPane } from "~/lib/sideChatPane";import { ComposerBanner } from "./ComposerBanner";import ChatMarkdown from "../ChatMarkdown";@@ -151,6 +152,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(const handler = (event: globalThis.KeyboardEvent) => {if (event.metaKey || event.ctrlKey || event.altKey) return;const target = event.target;+ if (isInSideChatPane(target)) return;if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {return;}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 8c779ee950d..4c281637660 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -53,7 +53,13 @@ import {import { type PendingApproval, type TimelineEntry } from "../../session-logic";import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";-import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react";+import {+ ArrowRightIcon,+ BotIcon,+ CircleAlertIcon,+ MessagesSquareIcon,+ Minimize2Icon,+} from "lucide-react";import { ChevronDown, ChevronRight } from "lucide";import { MorphIcon } from "~/components/MorphIcon";import { Skeleton } from "../ui/skeleton";@@ -251,9 +257,14 @@ interface MessagesTimelineProps {onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];turnItemSource?: TimelineRowSharedState["turnItemSource"];- /** The thread this one is a subagent of; `open` is absent when it cannot be opened from here. */+ /**+ * The thread this one is a subagent or side chat of; `open` is absent when it cannot be+ * opened from here.+ */parentThreadLink?: {readonly title: string;+ /** A side chat's inherited rows collapse into this link. */+ readonly sideChat?: boolean;/** Where it runs, when that is another environment. */readonly environmentLabel?: string;readonly open?: () => void;@@ -1098,13 +1109,13 @@ const ConversationTimeline = memo(function ConversationTimeline({<div className="messages-timeline-row-frame"><div className="chat-content-lane pt-1 sm:pt-2"><TimelineSystemDivider- label="Subagent of"+ label={parentThreadLink.sideChat ? "Context from" : "Subagent of"}detail={parentThreadLink.environmentLabel === undefined? parentThreadLink.title: `${parentThreadLink.title} on ${parentThreadLink.environmentLabel}`}- icon={BotIcon}+ icon={parentThreadLink.sideChat ? MessagesSquareIcon : BotIcon}{...(parentThreadLink.open === undefined? {}: { actionLabel: "Open parent thread", onAction: parentThreadLink.open })}diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsxindex 7abe1406989..6ca50c824cb 100644--- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx+++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx@@ -10,8 +10,10 @@ import type {} from "@t3tools/contracts";import { scopedThreadKey } from "@t3tools/client-runtime/environment";import { lazy, Suspense } from "react";+import SideChatPane from "./SideChatPane";import type { ComposerImageAttachment, DraftId } from "../../composerDraftStore";import type { ShortcutMatchContext } from "../../keybindings";+import type { SideChatParentPanel } from "../../lib/sideChatPane";import { type RightPanelSurface, useRightPanelStore } from "../../rightPanelStore";import {PersistentThreadTerminalPanel,@@ -75,6 +77,7 @@ export function RightPanelSurfaceContent(props: {readonly terminal: RightPanelTerminalProps;readonly pullRequest: RightPanelPullRequestProps;readonly files: RightPanelFileProps;+ readonly sideChatParentPanel: SideChatParentPanel;}) {const { surface, threadRef, visible } = props;if (surface === null) return null;@@ -165,6 +168,17 @@ export function RightPanelSurfaceContent(props: {}case "pull-requests":return <ThreadPullRequestsPanel threadRef={threadRef} />;+ case "side-chat":+ // Not lazy: revealing a suspended tiptap editor tears down its view and crashes the composer.+ return (+ <SideChatPane+ key={surface.id}+ parentRef={threadRef}+ threadId={surface.threadId}+ parentPanel={props.sideChatParentPanel}+ onClose={() => props.onCloseSurface(surface)}+ />+ );case "device":return (<Suspense fallback={null}>diff --git a/apps/web/src/components/chat/SideChatPane.tsx b/apps/web/src/components/chat/SideChatPane.tsxnew file mode 100644index 00000000000..1a5bd1141b3--- /dev/null+++ b/apps/web/src/components/chat/SideChatPane.tsx@@ -0,0 +1,179 @@+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";+import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";+import {+ isAtomCommandInterrupted,+ settlePromise,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import {+ AuthOrchestrationOperateScope,+ type ScopedThreadRef,+ type ThreadId,+} from "@t3tools/contracts";+import { Trash2Icon, XIcon } from "lucide-react";+import { useEffect, useState } from "react";++import { ComposerHandleContext } from "../../composerHandleContext";+import { useClientSettings } from "../../hooks/useSettings";+import type { SideChatParentPanel } from "../../lib/sideChatPane";+import { readLocalApi } from "../../localApi";+import { hostRightPanel, useRightPanelStore } from "../../rightPanelStore";+import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities";+import { useEnvironmentScope } from "../../state/session";+import { useEnvironmentShellHasSnapshot } from "../../state/shell";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import ChatView from "../ChatView";+import { Button } from "../ui/button";+import { toastManager } from "../ui/toast";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import { BackgroundThreadContext } from "./backgroundThread";++/** A side chat tab: its title, Bring back, Delete and Close, over the side chat's own chat. */+export default function SideChatPane(props: {+ readonly parentRef: ScopedThreadRef;+ readonly threadId: ThreadId;+ readonly parentPanel: SideChatParentPanel;+ readonly onClose: () => void;+}) {+ const { parentRef, threadId } = props;+ const threadRef = scopeThreadRef(parentRef.environmentId, threadId);+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store+ useEffect(+ () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef),+ [parentRef, threadId],+ );+ const shell = useQuietThreadShell(threadRef);+ const parent = useQuietThreadShell(parentRef);+ const snapshotLoaded = useEnvironmentShellHasSnapshot(parentRef.environmentId);+ const projection = useQuietThreadProjection(shell === null ? null : threadRef)?.projection;+ const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope);+ const mergeBack = useAtomCommand(threadEnvironment.mergeBack, { reportFailure: false });+ const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });+ const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);+ const [bringingBack, setBringingBack] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const mergeRun = projection ? resolveLatestMergeBackRun(projection) : null;+ // A pending merge-back would fail the main thread's queued message, so the server refuses it.+ const bringBackBlockedReason = !canOperate+ ? "This connection cannot change threads."+ : threadRuntimeIsActive(parent?.runtime)+ ? "Available when the main thread is idle."+ : mergeRun === null+ ? "Available after a finished reply."+ : null;++ const bringBack = async () => {+ if (bringBackBlockedReason !== null || mergeRun === null || bringingBack) return;+ setBringingBack(true);+ const result = await mergeBack({+ environmentId: parentRef.environmentId,+ input: { sourceThreadId: threadId, targetThreadId: parentRef.threadId, runId: mergeRun.id },+ });+ setBringingBack(false);+ if (result._tag === "Success") {+ toastManager.add({+ type: "success",+ title: "Brought back",+ description: "The main thread gets this side chat with your next message there.",+ });+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: "Could not bring back the side chat",+ ...(error instanceof Error ? { description: error.message } : {}),+ });+ }+ };++ const deleteSideChat = async () => {+ if (!canOperate || shell === null || deleting) return;+ if (confirmThreadDelete) {+ const api = readLocalApi();+ if (!api) return;+ const confirmed = await settlePromise(() =>+ api.dialogs.confirm(+ [+ `Delete side chat "${shell.title}"?`,+ "This permanently clears its conversation history.",+ ].join("\n"),+ { variant: "destructive" },+ ),+ );+ if (confirmed._tag === "Failure" || !confirmed.value) return;+ }+ setDeleting(true);+ const result = await deleteThread({+ environmentId: parentRef.environmentId,+ input: { threadId },+ });+ setDeleting(false);+ if (result._tag === "Success") {+ useRightPanelStore.getState().closeSurface(parentRef, `side-chat:${threadId}`);+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: "Could not delete the side chat",+ ...(error instanceof Error ? { description: error.message } : {}),+ });+ }+ };++ return (+ <div data-side-chat-pane className="flex h-full min-h-0 flex-col">+ <div className="flex h-9 shrink-0 items-center gap-1 border-b border-border pr-1 pl-3">+ <span className="min-w-0 flex-1 truncate text-xs font-medium">+ {shell?.title ?? "Side chat"}+ </span>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="xs"+ aria-disabled={bringBackBlockedReason !== null || bringingBack || undefined}+ onClick={() => void bringBack()}+ >+ Bring back+ </Button>+ }+ />+ <TooltipPopup side="bottom">+ {bringBackBlockedReason ?? "Adds this side chat to the main thread's next message."}+ </TooltipPopup>+ </Tooltip>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Delete side chat"+ disabled={!canOperate || shell === null || deleting}+ onClick={() => void deleteSideChat()}+ >+ <Trash2Icon />+ </Button>+ <Button variant="ghost" size="icon-xs" aria-label="Close side chat" onClick={props.onClose}>+ <XIcon />+ </Button>+ </div>+ {shell === null ? (+ snapshotLoaded ? (+ <p className="p-3 text-xs text-muted-foreground">This side chat was deleted.</p>+ ) : null+ ) : (+ <BackgroundThreadContext value>+ <ComposerHandleContext value={null}>+ <ChatView+ environmentId={parentRef.environmentId}+ threadId={threadId}+ routeKind="server"+ embedded={props.parentPanel}+ />+ </ComposerHandleContext>+ </BackgroundThreadContext>+ )}+ </div>+ );+}diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsxindex 8bd26e21a04..4c0af2d3472 100644--- a/apps/web/src/components/chat/ThreadActivityBanners.tsx+++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx@@ -30,12 +30,12 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import type { ComposerBannerStackItem } from "./ComposerBannerStack";import type { ThreadNowItem } from "./ThreadNow";-/** Subagents waiting on the user, unless the parent is itself waiting on them. */+/** Subagents and side chats waiting on the user, unless the parent is itself waiting on them. */export function childInputNowItem(input: {readonly childThreadInputs: ReadonlyArray<EnvironmentThreadShell>;readonly parentAwaitingUser: boolean;readonly onOpenThread: (threadId: ThreadId) => void;-}): ThreadNowItem | null {+}): (ThreadNowItem & { readonly waitingLabel: string }) | null {const { childThreadInputs, onOpenThread } = input;const first = childThreadInputs[0];if (!first || input.parentAwaitingUser) return null;@@ -48,6 +48,9 @@ export function childInputNowItem(input: {<MessageCircleIcon className="text-info-foreground" />),title: childThreadInputsTitle(childThreadInputs),+ waitingLabel: childThreadInputs.every((child) => child.lineage.sideChat === true)+ ? "Side chat waiting"+ : "Subagent waiting",description: childThreadInputs.map((child, index) => (<Fragment key={child.id}>{index > 0 ? " " : null}diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsxindex a5df136f146..9ffbc90de75 100644--- a/apps/web/src/components/chat/ThreadDetailsCard.tsx+++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx@@ -78,10 +78,10 @@ export function ThreadDetailsCard({const measure = () => {const frame = element.closest<HTMLElement>("[data-thread-details-card]");const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0);- // PR lists and lineage scroll as they expand. Counting them toward density would hide- // the section and workspace controls when the user asks to see more rows.+ // PR lists, lineage and side chats scroll as they expand. Counting them toward density+ // would hide the section and workspace controls when the user asks to see more rows.const lists = element.querySelectorAll<HTMLElement>(- "[data-thread-relationships-panel], [data-thread-details-pr-list]",+ "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list]",);const fittingHeight =next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0);diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsxindex b8d96a33ec5..5c648016ff5 100644--- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx+++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx@@ -249,10 +249,12 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {/>) : null}- {density === "full" && !props.draftId && visible.lineage ? (+ {density === "full" && !props.draftId && (visible.lineage || visible.sideChats) ? (<ThreadRelationshipsPanelenvironmentId={props.environmentId}threadId={props.threadId}+ showLineage={visible.lineage}+ showSideChats={visible.sideChats}/>) : null}diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsxindex 88bd956decc..959d0ac724f 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx@@ -65,7 +65,12 @@ it.each([setup();await using screen = await render(<ToastProvider timeout={0}>- <ThreadRelationshipsPanel environmentId={environmentId} threadId={threadId} />+ <ThreadRelationshipsPanel+ environmentId={environmentId}+ threadId={threadId}+ showLineage+ showSideChats+ /></ToastProvider>,);@@ -93,7 +98,12 @@ it.each([setup();await using screen = await render(<ToastProvider timeout={0}>- <ThreadRelationshipsPanel environmentId={environmentId} threadId={threadId} />+ <ThreadRelationshipsPanel+ environmentId={environmentId}+ threadId={threadId}+ showLineage+ showSideChats+ /></ToastProvider>,{ router: "/environment/fork" },);diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsxindex 63a8635c066..b95ae4093a8 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx@@ -49,6 +49,7 @@ import {ChevronDownIcon,CornerLeftUpIcon,GitForkIcon,+ MessagesSquareIcon,MoreHorizontalIcon,PlusIcon,SquareIcon,@@ -71,6 +72,7 @@ import { useAtomCommand } from "../../state/use-atom-command";import { AgentElapsed } from "./AgentElapsed";import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow";+import { openSideChatTab } from "../../lib/sideChatPane";import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";@@ -349,6 +351,8 @@ function DelegatedFromRow(props: {export function ThreadRelationshipsPanel(props: {readonly environmentId: EnvironmentId;readonly threadId: ThreadId;+ readonly showLineage: boolean;+ readonly showSideChats: boolean;}) {const ref = scopeThreadRef(props.environmentId, props.threadId);const projection = useThreadProjection(ref)?.projection ?? null;@@ -449,9 +453,12 @@ export function ThreadRelationshipsPanel(props: {related = [],active = [],previous = [],- } = groupBy(relationshipRows, ({ edge }) => {- if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId))- return "related";+ sideChats = [],+ } = groupBy(relationshipRows, ({ threadId, edge }) => {+ const isParent = isParentThreadRelationship(edge, props.threadId);+ if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true)+ return "sideChats";+ if (edge.kind !== "subagent" || isParent) return "related";return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(edge.status ?? "",)@@ -476,16 +483,25 @@ export function ThreadRelationshipsPanel(props: {// A linked environment's agent may have delegated this thread from there.const delegatedFrom = currentThread?.delegatedFrom;- if (- relationshipRows.length === 0 &&- runningCount === 0 &&- remoteSubagents.length === 0 &&- delegatedFrom === undefined- ) {+ const lineageVisible =+ props.showLineage &&+ (related.length > 0 ||+ active.length > 0 ||+ previous.length > 0 ||+ runningCount > 0 ||+ remoteSubagents.length > 0 ||+ delegatedFrom !== undefined ||+ // Disconnect lives in this heading, so a thread with only side chats still shows it.+ (canDetach && sideChats.length > 0));+ const sideChatsVisible = props.showSideChats && sideChats.length > 0;+ const runningSideChats = sideChats.filter(({ edge }) => edge.status === "running").length;++ if (!lineageVisible && !sideChatsVisible) {return null;}const openThread = (threadId: ThreadId) => {+ if (openSideChatTab(ref, graph.nodes.get(threadId)?.thread ?? null)) return;void navigate({to: "/$environmentId/$threadId",params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),@@ -572,327 +588,338 @@ export function ThreadRelationshipsPanel(props: {? null: (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);- return (- <ThreadDetailsSection- headingId="thread-details-lineage-heading"- title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}- // A lone "Previous agents" row names itself; the heading returns for status or actions.- showHeading={- runningCount > 0 ||- canDetach ||- related.length > 0 ||- active.length > 0 ||- delegatedFrom !== undefined- }- data-thread-relationships-panel- actions={- canDetach ? (- <Menu>- <MenuTrigger- render={- <ThreadDetailsControl- size="icon-xs"- variant="ghost"- part="icon"- aria-label="More thread actions"- disabled={busyAction !== null}- />- }- >- <MoreHorizontalIcon className="size-3.5" />- </MenuTrigger>- <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">- <MenuItem onClick={() => void detach()}>- <UnplugIcon className="size-3.5" />- Disconnect agent session- </MenuItem>- </MenuPopup>- </Menu>- ) : null- }- >- {delegatedFrom === undefined ? null : (- <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>- <DelegatedFromRow- delegatedFrom={delegatedFrom}- fallbackLabel={currentThread?.linkOrigin?.label}- />- </ThreadLineageRowList>- )}- {groups.map((group) => (- <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>- {(visibleRows) =>- visibleRows.map(({ threadId, edge }) => {- const node = graph.nodes.get(threadId);- const isSubagent = edge.kind === "subagent";- const isMergeTarget = threadId === mergeTargetThreadId;- const isParent = isParentThreadRelationship(edge, props.threadId);- const rowStatus =- (isParent && threadId === parentRef?.threadId- ? (node?.thread?.activityRunStatus ?? parentNativeStatus)- : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });- const RelationshipIcon = isParent- ? CornerLeftUpIcon- : isSubagent- ? BotIcon- : GitForkIcon;- const relationship = relationshipLabel(edge, props.threadId);- const projectedAgent =- isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;- const workflowGroup =- projectedAgent === undefined- ? undefined- : workflowGroupsById.get(projectedAgent.id);- const agent = workflowGroup- ? projectedAgent- : currentSubagent(projectedAgent, node?.thread);- const failed = rowStatus === "failed" || rowStatus === "error";- const canStop =- agent &&- (agent.origin === "app_owned" ||- (agent.origin === "provider_native" &&- agent.driver === "claudeAgent" &&- agent.runId != null &&- agent.nativeTaskRef?.strength === "strong" &&- agent.nativeTaskRef.nativeId !== null &&- ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&- agent.startedAt &&- ["pending", "running", "waiting"].includes(agent.status);- const threadTitle = relationshipThreadTitle({- title:- workflowGroup?.workflow.workflowName ??- node?.thread?.title ??- agent?.title ??- threadId,- isSubagent,- });- const provider = providers?.find(- (entry) =>- entry.instanceId ===- (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),- );- const providerDriver = agent?.driver ?? provider?.driver;- const canStopWorkflow =- canOperateWorkflow &&- workflowGroup?.workflow.status === "running" &&- agent?.origin === "provider_native" &&- providerDriver === "claudeAgent";- const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)- ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"- : "";- const project = projects.find((project) => project.id === node?.thread?.projectId);- const relationshipHint = node?.missing- ? "This related thread is unavailable"- : `Open ${relationship.toLowerCase()} in this chat`;- const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;- const relationshipTooltip = agent ? (- <SubagentTooltipContent- title={threadTitle}- model={agent.model}- providerInstanceId={agent.providerInstanceId}- origin={agent.origin}- modelSelection={agent.modelSelection}- provider={provider}- providers={providers}- driver={providerDriver}- elapsed={<AgentElapsed agent={agent} />}- status={agent.status}- result={agent.result}- progress={agent.progress}- parentThread={currentThread ?? undefined}- childThread={node?.thread ?? undefined}- parentProject={currentProject}- childProject={project}- />- ) : (- relationshipHint- );- const relationshipContent = (- <>- <ThreadRelationshipIcon- driver={isSubagent && !isParent ? providerDriver : undefined}- provider={provider}- fallbackIcon={RelationshipIcon}- status={rowStatus}+ const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {+ const node = graph.nodes.get(threadId);+ const isSubagent = edge.kind === "subagent";+ const isMergeTarget = threadId === mergeTargetThreadId;+ const isParent = isParentThreadRelationship(edge, props.threadId);+ const rowStatus =+ (isParent && threadId === parentRef?.threadId+ ? (node?.thread?.activityRunStatus ?? parentNativeStatus)+ : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });+ const RelationshipIcon = isParent+ ? CornerLeftUpIcon+ : isSubagent+ ? BotIcon+ : node?.thread?.lineage.sideChat === true+ ? MessagesSquareIcon+ : GitForkIcon;+ const relationship =+ node?.thread?.lineage.sideChat === true && !isParent+ ? "Side chat"+ : relationshipLabel(edge, props.threadId);+ const projectedAgent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;+ const workflowGroup =+ projectedAgent === undefined ? undefined : workflowGroupsById.get(projectedAgent.id);+ const agent = workflowGroup ? projectedAgent : currentSubagent(projectedAgent, node?.thread);+ const failed = rowStatus === "failed" || rowStatus === "error";+ const canStop =+ agent &&+ (agent.origin === "app_owned" ||+ (agent.origin === "provider_native" &&+ agent.driver === "claudeAgent" &&+ agent.runId != null &&+ agent.nativeTaskRef?.strength === "strong" &&+ agent.nativeTaskRef.nativeId !== null &&+ ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&+ agent.startedAt &&+ ["pending", "running", "waiting"].includes(agent.status);+ const threadTitle = relationshipThreadTitle({+ title:+ workflowGroup?.workflow.workflowName ?? node?.thread?.title ?? agent?.title ?? threadId,+ isSubagent,+ });+ const provider = providers?.find(+ (entry) =>+ entry.instanceId === (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),+ );+ const providerDriver = agent?.driver ?? provider?.driver;+ const canStopWorkflow =+ canOperateWorkflow &&+ workflowGroup?.workflow.status === "running" &&+ agent?.origin === "provider_native" &&+ providerDriver === "claudeAgent";+ const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)+ ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"+ : "";+ const project = projects.find((project) => project.id === node?.thread?.projectId);+ const relationshipHint = node?.missing+ ? "This related thread is unavailable"+ : `Open ${relationship.toLowerCase()} in this chat`;+ const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;+ const relationshipTooltip = agent ? (+ <SubagentTooltipContent+ title={threadTitle}+ model={agent.model}+ providerInstanceId={agent.providerInstanceId}+ origin={agent.origin}+ modelSelection={agent.modelSelection}+ provider={provider}+ providers={providers}+ driver={providerDriver}+ elapsed={<AgentElapsed agent={agent} />}+ status={agent.status}+ result={agent.result}+ progress={agent.progress}+ parentThread={currentThread ?? undefined}+ childThread={node?.thread ?? undefined}+ parentProject={currentProject}+ childProject={project}+ />+ ) : (+ relationshipHint+ );+ const relationshipContent = (+ <>+ <ThreadRelationshipIcon+ driver={isSubagent && !isParent ? providerDriver : undefined}+ provider={provider}+ fallbackIcon={RelationshipIcon}+ status={rowStatus}+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">+ {threadTitle}+ </span>+ </span>+ {agent ? null : (+ <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />+ )}+ {agent && !failed && (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (+ <span+ className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}+ >+ <AgentElapsed agent={agent} compact />+ </span>+ ) : !isMergeTarget ? (+ <span+ className={+ workflowGroup+ ? "sr-only"+ : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`+ }+ >+ {threadRelationshipStatusLabel(rowStatus)}+ </span>+ ) : null}+ </>+ );+ const relationshipLink = (+ <Tooltip>+ <TooltipTrigger+ delay={200}+ render={+ <ThreadDetailsControl+ size="sm"+ variant="ghost"+ part={workflowGroup ? "primary" : "row"}+ disabled={node?.missing === true}+ onClick={() => openThread(threadId)}+ />+ }+ >+ {relationshipContent}+ </TooltipTrigger>+ <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>+ </Tooltip>+ );+ if (workflowGroup && agent) {+ return (+ <ThreadLineageWorkflowRow+ key={threadId}+ group={workflowGroup}+ providerInstanceId={agent.providerInstanceId}+ provider={provider}+ providers={providers}+ driver={providerDriver}+ onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}+ isThreadAvailable={(memberThreadId) =>+ graph.nodes.get(memberThreadId as ThreadId)?.missing === false+ }+ onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}+ stopping={stoppingId === agent.id}+ stopDisabled={stoppingId !== null}+ header={relationshipLink}+ />+ );+ }+ return (+ <li key={threadId} className="group relative flex h-8 items-center rounded-lg">+ {isMergeTarget ? (+ <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>+ <Tooltip>+ <TooltipTrigger+ delay={200}+ render={+ <ThreadDetailsControl+ size="sm"+ variant="ghost"+ part="primary"+ aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}+ disabled={node?.missing === true}+ onClick={() => openThread(threadId)}/>- <span className="min-w-0 flex-1">- <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">- {threadTitle}- </span>- </span>- {agent ? null : (- <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />- )}- {agent &&- !failed &&- (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (- <span- className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}- >- <AgentElapsed agent={agent} compact />- </span>- ) : !isMergeTarget ? (- <span- className={- workflowGroup- ? "sr-only"- : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`- }- >- {threadRelationshipStatusLabel(rowStatus)}- </span>- ) : null}- </>- );- const relationshipLink = (- <Tooltip>- <TooltipTrigger- delay={200}- render={- <ThreadDetailsControl- size="sm"- variant="ghost"- part={workflowGroup ? "primary" : "row"}- disabled={node?.missing === true}- onClick={() => openThread(threadId)}- />+ }+ >+ {relationshipContent}+ </TooltipTrigger>+ <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>+ </Tooltip>+ <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />+ <Tooltip>+ <TooltipTrigger+ render={+ <ThreadDetailsControl+ size="sm"+ variant="ghost"+ part="secondary"+ aria-label={+ parentTitle+ ? `Merge back to ${parentTitle}`+ : "Merge back to source conversation"}+ disabled={!canMerge || busyAction !== null}+ onClick={() => void merge()}>- {relationshipContent}- </TooltipTrigger>- <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>- </Tooltip>- );- if (workflowGroup && agent) {- return (- <ThreadLineageWorkflowRow- key={threadId}- group={workflowGroup}- providerInstanceId={agent.providerInstanceId}- provider={provider}- providers={providers}- driver={providerDriver}- onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}- isThreadAvailable={(memberThreadId) =>- graph.nodes.get(memberThreadId as ThreadId)?.missing === false- }- onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}- stopping={stoppingId === agent.id}- stopDisabled={stoppingId !== null}- header={relationshipLink}+ {busyAction === "merge" ? (+ <Spinner size="xs" />+ ) : (+ <PullRequestGlyph.merged className="size-3" />+ )}+ </ThreadDetailsControl>+ }+ />+ <TooltipPopup side="left">+ {latestMergeBackRun === null+ ? "Complete a run in this fork before merging it back"+ : parentTitle+ ? `Merge this conversation back into ${parentTitle}`+ : "Merge this conversation back into its source"}+ </TooltipPopup>+ </Tooltip>+ <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">+ {threadRelationshipStatusLabel(rowStatus)}+ </span>+ </div>+ ) : (+ relationshipLink+ )}+ {canStop && agent ? (+ <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">+ <Tooltip>+ <TooltipTrigger+ render={+ <ThreadDetailsControl+ size="icon-xs"+ variant="ghost"+ part="icon"+ tone="destructive"+ aria-label={`Stop subagent ${threadTitle}`}+ disabled={stoppingId !== null}+ onClick={() => void stopSubagent(threadId, agent)}/>- );- }- return (- <li key={threadId} className="group relative flex h-8 items-center rounded-lg">- {isMergeTarget ? (- <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>- <Tooltip>- <TooltipTrigger- delay={200}- render={- <ThreadDetailsControl- size="sm"- variant="ghost"- part="primary"- aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}- disabled={node?.missing === true}- onClick={() => openThread(threadId)}- />- }- >- {relationshipContent}- </TooltipTrigger>- <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>- </Tooltip>- <span- aria-hidden="true"- className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}- />- <Tooltip>- <TooltipTrigger- render={- <ThreadDetailsControl- size="sm"- variant="ghost"- part="secondary"- aria-label={- parentTitle- ? `Merge back to ${parentTitle}`- : "Merge back to source conversation"- }- disabled={!canMerge || busyAction !== null}- onClick={() => void merge()}- >- {busyAction === "merge" ? (- <Spinner size="xs" />- ) : (- <PullRequestGlyph.merged className="size-3" />- )}- </ThreadDetailsControl>- }- />- <TooltipPopup side="left">- {latestMergeBackRun === null- ? "Complete a run in this fork before merging it back"- : parentTitle- ? `Merge this conversation back into ${parentTitle}`- : "Merge this conversation back into its source"}- </TooltipPopup>- </Tooltip>- <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">- {threadRelationshipStatusLabel(rowStatus)}- </span>- </div>- ) : (- relationshipLink- )}- {canStop && agent ? (- <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">- <Tooltip>- <TooltipTrigger- render={- <ThreadDetailsControl- size="icon-xs"- variant="ghost"- part="icon"- tone="destructive"- aria-label={`Stop subagent ${threadTitle}`}- disabled={stoppingId !== null}- onClick={() => void stopSubagent(threadId, agent)}- />- }- >- {stoppingId === threadId ? (- <Spinner aria-hidden size="xs" />- ) : (- <SquareIcon aria-hidden className="size-3 fill-current" />- )}- </TooltipTrigger>- <TooltipPopup side="left">Stop subagent</TooltipPopup>- </Tooltip>- </div>- ) : null}- </li>- );- })+ }+ >+ {stoppingId === threadId ? (+ <Spinner aria-hidden size="xs" />+ ) : (+ <SquareIcon aria-hidden className="size-3 fill-current" />+ )}+ </TooltipTrigger>+ <TooltipPopup side="left">Stop subagent</TooltipPopup>+ </Tooltip>+ </div>+ ) : null}+ </li>+ );+ };++ return (+ <>+ {lineageVisible ? (+ <ThreadDetailsSection+ headingId="thread-details-lineage-heading"+ title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}+ // A lone "Previous agents" row names itself; the heading returns for status or actions.+ showHeading={+ runningCount > 0 ||+ canDetach ||+ related.length > 0 ||+ active.length > 0 ||+ delegatedFrom !== undefined}- </ThreadLineageGroup>- ))}- {remoteSubagents.length > 0 ? (- <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>- {remoteSubagents.map((agent) => (- <RemoteSubagentRow- key={agent.id}- agent={agent}- // Its provider instance belongs to the environment it runs in.- provider={providersByEnvironment- .get(agent.remoteChild.environmentId)- ?.find((entry) => entry.instanceId === agent.providerInstanceId)}- />+ data-thread-relationships-panel+ actions={+ canDetach ? (+ <Menu>+ <MenuTrigger+ render={+ <ThreadDetailsControl+ size="icon-xs"+ variant="ghost"+ part="icon"+ aria-label="More thread actions"+ disabled={busyAction !== null}+ />+ }+ >+ <MoreHorizontalIcon className="size-3.5" />+ </MenuTrigger>+ <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">+ <MenuItem onClick={() => void detach()}>+ <UnplugIcon className="size-3.5" />+ Disconnect agent session+ </MenuItem>+ </MenuPopup>+ </Menu>+ ) : null+ }+ >+ {delegatedFrom === undefined ? null : (+ <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>+ <DelegatedFromRow+ delegatedFrom={delegatedFrom}+ fallbackLabel={currentThread?.linkOrigin?.label}+ />+ </ThreadLineageRowList>+ )}+ {groups.map((group) => (+ <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>+ {(visibleRows) => visibleRows.map(renderRelationshipRow)}+ </ThreadLineageGroup>))}- </ThreadLineageRowList>+ {remoteSubagents.length > 0 ? (+ <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>+ {remoteSubagents.map((agent) => (+ <RemoteSubagentRow+ key={agent.id}+ agent={agent}+ // Its provider instance belongs to the environment it runs in.+ provider={providersByEnvironment+ .get(agent.remoteChild.environmentId)+ ?.find((entry) => entry.instanceId === agent.providerInstanceId)}+ />+ ))}+ </ThreadLineageRowList>+ ) : null}+ </ThreadDetailsSection>) : null}- </ThreadDetailsSection>+ {sideChatsVisible ? (+ <ThreadDetailsSection+ headingId="thread-details-side-chats-heading"+ title={runningSideChats > 0 ? `Side chats · ${runningSideChats} running` : "Side chats"}+ data-thread-side-chats-panel+ >+ <ThreadLineageGroup+ key={`${scopedThreadKey(ref)}:side-chats`}+ label={null}+ rows={sideChats}+ expanded+ >+ {(visibleRows) => visibleRows.map(renderRelationshipRow)}+ </ThreadLineageGroup>+ </ThreadDetailsSection>+ ) : null}+ </>);}diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.tsindex bab90534b5c..b3dfee09a66 100644--- a/apps/web/src/components/chat/backgroundThread.ts+++ b/apps/web/src/components/chat/backgroundThread.ts@@ -1,4 +1,7 @@import { createContext } from "react";-/** True for a thread kept mounted under Settings or Usage; its global shortcuts stand down. */+/**+ * True for a thread kept mounted under Settings or Usage, or shown as a side chat in its+ * parent's panel; its global shortcuts and listeners stand down.+ */export const BackgroundThreadContext = createContext(false);diff --git a/apps/web/src/components/chat/composerSlashCommandSearch.ts b/apps/web/src/components/chat/composerSlashCommandSearch.tsindex adc095abaeb..0c5c04e28ca 100644--- a/apps/web/src/components/chat/composerSlashCommandSearch.ts+++ b/apps/web/src/components/chat/composerSlashCommandSearch.ts@@ -12,7 +12,7 @@ type SlashSearchItem = Extract<{ type: "slash-command" | "provider-slash-command" | "skill" }>;-/** Providers expand slash commands only at the message start. */+/** Provider commands, `/side` and `/btw` work only at the message start. */export function slashCommandItemsForPromptPosition(items: ReadonlyArray<SlashSearchItem>,isAtPromptStart: boolean,@@ -20,7 +20,11 @@ export function slashCommandItemsForPromptPosition(if (isAtPromptStart) {return [...items];}- return items.filter((item) => item.type !== "provider-slash-command");+ return items.filter(+ (item) =>+ item.type === "skill" ||+ (item.type === "slash-command" && item.command !== "side" && item.command !== "btw"),+ );}function scoreSlashCommandItem(item: SlashSearchItem, query: string): number | null {diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.tsindex 9922b1b8a0b..e6f94cc4e11 100644--- a/apps/web/src/components/chat/threadDetailsItems.ts+++ b/apps/web/src/components/chat/threadDetailsItems.ts@@ -11,6 +11,7 @@ export const THREAD_DETAILS_ITEMS = [{ id: "servers", label: "Servers", defaultVisible: true },{ id: "automations", label: "Automations", defaultVisible: true },{ id: "lineage", label: "Lineage", defaultVisible: true },+ { id: "sideChats", label: "Side chats", defaultVisible: true },{ id: "usage", label: "Usage limits", defaultVisible: false },{ id: "context", label: "Context window", defaultVisible: false },] as const;diff --git a/apps/web/src/components/chat/timelineViewport.ts b/apps/web/src/components/chat/timelineViewport.tsindex 2dcbc4ae1d2..527685285e0 100644--- a/apps/web/src/components/chat/timelineViewport.ts+++ b/apps/web/src/components/chat/timelineViewport.ts@@ -1,3 +1,4 @@+import { isInSideChatPane } from "../../lib/sideChatPane";import { registerCommands } from "../../shortcuts/dispatcher";import {eventPathContainsSelector,@@ -86,6 +87,7 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewporemit({ source: "pointer", onScrollbar: event.target === scrollNode });// Clicking message text can leave DOM focus on body, and keyboard scrolling// bypasses wheel and pointer events, so scroll keys are heard app-wide.+ // Body keys belong to the main timeline; a side chat's hears only its own.const handleKeyDown = (event: KeyboardEvent, consumed: boolean) => {const direction = UP_KEYS.has(event.key) ? "up" : DOWN_KEYS.has(event.key) ? "down" : null;if (@@ -93,8 +95,8 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewporconsumed ||!(event.target instanceof Node) ||(!scrollNode.contains(event.target) &&- event.target !== document.body &&- event.target !== document.documentElement) ||+ ((event.target !== document.body && event.target !== document.documentElement) ||+ isInSideChatPane(scrollNode))) ||event.isComposing ||event.altKey ||event.ctrlKey ||diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsxindex 64f56007cea..d04247d2797 100644--- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx+++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx@@ -1,4 +1,5 @@-import { useEffect } from "react";+import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";+import { useEffect, useState } from "react";import { expect, it } from "vite-plus/test";import { userEvent } from "vite-plus/test/browser";@@ -132,3 +133,57 @@ it.each([expect(composerKeys).toEqual(composer);expect(received).toEqual(launcher);});++const ctrlShift = (key: string, command: KeybindingCommand) => ({+ command,+ shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false },+});+const sideChatKeybindings: ResolvedKeybindingsConfig = [+ ctrlShift("m", "modelPicker.toggle"),+ ctrlShift("x", "thread.stop"),+];++// A side chat in the main chat's panel: no window listeners, only its composer's own chords.+function SideChat(props: { toggles: string[]; stops: string[] }) {+ const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);+ useChatShortcuts({+ enabled: false,+ embedded: true,+ composerElement,+ keybindings: sideChatKeybindings,+ scriptKeybindings: [],+ getShortcutContext: () => shortcutContext,+ threadFindActive: false,+ composerRef: {+ current: {+ toggleModelPicker: () => props.toggles.push("model"),+ } as Partial<ChatComposerHandle> as ChatComposerHandle,+ },+ branchToolbarRef: { current: null },+ closeThreadFind: () => {},+ commands: { "thread.stop": () => void props.stops.push("stop") },+ fallback: () => undefined,+ });+ return (+ <>+ <div ref={setComposerElement}>+ <textarea aria-label="Side chat composer" />+ </div>+ <textarea aria-label="Main composer" />+ </>+ );+}++it("runs a side chat's composer chords only from its composer, and never thread commands", async () => {+ const toggles: string[] = [];+ const stops: string[] = [];+ await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);++ await userEvent.click(screen.getByLabelText("Side chat composer"));+ await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");+ await userEvent.click(screen.getByLabelText("Main composer"));+ await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");++ expect(toggles).toEqual(["model"]);+ expect(stops).toEqual([]);+});diff --git a/apps/web/src/components/chat/useChatShortcuts.ts b/apps/web/src/components/chat/useChatShortcuts.tsindex 7e90fc957ae..637546f65d2 100644--- a/apps/web/src/components/chat/useChatShortcuts.ts+++ b/apps/web/src/components/chat/useChatShortcuts.ts@@ -7,6 +7,7 @@ import {preventRepeatedTerminalCloseShortcut,preventTerminalCloseShortcut,} from "../../lib/terminalCloseShortcut";+import { isInSideChatPane } from "../../lib/sideChatPane";import { getTerminalFocusOwner, type TerminalFocusOwner } from "../../lib/terminalFocus";import type { ComposerHandleRef } from "../../composerHandleContext";import type { BranchToolbarHandle } from "../BranchToolbar";@@ -23,6 +24,12 @@ export type ChatShortcutCommands = Partial<Record<KeybindingCommand, ChatShortcuinterface ChatShortcutsInput {readonly enabled: boolean;+ /**+ * A side chat inside another chat leaves the window to the outer chat. It runs only+ * composer chords, for keys pressed inside `composerElement`.+ */+ readonly embedded?: boolean;+ readonly composerElement?: HTMLElement | null;readonly keybindings: ResolvedKeybindingsConfig;readonly scriptKeybindings: ResolvedKeybindingsConfig;readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {@@ -44,6 +51,8 @@ interface ChatShortcutsInput {* act on the current render without re-registering on every change.*/export function useChatShortcuts(input: ChatShortcutsInput) {+ const embedded = input.embedded === true;+ const composerElement = embedded ? (input.composerElement ?? null) : null;const handleShortcut = useEffectEvent((event: KeyboardEvent) => {const { keybindings } = input;if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {@@ -55,7 +64,7 @@ export function useChatShortcuts(input: ChatShortcutsInput) {event.stopPropagation();return;}- if (!input.enabled || isCommandPaletteOpen()) return;+ if (!input.enabled || isCommandPaletteOpen() || isInSideChatPane(event.target)) return;const terminalFocusOwner = getTerminalFocusOwner();if (event.defaultPrevented && terminalFocusOwner === null) return;const shortcutContext = input.getShortcutContext(event.target);@@ -90,7 +99,8 @@ export function useChatShortcuts(input: ChatShortcutsInput) {event.defaultPrevented ||event.isComposing ||event.keyCode === 229 ||- isCommandPaletteOpen()+ isCommandPaletteOpen() ||+ isInSideChatPane(event.target))return;const context = input.getShortcutContext(event.target);@@ -98,8 +108,26 @@ export function useChatShortcuts(input: ChatShortcutsInput) {event.preventDefault();input.closeThreadFind();});- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window keydown listeners for chat shortcuts and find dismissal for the component's lifetime+ const handleComposerShortcut = useEffectEvent((event: KeyboardEvent) => {+ if (event.defaultPrevented || isCommandPaletteOpen()) return;+ const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {+ context: input.getShortcutContext(event.target),+ });+ const run = command+ ? composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command]+ : undefined;+ if (!run || run({ event, terminalFocusOwner: null }) === false) return;+ event.preventDefault();+ event.stopPropagation();+ });+ // 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 composeruseEffect(() => {+ if (embedded) {+ if (composerElement === null) return;+ const onComposerKeyDown = (event: KeyboardEvent) => handleComposerShortcut(event);+ composerElement.addEventListener("keydown", onComposerKeyDown, true);+ return () => composerElement.removeEventListener("keydown", onComposerKeyDown, true);+ }const onKeyDownCapture = (event: KeyboardEvent) => handleShortcut(event);const onKeyDown = (event: KeyboardEvent) => dismissFind(event);window.addEventListener("keydown", onKeyDownCapture, true);@@ -108,5 +136,5 @@ export function useChatShortcuts(input: ChatShortcutsInput) {window.removeEventListener("keydown", onKeyDownCapture, true);window.removeEventListener("keydown", onKeyDown);};- }, []);+ }, [composerElement, embedded]);}diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.tsindex 6468b2f5762..3ae947ff897 100644--- a/apps/web/src/components/chat/useComposerMenuItems.ts+++ b/apps/web/src/components/chat/useComposerMenuItems.ts@@ -64,6 +64,8 @@ export function useComposerMenuItems({pullRequestRepository,threadPullRequests,planModeUiEnabled,+ sideChatAvailable,+ sideChatDisabledReason,compactSlashCommandAvailable,selectedProvider,selectedProviderSkills,@@ -80,6 +82,8 @@ export function useComposerMenuItems({readonly pullRequestRepository: string | null;readonly threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined;readonly planModeUiEnabled: boolean;+ readonly sideChatAvailable: boolean;+ readonly sideChatDisabledReason: string | null;readonly compactSlashCommandAvailable: boolean;readonly selectedProvider: ProviderDriverKind;readonly selectedProviderSkills: ServerProvider["skills"];@@ -236,6 +240,24 @@ export function useComposerMenuItems({},] as const): []),+ ...(sideChatAvailable+ ? ([+ {+ id: "slash:side",+ type: "slash-command",+ command: "side",+ label: "/side",+ description: sideChatDisabledReason ?? "Ask a side question in a new side chat",+ },+ {+ id: "slash:btw",+ type: "slash-command",+ command: "btw",+ label: "/btw",+ description: sideChatDisabledReason ?? "Same as /side",+ },+ ] as const)+ : []),] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;const slashMenuSkills = getProviderSkillsForSlashMenu(selectedProviderSkills,diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.tsindex a3bdcd2d9c5..b22c313f693 100644--- a/apps/web/src/components/chat/useComposerSend.ts+++ b/apps/web/src/components/chat/useComposerSend.ts@@ -54,6 +54,7 @@ import {import {type ComposerSubmissionIntent,collapseExpandedComposerCursor,+ parseSideChatCommand,parseStandaloneComposerSlashCommand,} from "../../composer-logic";import { resolvePlanFollowUpSubmission } from "../../proposedPlan";@@ -76,7 +77,10 @@ import {useComposerDraftStore,DraftId,} from "../../composerDraftStore";-import { type TerminalContextDraft } from "../../lib/terminalContext";+import {+ filterTerminalContextsWithText,+ type TerminalContextDraft,+} from "../../lib/terminalContext";import { ensureInlineContextReferences } from "../../lib/composerContextReferences";import {buildMessageContext,@@ -237,6 +241,10 @@ interface ComposerSendInput {readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];readonly acknowledgeActiveThreadWoke: () => void;readonly handleInteractionModeChange: (mode: ProviderInteractionMode) => void;+ /** Resolves true once the side chat started and got the prompt. */+ readonly onSideChat?: ((prompt: string) => Promise<boolean>) | undefined;+ /** Refuses `/side` with this reason and keeps the draft. */+ readonly sideChatDisabledReason: string | null;readonly handleNewThreadInActiveProject: () => void;readonly persistThreadSettingsForNextTurn: (input: {threadId: ThreadId;@@ -322,6 +330,8 @@ export function useComposerSend(input: ComposerSendInput) {anchorNewTurn,acknowledgeActiveThreadWoke,handleInteractionModeChange,+ onSideChat,+ sideChatDisabledReason,handleNewThreadInActiveProject,persistThreadSettingsForNextTurn,} = input;@@ -473,7 +483,57 @@ export function useComposerSend(input: ComposerSendInput) {return;}const sendCtx = composerRef.current?.getSendContext();- if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) {+ // `/side` beats an open question and a plan follow-up, which would send the text to main.+ const sideChatCommand =+ sendCtx && !directAnnotation && !queuedRunEdit.isEditing+ ? parseSideChatCommand(promptAtSend)+ : null;+ const answeringQuestion =+ Boolean(activePendingProgress) && sendCtx?.answeringPendingUserInput !== false;+ // Where side chats are unavailable, `/side` text can still be a literal answer.+ if (sideChatDisabledReason !== null && sideChatCommand && !answeringQuestion) {+ toastManager.add(+ stackedThreadToast({+ type: "warning",+ title: "Side chat not started",+ description: sideChatDisabledReason,+ }),+ );+ return;+ }+ if (onSideChat && sendCtx && sideChatCommand && sideChatDisabledReason === null) {+ if (+ sendCtx.images.length > 0 ||+ sendCtx.files.length > 0 ||+ filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 ||+ sendCtx.previewAnnotations.length > 0 ||+ sendCtx.reviewComments.length > 0 ||+ sendCtx.threadContexts.length > 0 ||+ sendCtx.environmentContexts.length > 0+ ) {+ toastManager.add(+ stackedThreadToast({+ type: "warning",+ title: "Side chats take text only",+ description: "Remove the attachments and context, then send it again.",+ }),+ );+ return;+ }+ const started = await onSideChat(sideChatCommand.prompt);+ // Clear only what was sent; the user may have edited the draft or left meanwhile.+ if (+ started &&+ currentRouteThreadKeyRef.current === routeThreadKey &&+ promptRef.current === promptAtSend+ ) {+ promptRef.current = "";+ setComposerDraftPrompt(composerDraftTarget, "");+ composerRef.current?.resetCursorState();+ }+ return;+ }+ if (answeringQuestion) {if (directAnnotation) {notifyDirectAnnotationAttached();return;diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.tsindex 6f092cd2f00..1d480dcf150 100644--- a/apps/web/src/components/chat/useComposerStash.ts+++ b/apps/web/src/components/chat/useComposerStash.ts@@ -61,6 +61,7 @@ import {useState,} from "react";import { BackgroundThreadContext } from "./backgroundThread";+import { isInSideChatPane } from "../../lib/sideChatPane";import { useStableCallback } from "../../hooks/useStableCallback";/**@@ -699,7 +700,11 @@ export function useComposerStash(input: {if (backgroundThread) return;return registerCommands({ "composer.stash": handleStashShortcut },- { capture: true, context: readShortcutContext },+ {+ capture: true,+ context: readShortcutContext,+ when: (event) => !isInSideChatPane(event.target),+ },);}, [backgroundThread, handleStashShortcut, readShortcutContext]);diff --git a/apps/web/src/components/chat/usePasteToFocusComposer.ts b/apps/web/src/components/chat/usePasteToFocusComposer.tsindex 7c16110c94d..84672cc570c 100644--- a/apps/web/src/components/chat/usePasteToFocusComposer.ts+++ b/apps/web/src/components/chat/usePasteToFocusComposer.ts@@ -5,6 +5,7 @@ import { useEffect, useRef } from "react";import { isMacPlatform } from "../../lib/utils";import { isCommandPaletteOpen } from "../../commandPaletteBus";import { getTerminalFocusOwner } from "../../lib/terminalFocus";+import { isInSideChatPane } from "../../lib/sideChatPane";import type { ThreadId } from "@t3tools/contracts";import type { ComposerHandleRef } from "../../composerHandleContext";/**@@ -18,6 +19,7 @@ export function usePasteToFocusComposer(const pasteAsTextShortcutUntilRef = useRef(0);// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window keydown and paste capture listeners that route stray pastes into the composeruseEffect(() => {+ if (!activeThreadId) return;const keyHandler = (event: KeyboardEvent) => {if (shouldRedirectInputToComposer(event) &&@@ -27,7 +29,7 @@ export function usePasteToFocusComposer(}};const handler = (event: ClipboardEvent) => {- if (!activeThreadId || isCommandPaletteOpen()) return;+ if (isCommandPaletteOpen() || isInSideChatPane(event.target)) return;if (getTerminalFocusOwner() !== null) return;if (composerRef.current?.isModelPickerOpen()) return;const text = pasteTextToFocusComposer(event);diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.tsindex 3919df03b6a..0f8e8e3ce30 100644--- a/apps/web/src/components/chat/useRightPanelActions.ts+++ b/apps/web/src/components/chat/useRightPanelActions.ts@@ -45,6 +45,8 @@ interface RightPanelActionsInput {readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;readonly threadPanelPresentation: ThreadPanelPresentation;readonly isServerThread: boolean;+ /** A side chat pane; the main view already answers preview bus actions. */+ readonly embedded: boolean;readonly isGitRepo: boolean;readonly browserAvailable: boolean;readonly canOperatePreview: boolean;@@ -78,6 +80,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {pullRequestPanelTarget,threadPanelPresentation,isServerThread,+ embedded,isGitRepo,browserAvailable,canOperatePreview,@@ -316,10 +319,12 @@ export function useRightPanelActions(input: RightPanelActionsInput) {// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview paneluseEffect(() =>- subscribePreviewAction((action) => {- if (action === "toggle-panel") togglePreviewPanelStable();- }),- [togglePreviewPanelStable],+ embedded+ ? undefined+ : subscribePreviewAction((action) => {+ if (action === "toggle-panel") togglePreviewPanelStable();+ }),+ [embedded, togglePreviewPanelStable],);const shortcuts = {diff --git a/apps/web/src/components/chat/useSideChat.ts b/apps/web/src/components/chat/useSideChat.tsnew file mode 100644index 00000000000..7ac27f75826--- /dev/null+++ b/apps/web/src/components/chat/useSideChat.ts@@ -0,0 +1,96 @@+import type { ScopedThreadRef } from "@t3tools/contracts";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";+import {+ type AtomCommandResult,+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { useRef } from "react";++import { newMessageId, newThreadId } from "~/lib/utils";+import { useStableCallback } from "../../hooks/useStableCallback";+import { useRightPanelStore } from "../../rightPanelStore";+import { waitForThreadShell } from "../../state/entities";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { useOrchestrationCommand } from "../../state/use-orchestration-command";++/**+ * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the+ * thread's latest stable point, sends `prompt` there, and shows the side chat's tab. It+ * resolves false when the side chat did not start, or another one is still starting.+ */+export function useSideChat(input: {+ readonly threadRef: ScopedThreadRef | null;+ readonly onError: (message: string) => void;+}) {+ const pendingRef = useRef(false);+ const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });+ const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });+ const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {+ reportFailure: false,+ });+ const reportFailure = (+ failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,+ fallback: string,+ ) => {+ if (isAtomCommandInterrupted(failure)) return;+ const error = squashAtomCommandFailure(failure);+ input.onError(error instanceof Error ? error.message : fallback);+ };+ const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {+ const targetThreadId = newThreadId();+ const fork = await forkSideChat({+ environmentId: threadRef.environmentId,+ input: { sourceThreadId: threadRef.threadId, targetThreadId, title: "Side chat" },+ });+ if (fork._tag === "Failure") {+ reportFailure(fork, "Could not start a side chat.");+ return false;+ }+ // Drops the empty side chat a failed start leaves behind; one that got its message stays.+ const discard = () =>+ void deleteThread({+ environmentId: threadRef.environmentId,+ input: { threadId: targetThreadId, onlyIfUnused: true },+ });+ if (!(await waitForThreadShell(scopeThreadRef(threadRef.environmentId, targetThreadId)))) {+ input.onError("The side chat was created, but it did not reach this client.");+ discard();+ return false;+ }+ const text = prompt?.trim();+ // Send before showing the tab: closing a tab whose side chat has no run deletes it.+ if (text) {+ // The server asks before edits on a side chat's first turn whatever mode is sent.+ const turn = await startThreadTurn({+ environmentId: threadRef.environmentId,+ input: {+ threadId: targetThreadId,+ message: { messageId: newMessageId(), role: "user", text, attachments: [] },+ titleSeed: deriveThreadTitleSeed({ text, attachments: [] }),+ runtimeMode: "approval-required",+ interactionMode: "default",+ createdAt: new Date().toISOString(),+ },+ });+ if (turn._tag === "Failure") {+ reportFailure(turn, "Could not send the side chat message.");+ discard();+ return false;+ }+ }+ useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);+ return true;+ };+ const open = async (prompt?: string) => {+ const { threadRef } = input;+ if (!threadRef || pendingRef.current) return false;+ pendingRef.current = true;+ return start(threadRef, prompt).finally(() => {+ pendingRef.current = false;+ });+ };+ return { available: input.threadRef !== null, open: useStableCallback(open) };+}diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsxindex a619cb4223e..4157dca2899 100644--- a/apps/web/src/components/chat/useThreadLifecycle.tsx+++ b/apps/web/src/components/chat/useThreadLifecycle.tsx@@ -69,6 +69,7 @@ import { useAtomValue } from "@effect/atom-react";import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";import { Atom } from "effect/reactivity";import { environmentThreadDetails } from "../../state/threads";+import { openSideChatTab } from "../../lib/sideChatPane";import type { useLocalDispatchState } from "./useLocalDispatchState";const RELATED_THREAD_SHELL_WAIT_MS = 1_000;const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(@@ -451,6 +452,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {toastManager.add({ type: "info", title: "This thread is no longer available" });return;}+ if (activeThreadRef && openSideChatTab(activeThreadRef, shell)) return;void navigate({to: "/$environmentId/$threadId",params: buildThreadRouteParams(threadRef),diff --git a/apps/web/src/components/preview/openPreviewSession.test.ts b/apps/web/src/components/preview/openPreviewSession.test.tsindex edd04a0661c..005d44d9468 100644--- a/apps/web/src/components/preview/openPreviewSession.test.ts+++ b/apps/web/src/components/preview/openPreviewSession.test.ts@@ -8,9 +8,18 @@ import { AsyncResult } from "effect/reactivity";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import * as browserDefaults from "~/browser/browserDefaults";-import { BrowserSettingsReadError, openUrlInPreview } from "~/browser/openFileInPreview";+import {+ BrowserSettingsReadError,+ openFileInPreview,+ openUrlInPreview,+} from "~/browser/openFileInPreview";+import * as previewRuntime from "~/browser/previewRuntime";import { __setClientSettingsForTests } from "~/hooks/useSettings";-import { useRightPanelStore } from "~/rightPanelStore";+import {+ hostRightPanel,+ selectActiveRightPanelSurface,+ useRightPanelStore,+} from "~/rightPanelStore";import {applyPreviewServerSnapshot,readThreadPreviewState,@@ -91,6 +100,47 @@ describe("openPreviewSession", () => {});describe("openUrlInPreview from a link", () => {+ it.each(["link", "file"] as const)(+ "opens a side chat's %s in the parent's browser panel after the pane unmounts",+ async (entryPoint) => {+ const sideChatRef = { ...threadRef, threadId: "side-chat" as ScopedThreadRef["threadId"] };+ const unhost = hostRightPanel(sideChatRef, threadRef);+ const openPreview = vi.fn(async () => AsyncResult.success(snapshot));+ vi.spyOn(previewRuntime, "isPreviewAvailableFor").mockReturnValue(true);+ vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockImplementation(async () => {+ unhost();+ return browserDefaults.getBrowserDefaults();+ });++ if (entryPoint === "link") {+ await openUrlInPreview({ openPreview, threadRef: sideChatRef, url: "https://t3.chat/" });+ } else {+ await openFileInPreview({+ threadRef: sideChatRef,+ filePath: "/repo/index.html",+ workspaceRoot: "/repo",+ httpBaseUrl: "http://localhost:3000",+ createAssetUrl: async () => {+ unhost();+ return AsyncResult.success({ relativeUrl: "/assets/index.html", expiresAt: 0 });+ },+ openPreview,+ });+ }++ expect(openPreview).toHaveBeenCalledWith(+ expect.objectContaining({+ input: expect.objectContaining({ threadId: threadRef.threadId }),+ }),+ );+ expect(readThreadPreviewState(threadRef).activeTabId).toBe(snapshot.tabId);+ expect(readThreadPreviewState(sideChatRef).sessions).toEqual({});+ expect(+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.kind,+ ).toBe("preview");+ },+ );+// regression: #16961 a background link open switched the active preview tabit("keeps the current tab active for a background open", async () => {applyPreviewServerSnapshot(threadRef, { ...snapshot, tabId: "tab-current" });diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.tsindex 4a76b3fcf93..51635a651d4 100644--- a/apps/web/src/composer-logic.test.ts+++ b/apps/web/src/composer-logic.test.ts@@ -22,8 +22,10 @@ import {extendReplacementRangeForTrailingSpace,formatAssistantCitationForComposer,isPathSuggestionCurrent,+ parseSideChatCommand,replaceTextRange,} from "./composer-logic";+import { slashCommandItemsForPromptPosition } from "./components/chat/composerSlashCommandSearch";import { carryDisplacedCustomAnswerIntoPrompt } from "./pendingUserInput";import { formatTerminalContextReference } from "./lib/terminalContext";@@ -548,3 +550,29 @@ describe("extendReplacementRangeForTrailingSpace", () => {expect(extendReplacementRangeForTrailingSpace("@fi", 3, "@file ")).toBe(3);});});++describe("parseSideChatCommand", () => {+ it("reads an optional prompt after /side or /btw", () => {+ expect(parseSideChatCommand("/side")).toEqual({ prompt: "" });+ expect(parseSideChatCommand(" /SIDE why does this fail?\nline two ")).toEqual({+ prompt: "why does this fail?\nline two",+ });+ expect(parseSideChatCommand("/btw check @src/a.ts")).toEqual({ prompt: "check @src/a.ts" });+ });++ it("ignores other commands and inline mentions, which the menu does not offer", () => {+ expect(parseSideChatCommand("/sidebar")).toBeNull();+ expect(parseSideChatCommand("/btwx")).toBeNull();+ expect(parseSideChatCommand("ask /side later")).toBeNull();+ const items = (["side", "btw", "plan"] as const).map((command) => ({+ id: `slash:${command}`,+ type: "slash-command" as const,+ command,+ label: `/${command}`,+ description: "",+ }));+ expect(slashCommandItemsForPromptPosition(items, false).map((item) => item.id)).toEqual([+ "slash:plan",+ ]);+ });+});diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.tsindex a3043ce20cc..9b722379719 100644--- a/apps/web/src/composer-logic.ts+++ b/apps/web/src/composer-logic.ts@@ -18,7 +18,7 @@ import {import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";-export type ComposerSlashCommand = "model" | "plan" | "default";+export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw";export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";export interface ComposerTrigger {@@ -318,9 +318,15 @@ export function composerStateAtPromptEnd(};}+/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */+export function parseSideChatCommand(text: string): { prompt: string } | null {+ const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());+ return match ? { prompt: match[1]?.trim() ?? "" } : null;+}+export function parseStandaloneComposerSlashCommand(text: string,-): Exclude<ComposerSlashCommand, "model"> | null {+): Exclude<ComposerSlashCommand, "model" | "side" | "btw"> | null {const match = /^\/(plan|default)\s*$/i.exec(text.trim());if (!match) {return null;diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsxindex d394c67c9df..9b1299aee1d 100644--- a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx@@ -31,6 +31,7 @@ vi.mock("../state/session", () => ({vi.mock("../state/entities", () => ({useQuietThreadShell: () => null,useProject: () => null,+ readThreadShell: () => null,}));vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));vi.mock("../composerDraftStore", async () => {@@ -56,6 +57,8 @@ vi.mock("../state/use-atom-command", () => ({// The commands are replaced above; importing their runtime would connect a client.vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}, write: {} } }));vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));+vi.mock("../state/threads", () => ({ threadEnvironment: { delete: {} } }));+vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: () => null } }));vi.mock("@t3tools/client-runtime/state/runtime", () => ({isAtomCommandInterrupted: () => false,}));diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.ts b/apps/web/src/hooks/useRightPanelSurfaceClose.tsindex e79042ec375..305c2a73dd3 100644--- a/apps/web/src/hooks/useRightPanelSurfaceClose.ts+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.ts@@ -1,8 +1,10 @@import {+ AuthOrchestrationOperateScope,AuthPreviewOperateScope,AuthTerminalOperateScope,type ScopedThreadRef,} from "@t3tools/contracts";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";import { closePreviewSession } from "../components/preview/closePreviewSession";@@ -17,19 +19,27 @@ import {useRightPanelStore,type RightPanelSurface,} from "../rightPanelStore";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { readThreadShell } from "../state/entities";import { previewEnvironment } from "../state/preview";import { readEnvironmentScope, useEnvironmentScope } from "../state/session";+import { environmentShell } from "../state/shell";+import { threadEnvironment } from "../state/threads";import { useAtomCommand } from "../state/use-atom-command";import { useTerminalUiStateStore } from "../terminalUiStateStore";import { useStableCallback } from "./useStableCallback";-/** Closing releases preview and terminal sessions. Agent-driven browsers and terminal tabs require confirmation. */+/**+ * Closing releases preview and terminal sessions, and deletes a side chat that never ran.+ * Agent-driven browsers and terminal tabs require confirmation.+ */export function useRightPanelSurfaceClose(input: {readonly threadRef: ScopedThreadRef | null;readonly terminalLabelsById: ReadonlyMap<string, string>;}) {const { threadRef, terminalLabelsById } = input;const closePreview = useAtomCommand(previewEnvironment.close, "preview close");+ const deleteThread = useAtomCommand(threadEnvironment.delete, "side chat delete");const canOperatePreview = useEnvironmentScope(threadRef?.environmentId ?? null,AuthPreviewOperateScope,@@ -60,6 +70,21 @@ export function useRightPanelSurfaceClose(input: {terminalActions.closeTerminalSession(terminalId, ref);}}+ if (+ surface.kind === "side-chat" &&+ readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope) &&+ // A live shell without the side chat means it is already deleted.+ !(+ appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live" &&+ readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId)) === null+ )+ ) {+ // The server keeps a side chat with a run or message. Reopen skips one it deleted.+ void deleteThread({+ environmentId: ref.environmentId,+ input: { threadId: surface.threadId, onlyIfUnused: true },+ });+ }};const closeAfterAgentBrowserConfirmation = (toClose: readonly RightPanelSurface[],diff --git a/apps/web/src/lib/desktopPasteAsText.ts b/apps/web/src/lib/desktopPasteAsText.tsindex 1f93560d1a5..4efdb90038b 100644--- a/apps/web/src/lib/desktopPasteAsText.ts+++ b/apps/web/src/lib/desktopPasteAsText.ts@@ -2,14 +2,19 @@ import type { DesktopBridge } from "@t3tools/contracts";export const DESKTOP_PASTE_AS_TEXT_EVENT = "t3:paste-as-text";-/** Arm composer paste handling before Electron delivers the native clipboard event. */+/**+ * Arm composer paste handling before Electron delivers the native clipboard event. The event+ * bubbles from the focused element, so a composer can listen on its own form or on `target`.+ */export function installDesktopPasteAsText(bridge: Pick<DesktopBridge, "onMenuAction" | "pasteAsText"> | undefined,target: EventTarget,): (() => void) | undefined {return bridge?.onMenuAction((action) => {if (action !== "paste-as-text") return;- target.dispatchEvent(new Event(DESKTOP_PASTE_AS_TEXT_EVENT));+ (document.activeElement ?? target).dispatchEvent(+ new Event(DESKTOP_PASTE_AS_TEXT_EVENT, { bubbles: true }),+ );void bridge.pasteAsText();});}diff --git a/apps/web/src/lib/sideChatPane.ts b/apps/web/src/lib/sideChatPane.tsnew file mode 100644index 00000000000..3bbf09f24bc--- /dev/null+++ b/apps/web/src/lib/sideChatPane.ts@@ -0,0 +1,31 @@+import type { OrchestrationV2ThreadShell, ScopedThreadRef } from "@t3tools/contracts";++import type { ToolCallDiffTarget } from "../diffPanelStore";+import { useRightPanelStore } from "../rightPanelStore";++/** Whether an event started in the side chat pane (`data-side-chat-pane`), which the main chat ignores. */+export function isInSideChatPane(target: EventTarget | null): boolean {+ return target instanceof Element && target.closest("[data-side-chat-pane]") !== null;+}++/**+ * Opens an embedded side chat's tool diffs in its parent's diff panel and runs its shell commands+ * in the parent's terminal drawer, since the embedded view hides its own. Other panel actions reach+ * the parent through `hostRightPanel`; diff selection and the drawer are not panel state.+ */+export interface SideChatParentPanel {+ readonly openToolDiff: (target: ToolCallDiffTarget) => void;+ readonly runShellCommand: (command: string) => void;+}++/** Opens `thread` in its tab when it is a side chat of `parentRef`; false for any other thread. */+export function openSideChatTab(+ parentRef: ScopedThreadRef,+ thread: Pick<OrchestrationV2ThreadShell, "id" | "lineage"> | null,+): boolean {+ if (thread?.lineage.sideChat !== true || thread.lineage.parentThreadId !== parentRef.threadId) {+ return false;+ }+ useRightPanelStore.getState().openSideChat(parentRef, thread.id);+ return true;+}diff --git a/apps/web/src/reopenClosedView.test.ts b/apps/web/src/reopenClosedView.test.tsindex bd33011e978..04532373624 100644--- a/apps/web/src/reopenClosedView.test.ts+++ b/apps/web/src/reopenClosedView.test.ts@@ -134,6 +134,7 @@ describe("planNextReopen", () => {environmentKnown: true,catalogReady: true,ownerExists: true,+ sideChatExists: true,shellLive: true,panel: { isOpen: false, activeSurfaceId: null, surfaces: [] },};@@ -163,6 +164,18 @@ describe("planNextReopen", () => {[],"b",],+ [+ "skips but keeps a side chat deleted from a live shell",+ [{ ...known, sideChatExists: false }, known],+ [],+ "b",+ ],+ [+ "waits when a cached shell lacks the side chat",+ [{ ...known, sideChatExists: false, shellLive: false }, known],+ [],+ null,+ ],["waits when a cached shell lacks the thread",[{ ...known, ownerExists: false, shellLive: false }, known],diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.tsindex 2ae5e0874e1..005887ad81f 100644--- a/apps/web/src/reopenClosedView.ts+++ b/apps/web/src/reopenClosedView.ts@@ -14,6 +14,8 @@ export interface ReopenOwnerState {environmentKnown: boolean;catalogReady: boolean;ownerExists: boolean;+ /** False only for a side chat tab whose thread is gone from the shell. */+ sideChatExists: boolean;shellLive: boolean;panel: ThreadRightPanelState;}@@ -30,7 +32,7 @@ export function planNextReopen(drop.push(entry);continue;}- if (!owner.ownerExists) {+ if (!owner.ownerExists || !owner.sideChatExists) {if (owner.shellLive) continue;break;}@@ -134,6 +136,9 @@ export async function reopenClosedView(case "pull-request":panels.openPullRequest(ref, surface);break;+ case "side-chat":+ panels.openSideChat(ref, surface.threadId);+ break;default:panels.open(ref, surface.kind);}diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.tsindex 764fad8879b..ec0f4e87c12 100644--- a/apps/web/src/rightPanelStore.test.ts+++ b/apps/web/src/rightPanelStore.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";import { useClosedViewStore } from "./closedViewStore";import { reopenClosedView } from "./reopenClosedView";import {+ hostRightPanel,migratePersistedRightPanelState,pullRequestSurface,pullRequestSurfaceId,@@ -39,6 +40,23 @@ async function reloadRightPanelStore() {}describe("rightPanelStore", () => {+ it("opens a hosted side chat's panel actions in its parent's panel until unhosted", () => {+ const store = useRightPanelStore.getState();+ const unhost = hostRightPanel(refB, refA);+ store.openFile(refB, "src/app.ts");+ expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id).toBe(+ "file:src/app.ts",+ );+ expect(+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB).surfaces,+ ).toEqual([]);+ unhost();+ store.openFile(refB, "src/app.ts");+ expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refB)?.id).toBe(+ "file:src/app.ts",+ );+ });+it("records single and bulk tab closes, newest first", () => {const store = useRightPanelStore.getState();const pr = pullRequestSurface({diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex ea043c0298b..6d9c692d645 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -21,6 +21,7 @@ const RIGHT_PANEL_KINDS = ["terminal","pull-request","pull-requests",+ "side-chat",] as const;export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];@@ -74,7 +75,8 @@ export type RightPanelSurface =url?: string;detailTab?: PullRequestDetailTab;}- | { id: "pull-requests"; kind: "pull-requests" };+ | { id: "pull-requests"; kind: "pull-requests" }+ | { id: `side-chat:${string}`; kind: "side-chat"; threadId: ThreadId };const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";const RIGHT_PANEL_STORAGE_VERSION = 14;@@ -121,8 +123,9 @@ interface RightPanelStoreState {) => boolean;open: (ref: ScopedThreadRef,- kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,+ kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "side-chat">,) => void;+ openSideChat: (ref: ScopedThreadRef, threadId: ThreadId) => void;openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;@@ -180,7 +183,7 @@ interface RightPanelStoreState {toggleVisibility: (ref: ScopedThreadRef) => void;toggle: (ref: ScopedThreadRef,- kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,+ kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request" | "side-chat">,) => void;setThreadPanelOpen: (ref: ScopedThreadRef,@@ -203,7 +206,7 @@ const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {};const singletonSurface = (- kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,+ kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request" | "side-chat">,): RightPanelSurface => {switch (kind) {case "diff":@@ -382,11 +385,39 @@ const automaticUpdate = (...updateThread(state, threadKey, updater),});+// A side chat pane has no panel of its own, so its panel actions open in its parent's panel.+const panelHosts = new Map<string, ScopedThreadRef>();++/** Routes `guest`'s panel actions to `host`'s panel until the returned cleanup runs. */+export function hostRightPanel(guest: ScopedThreadRef, host: ScopedThreadRef): () => void {+ const guestKey = scopedThreadKey(guest);+ panelHosts.set(guestKey, host);+ return () => {+ if (panelHosts.get(guestKey) === host) panelHosts.delete(guestKey);+ };+}++/** The thread whose panel shows `ref`'s panel actions, so it also owns their browser tabs. */+export function rightPanelHostRef(ref: ScopedThreadRef): ScopedThreadRef {+ return panelHosts.get(scopedThreadKey(ref)) ?? ref;+}+const userAction = (state: RightPanelStoreState,- threadKey: string,+ guestKey: string,updater: (current: ThreadRightPanelState) => ThreadRightPanelState,closesView = false,+): Partial<RightPanelStoreState> => {+ const host = panelHosts.get(guestKey);+ const threadKey = host === undefined ? guestKey : scopedThreadKey(host);+ return userActionOnThread(state, threadKey, updater, closesView);+};++const userActionOnThread = (+ state: RightPanelStoreState,+ threadKey: string,+ updater: (current: ThreadRightPanelState) => ThreadRightPanelState,+ closesView: boolean,): Partial<RightPanelStoreState> => ({...updateThread(state, threadKey, (current) => {const next = updater(current);@@ -682,6 +713,12 @@ export const useRightPanelStore = create<RightPanelStoreState>()();}),),+ openSideChat: (ref, threadId) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) =>+ upsertSurface(current, { id: `side-chat:${threadId}`, kind: "side-chat", threadId }),+ ),+ ),renameDevice: (ref, surfaceId, title) =>set((state) =>userAction(state, scopedThreadKey(ref), (current) => ({diff --git a/docs/orchestration-v2/thread-lineage-and-context-transfer.md b/docs/orchestration-v2/thread-lineage-and-context-transfer.mdindex aafaad5176e..2bdb17e4234 100644--- a/docs/orchestration-v2/thread-lineage-and-context-transfer.md+++ b/docs/orchestration-v2/thread-lineage-and-context-transfer.md@@ -240,6 +240,8 @@ type AppThreadLineage = {parentThreadId: ThreadId | null;relationshipToParent: "fork" | "subagent" | null;rootThreadId: ThreadId;+ // A side chat: a fork shown only inside its parent. The fork planner sets it from `thread.fork`.+ sideChat?: boolean;};```diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex 062fd749a17..9dbaceae8ed 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -283,6 +283,30 @@ To choose what the thread details card shows, right-click the card or openshortcuts, such as Open in editor and project scripts. **Reset to default** bringsback the standard rows.+## Side chats++A side chat lets you ask a question about a thread without adding to it. It starts+with what the thread knows, and the thread keeps working while you ask.++On web and desktop, start a message with `/side` or `/btw`, then your question.+You can also choose **Side chat** from the **+** menu in the right panel. The side+chat opens as a tab there, with its own composer. Side chats do not show in the+sidebar. Find one again under **Side chats** in thread details.++A side chat works in the same folder as the thread. Its first reply asks before it+edits files or runs commands. After that, it uses the permission mode you choose+in its composer.++To use what you learned, choose **Bring back**. The thread gets the side chat with+your next message there. Bring back is available while the thread is idle.++Closing a side chat you never sent a message in deletes it. To delete one you used,+choose **Delete** at the top of the side chat. Deleting a thread also deletes its+side chats.++On mobile, a thread lists its side chats above the composer. Tap one to open it and+answer its questions.+## Snooze until laterTo change the choices in the snooze menu, open **Settings → Threads → Snooze options**.diff --git a/evals/mcp-tool-use/cases/side-chats.ndjson b/evals/mcp-tool-use/cases/side-chats.ndjsonnew file mode 100644index 00000000000..1dd4c70d366--- /dev/null+++ b/evals/mcp-tool-use/cases/side-chats.ndjson@@ -0,0 +1,2 @@+{"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"}]}}+{"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"}]}}diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.tsindex 7baefcbbcc6..7cad56ae980 100644--- a/evals/mcp-tool-use/run.ts+++ b/evals/mcp-tool-use/run.ts@@ -39,6 +39,8 @@ import { EnvironmentId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, ThreadId } from "@t3import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";import { formatThreadLink } from "@t3tools/shared/threadLinks";import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts";+import { makeSideChatContext } from "../../apps/server/src/orchestration-v2/ContextHandoffService.ts";+import { withInlineContext } from "../../apps/server/src/orchestration-v2/ContextHandoffDelivery.ts";import { AttachmentToolkit } from "../../apps/server/src/mcp/toolkits/attachment/tools.ts";import { DeviceToolkit } from "../../apps/server/src/mcp/toolkits/device/tools.ts";import { EnvironmentToolkit } from "../../apps/server/src/mcp/toolkits/environment/tools.ts";@@ -249,6 +251,10 @@ export const McpToolUseCase = Schema.Struct({shellMocks: Schema.optional(Schema.Array(Schema.Struct({ match: Schema.String, output: Schema.String })),),+ /** The thread is a side chat's first turn: T3 puts the parent's digest ahead of `prompt`. */+ sideChat: Schema.optional(+ Schema.Struct({ parentThreadId: Schema.String, digest: Schema.Array(Schema.String) }),+ ),}),prompt: Schema.String,/** Records for the context chips `prompt` links, projected as T3 sends them. */@@ -870,10 +876,21 @@ export const buildMessages = (sample: Sample) => {}if (turn.text) push(turn.role, text(turn.text));}- const prompt =+ const userText =testCase.promptContext === undefined? testCase.prompt: projectComposerContextForProvider({ text: testCase.prompt, ...testCase.promptContext });+ const sideChat = testCase.setup.sideChat;+ const prompt =+ sideChat === undefined+ ? userText+ : withInlineContext(+ makeSideChatContext({+ parentThreadId: ThreadId.make(sideChat.parentThreadId),+ digest: sideChat.digest,+ }),+ userText,+ );const childPrompt = () => taskPrompt({ task: prompt, role: delegateRole });push("user", text(role === "delegated-child" ? childPrompt() : prompt));// Claude Code gives a subagent its SubagentStart hooks' context as a reminder after the task.diff --git a/packages/client-runtime/src/composerThreadItems.ts b/packages/client-runtime/src/composerThreadItems.tsindex e3172715ab2..32adee581a6 100644--- a/packages/client-runtime/src/composerThreadItems.ts+++ b/packages/client-runtime/src/composerThreadItems.ts@@ -1,8 +1,9 @@-import type {- EnvironmentId,- EnvironmentMachineKind,- ScopedThreadRef,- ThreadId,+import {+ isListedThreadLineage,+ type EnvironmentId,+ type EnvironmentMachineKind,+ type ScopedThreadRef,+ type ThreadId,} from "@t3tools/contracts";import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";@@ -24,7 +25,7 @@ export interface ComposerThreadItem {/*** Threads to reference from the composer, matched and ranked like the command- * palette, without subagent threads. The agent reads threads on its own server+ * palette, without subagent or side chat threads. The agent reads threads on its own server* and on the machines it links to, so candidates stay within those, and a linked* machine's threads say which machine they are on.*/@@ -46,7 +47,7 @@ export function matchComposerThreadItems(input: {input.linkedEnvironments.has(shell.environmentId)) &&shell.id !== input.excludeThreadId &&shell.archivedAt === null &&- shell.lineage.relationshipToParent !== "subagent",+ isListedThreadLineage(shell.lineage),);return rankSearchItems(candidates, (shell, options) =>scoreThreadSearch(query, threadSearchSubject(shell, null), input.now, {diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex 294a9baf6e9..f7ca0d575d0 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -82,7 +82,10 @@ export interface ThreadCommandInput extends CommandMetadata {readonly threadId: ThreadId;}-export type DeleteThreadInput = ThreadCommandInput;+export interface DeleteThreadInput extends ThreadCommandInput {+ /** The server deletes only a thread with no runs and no messages. */+ readonly onlyIfUnused?: boolean;+}export type ArchiveThreadInput = ThreadCommandInput;export type UnarchiveThreadInput = ThreadCommandInput;export type SettleThreadInput = ThreadCommandInput;@@ -218,6 +221,12 @@ export interface ForkThreadFromRunInput extends CommandMetadata {readonly title?: string;}+export interface ForkSideChatInput extends CommandMetadata {+ readonly sourceThreadId: ThreadId;+ readonly targetThreadId: ThreadId;+ readonly title?: string;+}+export interface MergeThreadBackInput extends CommandMetadata {readonly sourceThreadId: ThreadId;readonly targetThreadId: ThreadId;@@ -401,7 +410,6 @@ export const createThread = Effect.fn("EnvironmentCommands.createThread")(functifunction simpleThreadCommand(type:- | "thread.delete"| "thread.archive"| "thread.unarchive"| "thread.settle"@@ -418,7 +426,12 @@ function simpleThreadCommand(export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (input: DeleteThreadInput,) {- return yield* simpleThreadCommand("thread.delete", input);+ return yield* dispatch({+ type: "thread.delete",+ commandId: yield* allocateCommandId(input),+ threadId: input.threadId,+ ...(input.onlyIfUnused === undefined ? {} : { onlyIfUnused: input.onlyIfUnused }),+ });});export type CloseGuestShareInput = ThreadCommandInput;@@ -974,6 +987,23 @@ export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRu});});+/** Forks the thread's latest stable point into a hidden side chat; works while it runs. */+export const forkSideChat = Effect.fn("EnvironmentCommands.forkSideChat")(function* (+ input: ForkSideChatInput,+) {+ return yield* dispatch({+ type: "thread.fork",+ commandId: yield* allocateCommandId(input),+ createdBy: "user",+ creationSource: input.creationSource ?? "web",+ sourceThreadId: input.sourceThreadId,+ targetThreadId: input.targetThreadId,+ sourcePoint: { type: "latest_stable" },+ sideChat: true,+ ...(input.title === undefined ? {} : { title: input.title }),+ });+});+export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (input: MergeThreadBackInput,) {diff --git a/packages/client-runtime/src/promptLinks.test.ts b/packages/client-runtime/src/promptLinks.test.tsindex 12a73ddf915..20e8b2b7df7 100644--- a/packages/client-runtime/src/promptLinks.test.ts+++ b/packages/client-runtime/src/promptLinks.test.ts@@ -6,12 +6,14 @@ import {ThreadId,type PullRequestLinkedThreadsResult,type RepositoryIdentity,+ type ThreadPullRequestLink,} from "@t3tools/contracts";import { AsyncResult } from "effect/reactivity";import { describe, expect, it } from "vite-plus/test";import {findPromptLinkProjects,+ findPromptLinkPullRequestThread,pickPromptLinkPullRequestThread,resolvePromptLinkModelSelection,} from "./promptLinks.ts";@@ -54,6 +56,36 @@ describe("findPromptLinkProjects", () => {});});+describe("findPromptLinkPullRequestThread", () => {+ it("takes the newest linked thread, never a side chat that inherited the link", () => {+ const link: ThreadPullRequestLink = {+ host: "github.com",+ repository: "acme/web",+ number: 7,+ url: "https://github.com/acme/web/pull/7",+ source: "manual",+ linkedAt: "2026-01-01T00:00:00.000Z",+ snapshot: null,+ stack: null,+ };+ const thread = (id: string, updatedAt: string, sideChat?: boolean) => ({+ id,+ updatedAt,+ pullRequests: [link],+ ...(sideChat === undefined ? {} : { lineage: { sideChat } }),+ });+ const found = findPromptLinkPullRequestThread(+ [+ thread("old", "2026-01-01T00:00:00.000Z"),+ thread("parent", "2026-01-02T00:00:00.000Z", false),+ thread("side-chat", "2026-01-03T00:00:00.000Z", true),+ ],+ { owner: "acme", name: "web", number: 7 },+ );+ expect(found?.id).toBe("parent");+ });+});+describe("pickPromptLinkPullRequestThread", () => {it("takes the first open thread in order once every earlier lookup has answered", () => {const laptop = EnvironmentId.make("laptop");diff --git a/packages/client-runtime/src/promptLinks.ts b/packages/client-runtime/src/promptLinks.tsindex 2c72280745b..edb13ce3f02 100644--- a/packages/client-runtime/src/promptLinks.ts+++ b/packages/client-runtime/src/promptLinks.ts@@ -43,6 +43,7 @@ export function findPromptLinkPullRequestThread<readonly updatedAt: string;readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;+ readonly lineage?: { readonly sideChat?: boolean | undefined } | undefined;},>(threads: ReadonlyArray<T>, pullRequest: PromptLinkPullRequest): T | undefined {const key = threadPullRequestKeyOf({@@ -53,6 +54,8 @@ export function findPromptLinkPullRequestThread<let latest: T | undefined;for (const thread of threads) {if (latest !== undefined && thread.updatedAt <= latest.updatedAt) continue;+ // Side chats inherit their parent's links but stay hidden.+ if (thread.lineage?.sideChat === true) continue;const linked = visibleThreadPullRequests(threadPullRequestsOf(thread)).some((link) => threadPullRequestKeyOf(link) === key,);diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex ac40471a853..8e04837b8b6 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -216,6 +216,17 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {);}+/** An async question waits for an answer only once its run stops working. */+export function shellHasPendingUserInput(thread: OrchestrationV2ThreadShell): boolean {+ const status = shellRuntime(thread)?.status;+ // Waiting runs have ended their provider turn and are only draining effects.+ const working = status === "preparing" || status === "starting" || status === "running";+ return (+ thread.pendingRuntimeRequest?.kind === "user_input" &&+ (thread.pendingRuntimeRequest.blocking !== false || !working)+ );+}+// Only work the agent waits on holds it: commands and monitors it left running// unmarked, such as a dev server, present the run's own status. The// server suppresses the roster while an interruptible activity run exists, so a@@ -277,11 +288,6 @@ export function presentThreadShell(assistantMessageId: null,} satisfies ThreadRunSummary);const runtime = shellRuntime(thread);- // Waiting runs have ended their provider turn and are only draining effects.- const runtimeIsWorking =- runtime?.status === "preparing" ||- runtime?.status === "starting" ||- runtime?.status === "running";return {environmentId,id: thread.id,@@ -315,9 +321,7 @@ export function presentThreadShell(thread.pendingRuntimeRequest !== null &&thread.pendingRuntimeRequest.kind !== "user_input" &&thread.pendingRuntimeRequest.kind !== "auth_refresh",- hasPendingUserInput:- thread.pendingRuntimeRequest?.kind === "user_input" &&- (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),+ hasPendingUserInput: shellHasPendingUserInput(thread),pendingSubagentRequest,pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,hasActionableProposedPlan: thread.hasActionableProposedPlan,diff --git a/packages/client-runtime/src/state/olderSettledThreads.ts b/packages/client-runtime/src/state/olderSettledThreads.tsindex 86f7f86f0d1..c4d7e2f6652 100644--- a/packages/client-runtime/src/state/olderSettledThreads.ts+++ b/packages/client-runtime/src/state/olderSettledThreads.ts@@ -1,4 +1,5 @@import {+ isListedThreadLineage,isOlderSettledThreadShell,ORCHESTRATION_V2_WS_METHODS,type EnvironmentId,@@ -77,7 +78,7 @@ export function olderSettledCountKey(for (const sequence of removedAt.values()) lastRemoval = Math.max(lastRemoval, sequence);const rows: string[] = [];for (const thread of threads) {- if (thread.lineage.relationshipToParent === "subagent") continue;+ if (!isListedThreadLineage(thread.lineage)) continue;const older = isOlderSettledThreadShell(thread, beforeMs);if (older || DateTime.toEpochMillis(thread.createdAt) < beforeMs) {rows.push(`${thread.id}:${older ? 1 : 0}`);diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex 0f34a926676..e0aae375ec5 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -27,6 +27,7 @@ import {deleteThread,editQueuedRun,interruptThreadTurn,+ forkSideChat,forkThreadFromRun,markThreadUnread,mergeThreadBack,@@ -307,6 +308,15 @@ export function createThreadEnvironmentAtoms<R, E>(key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),},}),+ forkSideChat: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:fork-side-chat",+ execute: forkSideChat,+ scheduler,+ concurrency: {+ mode: "serial",+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),+ },+ }),mergeBack: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:merge-back",execute: mergeThreadBack,diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.tsindex fda1054064f..8807162eb99 100644--- a/packages/client-runtime/src/state/threadShell.test.ts+++ b/packages/client-runtime/src/state/threadShell.test.ts@@ -156,6 +156,101 @@ describe("v2 thread shell lists", () => {registry.dispose();});+ it("rolls a side chat's questions and approvals up to its parent row", () => {+ const { registry, threads, snapshotAtom } = makeHarness();+ const root = v2ThreadShell;+ const sideChat = {+ ...root,+ id: ThreadId.make("side-chat"),+ status: "running" as const,+ activityRunStatus: "running" as const,+ latestRunId: RunId.make("side-chat-run"),+ lineage: {+ ...root.lineage,+ parentThreadId: root.id,+ relationshipToParent: "fork" as const,+ sideChat: true,+ },+ };+ const request = { id: RuntimeRequestId.make("ask"), createdAt: v2Now };+ const parentRef = { environmentId, threadId: root.id };+ const parent = threads.threadShellAtom(parentRef);+ const inputs = threads.childThreadInputsAtom(parentRef);+ const disposeParent = registry.mount(parent);+ const disposeInputs = registry.mount(inputs);+ const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);+ const withRequest = (+ kind: "user_input" | "command",+ options: { readonly blocking?: boolean; readonly settled?: boolean } = {},+ ) =>+ registry.set(snapshotAtom(environmentId), {+ ...v2ShellSnapshot,+ threads: [+ root,+ {+ ...sideChat,+ ...(options.settled ? { status: "completed" as const, activityRunStatus: null } : {}),+ pendingRuntimeRequest: {+ ...request,+ kind,+ ...(options.blocking === undefined ? {} : { blocking: options.blocking }),+ },+ },+ ],+ });++ withRequest("user_input");+ expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");+ expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs input");+ expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([+ root.id,+ ]);++ // An async question waits while the side chat works, like its own row's indicator.+ withRequest("user_input", { blocking: false });+ expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();+ expect(registry.get(inputs)).toEqual([]);+ withRequest("user_input", { blocking: false, settled: true });+ expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");++ withRequest("command");+ expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");+ expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs approval");++ const helper = {+ ...sideChat,+ id: ThreadId.make("side-chat-helper"),+ creationSource: "mcp" as const,+ lineage: {+ ...sideChat.lineage,+ parentThreadId: sideChat.id,+ relationshipToParent: "subagent" as const,+ sideChat: false,+ },+ pendingRuntimeRequest: { ...request, kind: "command" as const },+ };+ const sideChats = threads.sideChatsAtom(parentRef);+ const disposeSideChats = registry.mount(sideChats);+ registry.set(snapshotAtom(environmentId), {+ ...v2ShellSnapshot,+ threads: [root, sideChat, helper],+ });+ expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");+ expect(+ registry.get(sideChats).map((thread) => [thread.id, thread.pendingSubagentRequest]),+ ).toEqual([[sideChat.id, "approval"]]);++ registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, sideChat] });+ expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();+ expect(registry.get(sideChats).map((thread) => thread.pendingSubagentRequest)).toEqual([null]);+ expect(registry.get(inputs)).toEqual([]);+ disposeSideChats();+ disposeNavigation();+ disposeInputs();+ disposeParent();+ registry.dispose();+ });+it("brings a parent back from Working while a nested subagent waits for approval", () => {const { registry, threads, snapshotAtom } = makeHarness();const child = {diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.tsindex 15718da1eca..b7a6eebe571 100644--- a/packages/client-runtime/src/state/threadShell.ts+++ b/packages/client-runtime/src/state/threadShell.ts@@ -6,12 +6,16 @@ import type {ScopedThreadRef,ThreadId,} from "@t3tools/contracts";-import { isProviderNativeSubagentThread, OrchestrationV2ThreadShell } from "@t3tools/contracts";+import {+ isListedThreadLineage,+ isProviderNativeSubagentThread,+ OrchestrationV2ThreadShell,+} from "@t3tools/contracts";import * as Schema from "effect/Schema";import { Atom } from "effect/reactivity";import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";-import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";+import { presentThreadShell, shellHasPendingUserInput, threadRuntimeIsActive } from "./models.ts";import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";import {arrayElementsEqual,@@ -26,6 +30,11 @@ const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();const EMPTY_SUBAGENT_REQUESTS: ReadonlyMap<ThreadId, PendingSubagentRequest> = new Map();+const EMPTY_SIDE_CHATS_BY_PARENT: ReadonlyMap<+ ThreadId,+ ReadonlyArray<OrchestrationV2ThreadShell>+> = new Map();+const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = Object.freeze([]);const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<ProjectId,ReadonlyArray<ScopedThreadRef>@@ -47,7 +56,7 @@ const isChildRunLive = (/*** Whether a thread shows under its parent rather than in thread lists: a- * subagent, or a task a linked environment delegated here whose parent the+ * subagent, a side chat, or a task a linked environment delegated here whose parent the* client lists (`delegatedUnderParent`, by thread key). A task whose parent* the client cannot list stays in the lists, so its work is never out of reach.*/@@ -56,7 +65,7 @@ export function isShownUnderParent(lineage: OrchestrationV2ThreadShell["lineage"],delegatedUnderParent: ReadonlySet<string>,): boolean {- return lineage.relationshipToParent === "subagent" || delegatedUnderParent.has(threadKey(ref));+ return !isListedThreadLineage(lineage) || delegatedUnderParent.has(threadKey(ref));}/** Provider-native@@ -75,10 +84,24 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReqreturn kind === "user_input" ? "user_input" : "approval";}+/**+ * A side chat asks its user directly, so questions roll up to the parent as well as approvals,+ * when its own row would show them.+ */+function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {+ const kind = thread.pendingRuntimeRequest?.kind;+ if (kind === undefined || kind === "auth_refresh" || thread.lineage.sideChat !== true) {+ return null;+ }+ if (kind !== "user_input") return "approval";+ return shellHasPendingUserInput(thread) ? "user_input" : null;+}+/*** The threads to flag for a subagent's live approval, up its- * subagent chain. `delegated` are tasks this environment's threads delegated- * to linked environments, with what each one, or its own subagents, asks.+ * subagent chain and through a side chat to its parent. `delegated` are tasks this+ * environment's threads delegated to linked environments, with what each one, or its+ * own subagents, asks.*/function pendingSubagentRequestsByThread(threads: ReadonlyArray<OrchestrationV2ThreadShell>,@@ -103,13 +126,23 @@ function pendingSubagentRequestsByThread(if (requests.get(parentId) !== "approval") requests.set(parentId, request);const parent = byId.get(parentId);parentId =- parent?.lineage.relationshipToParent === "subagent" ? parent.lineage.parentThreadId : null;+ parent?.lineage.relationshipToParent === "subagent" || parent?.lineage.sideChat === true+ ? parent.lineage.parentThreadId+ : null;}};for (const child of threads) {+ const parentId = child.lineage.parentThreadId;+ if (child.lineage.sideChat === true) {+ const request = sideChatRequest(child);+ if (parentId !== null && request !== null && requests.get(parentId) !== "approval") {+ requests.set(parentId, request);+ }+ continue;+ }if (child.lineage.relationshipToParent !== "subagent") continue;const request = subagentRequest(child);- if (request !== null) flag(child.lineage.parentThreadId, request, new Set([child.id]));+ if (request !== null) flag(parentId, request, new Set([child.id]));}for (const task of delegated) flag(task.parentThreadId, task.request, new Set());return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;@@ -123,13 +156,16 @@ const sameRequests = ([...right].every(([threadId, request]) => left.get(threadId) === request);export function childThreadInputsTitle(- children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals">>,+ children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals" | "lineage">>,): string {const approvals = children.filter((child) => child.hasPendingApprovals).length;const need = approvals === 0 ? "input" : approvals === children.length ? "approval" : "you";+ const sideChats = children.filter((child) => child.lineage.sideChat === true).length;+ const noun =+ sideChats === children.length ? "side chat" : sideChats === 0 ? "subagent" : "thread";return children.length === 1- ? `Subagent needs ${need}`- : `${children.length} subagents need ${need}`;+ ? `${noun === "side chat" ? "Side chat" : "Subagent"} needs ${need}`+ : `${children.length} ${noun}s need ${need}`;}const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);@@ -216,6 +252,23 @@ export function createEnvironmentThreadShellAtoms(input: {}).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),);+ // Side chats by parent, built once per change for every parent's row. Without side chats+ // it stays the same empty map, so those rows do no work.+ const environmentSideChatsByParentAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get) => {+ let byParent: Map<ThreadId, OrchestrationV2ThreadShell[]> | undefined;+ for (const thread of get(environmentThreadsAtom(environmentId))) {+ const parentId = thread.lineage.parentThreadId;+ if (thread.lineage.sideChat !== true || parentId === null) continue;+ byParent ??= new Map();+ const siblings = byParent.get(parentId);+ if (siblings) siblings.push(thread);+ else byParent.set(parentId, [thread]);+ }+ return byParent ?? EMPTY_SIDE_CHATS_BY_PARENT;+ }).pipe(Atom.withLabel(`environment-side-chats-by-parent:${environmentId}`)),+ );+// What an environment's own subagents ask. Kept apart from the tasks other// environments run for it, so two environments delegating to each other// never read each other's totals.@@ -399,7 +452,10 @@ export function createEnvironmentThreadShellAtoms(input: {for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {for (const thread of get(environmentThreadsAtom(environmentId))) {const parent = thread.lineage.parentThreadId;- if (parent !== null && thread.lineage.relationshipToParent === "subagent") {+ if (+ parent !== null &&+ (thread.lineage.relationshipToParent === "subagent" || thread.lineage.sideChat === true)+ ) {addChild({ environmentId, threadId: parent }, environmentId, thread);} else if (thread.delegatedFrom !== undefined) {addChild(thread.delegatedFrom, environmentId, thread);@@ -415,7 +471,7 @@ export function createEnvironmentThreadShellAtoms(input: {if (seen.has(childKey)) continue;seen.add(childKey);pending.push(childKey);- if (subagentRequest(thread) !== null) {+ if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) {next.push(scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))),);@@ -441,6 +497,39 @@ export function createEnvironmentThreadShellAtoms(input: {}).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));});+ // A parent's side chats. Rows read only ids, titles and whether one needs the user, so+ // streaming updates keep the old array.+ const sideChatsAtomFamily = Atom.family((key: string) => {+ const ref = parseThreadKey(key);+ let previous = EMPTY_THREAD_SHELLS;+ return Atom.make((get) => {+ const sideChats = get(environmentSideChatsByParentAtom(ref.environmentId)).get(ref.threadId);+ if (sideChats === undefined) {+ previous = EMPTY_THREAD_SHELLS;+ return previous;+ }+ const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));+ const next = sideChats.map((thread) =>+ scopedThread(ref.environmentId, thread, subagentRequests),+ );+ if (+ previous.length === next.length &&+ previous.every(+ (thread, index) =>+ thread.id === next[index]?.id &&+ thread.title === next[index]?.title &&+ thread.hasPendingApprovals === next[index]?.hasPendingApprovals &&+ thread.hasPendingUserInput === next[index]?.hasPendingUserInput &&+ thread.pendingSubagentRequest === next[index]?.pendingSubagentRequest,+ )+ ) {+ return previous;+ }+ previous = next;+ return next;+ }).pipe(Atom.withLabel(`environment-side-chats:${key}`));+ });+const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {const projectRefs = parseProjectRefCollectionKey(key);let previous: ReadonlyArray<EnvironmentThreadShell> = [];@@ -583,5 +672,6 @@ export function createEnvironmentThreadShellAtoms(input: {threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),+ sideChatsAtom: (ref: ScopedThreadRef) => sideChatsAtomFamily(threadKey(ref)),};}diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 326f2f675af..117f75bc3d3 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -81,6 +81,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({),pullRequests: Schema.optionalKey(Schema.Boolean),pullRequestChecks: Schema.optionalKey(Schema.Boolean),+ /** Side chats: hidden `lineage.sideChat` forks. Older servers ignore the fork flag. */+ sideChats: Schema.optionalKey(Schema.Boolean),/** Every protocol-2 server sends this; older mobile builds still read it. */inlineMessageContext: Schema.optionalKey(Schema.Boolean),requiredWorktreeBootstrap: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex d20da578025..1c80128f8bb 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -154,9 +154,14 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({parentThreadId: Schema.NullOr(ThreadId),relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),rootThreadId: ThreadId,+ sideChat: Schema.optional(Schema.Boolean),});export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type;+/** Subagents and side chats live inside their parent's view, never in thread lists. */+export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean =>+ lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true;+export const OrchestrationV2ContextTransferType = Schema.Literals(["fork","provider_handoff",@@ -704,6 +709,24 @@ export function orchestrationV2RunWorkStartedAt(return run.workStartedAt ?? run.startedAt ?? run.requestedAt;}+/**+ * Work started now would run in the project checkout, not the worktree the thread asked for. A+ * failed or interrupted setup leaves the request standing until a worktree exists.+ */+export function orchestrationV2WorktreePending(+ worktreePath: string | null,+ runs: ReadonlyArray<Pick<OrchestrationV2Run, "status" | "workspacePreparation">>,+): boolean {+ return (+ worktreePath === null &&+ runs.some(+ (run) =>+ (run.status === "preparing" || run.status === "failed" || run.status === "interrupted") &&+ run.workspacePreparation?.type === "worktree",+ )+ );+}+export const OrchestrationV2RunAttempt = Schema.Struct({id: RunAttemptId,// Provider-thread rows can be reused after recovery; retain the native input destination.@@ -2148,7 +2171,7 @@ export function isOlderSettledThreadShell(beforeMs: number,): boolean {return (- thread.lineage.relationshipToParent !== "subagent" &&+ isListedThreadLineage(thread.lineage) &&thread.settledOverride === "settled" &&thread.settledAt !== null &&DateTime.toEpochMillis(thread.settledAt) < beforeMs@@ -2915,6 +2938,8 @@ export const OrchestrationV2Command = Schema.Union([type: Schema.Literal("thread.delete"),commandId: CommandId,threadId: ThreadId,+ /** Delete only a thread with no runs and no messages; otherwise succeed without a change. */+ onlyIfUnused: Schema.optional(Schema.Boolean),}),Schema.Struct({type: Schema.Literal("thread.settle"),@@ -3254,6 +3279,7 @@ export const OrchestrationV2Command = Schema.Union([targetThreadId: ThreadId,sourcePoint: OrchestrationV2ThreadForkSourcePoint,title: Schema.optional(TrimmedNonEmptyString),+ sideChat: Schema.optional(Schema.Boolean),createdAt: Schema.optional(Schema.DateTimeUtc),}),Schema.Struct({diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.tsindex caf261bfbb1..3788b7a3e6b 100644--- a/packages/shared/src/agentAwareness.test.ts+++ b/packages/shared/src/agentAwareness.test.ts@@ -63,25 +63,29 @@ describe("projectThreadAwarenessV2", () => {).toBeNull();});- it.each(["running", "completed", "failed"] as const)(- "does not publish %s subagent activity",- (status) => {- expect(- projectThreadAwarenessV2({- environmentId: "env-1" as EnvironmentId,- project,- thread: v2Thread({- status,- lineage: {- rootThreadId: "parent" as ThreadId,- parentThreadId: "parent" as ThreadId,- relationshipToParent: "subagent",- },- }),+ it.each([+ ["running", "subagent"],+ ["completed", "subagent"],+ ["failed", "subagent"],+ ["running", "side chat"],+ ] as const)("does not publish %s %s activity", (status, kind) => {+ expect(+ projectThreadAwarenessV2({+ environmentId: "env-1" as EnvironmentId,+ project,+ thread: v2Thread({+ status,+ lineage: {+ rootThreadId: "parent" as ThreadId,+ parentThreadId: "parent" as ThreadId,+ ...(kind === "subagent"+ ? { relationshipToParent: "subagent" }+ : { relationshipToParent: "fork", sideChat: true }),+ },}),- ).toBeNull();- },- );+ }),+ ).toBeNull();+ });it("keeps an older activity run visible over a newer cancelled run", () => {expect(diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.tsindex df912b4bb0f..e36001ead3d 100644--- a/packages/shared/src/agentAwareness.ts+++ b/packages/shared/src/agentAwareness.ts@@ -1,8 +1,9 @@-import type {- EnvironmentId,- OrchestrationV2ThreadShell,- Project,- ThreadId,+import {+ isListedThreadLineage,+ type EnvironmentId,+ type OrchestrationV2ThreadShell,+ type Project,+ type ThreadId,} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";@@ -60,7 +61,7 @@ export function projectThreadAwarenessV2(input: ProjectThreadAwarenessV2Input,): AgentAwarenessState | null {const { environmentId, project, thread } = input;- if (thread.lineage.relationshipToParent === "subagent") return null;+ if (!isListedThreadLineage(thread.lineage)) return null;const phase = resolveThreadAwarenessPhaseV2(thread);if (phase === null) {return null;