feat(mobile): nested subagent threads behind a toggle #3871
ClosedPixPMusic(GitHub profile, opens in a new tab)wants to merge 104 commits into
android-dev-pr-3514 fromrefs/pull/3871/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -163,4 +184,18 @@163184 : baselineCount,164185 totalCount,165186 );166- const visibleThreads = group.threads.slice(0, visibleCount);187+ const visibleRoots = roots.slice(0, visibleCount);188+ const visibleThreadRows: readonly SubagentThreadTreeRow<EnvironmentThreadShell>[] =189+ input.showSubagentThreads === true190+ ? flattenSubagentThreadTree({191+ threads: group.threads,192+ roots: visibleRoots,193+ expandedThreadKeys: input.expandedThreadKeys ?? new Set(),194+ threadSortOrder: input.threadSortOrder ?? "updated_at",195+ })196+ : visibleRoots.map((thread) => ({197+ thread,198+ depth: 0,199+ hasSubagentChildren: false,200+ isSubagentBranchExpanded: false,201+ }));@@ -163,4 +184,18 @@163184 : baselineCount,164185 totalCount,165186 );166- const visibleThreads = group.threads.slice(0, visibleCount);187+ const visibleRoots = roots.slice(0, visibleCount);188+ const visibleThreadRows: readonly SubagentThreadTreeRow<EnvironmentThreadShell>[] =189+ input.showSubagentThreads === true190+ ? flattenSubagentThreadTree({191+ threads: group.threads,192+ roots: visibleRoots,193+ expandedThreadKeys: input.expandedThreadKeys ?? new Set(),194+ threadSortOrder: input.threadSortOrder ?? "updated_at",195+ })196+ : visibleRoots.map((thread) => ({197+ thread,198+ depth: 0,199+ hasSubagentChildren: false,200+ isSubagentBranchExpanded: false,201+ }));
- @@ -0,0 +42,21 @@42+ return yield* service.listScheduledTasks(scope);43+ }),44+ update_scheduled_task: (input) =>45+ Effect.gen(function* () {46+ const scope = yield* McpInvocationContext;47+ const service = yield* OrchestratorMcpService;48+ return yield* service.updateScheduledTask(scope, input);49+ }),50+ delete_scheduled_task: (input) =>51+ Effect.gen(function* () {52+ const scope = yield* McpInvocationContext;53+ const service = yield* OrchestratorMcpService;54+ return yield* service.deleteScheduledTask(scope, input);55+ }),56+ create_threads: (input) =>57+ Effect.gen(function* () {58+ const scope = yield* McpInvocationContext;59+ const service = yield* OrchestratorMcpService;60+ return yield* service.createThreads(scope, input);61+ }),62+ t3_thread_start: (input) =>@@ -0,0 +242,21 @@242+ },243+} satisfies OrchestrationV2ProviderCapabilities;244+245+function negotiatedCapabilities(246+ base: OrchestrationV2ProviderCapabilities,247+ started: AcpSessionRuntimeStartResult,248+): OrchestrationV2ProviderCapabilities {249+ const agent = started.initializeResult.agentCapabilities ?? {};250+ const session = agent.sessionCapabilities;251+ const setup = started.sessionSetupResult;252+ const hasModelConfig =253+ setup.configOptions?.some((option) => option.category === "model") === true;254+ const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true;255+ const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true;256+ const canLoad = agent.loadSession === true;257+ const canFork = session?.fork != null;258+ return {259+ ...base,260+ sessions: {261+ ...base.sessions,262+ supportsModelSwitchInSession: setup.models != null || hasModelConfig,@@ -0,0 +444,21 @@444+ }445+ if (result.type === "count") {446+ return result.output.counts.map((entry) => ({447+ fileName: entry.file,448+ preview: `${entry.count} matches`,449+ }));450+ }451+ return result.output.matches.map((entry) => ({452+ fileName: entry.file,453+ ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }),454+ preview: entry.line,455+ }));456+ });457+ case "semSearch":458+ return [459+ {460+ fileName: "semantic-search",461+ preview: toolCall.result.value.results,462+ },463+ ];464+ default:@@ -159,9 +157,19 @@157+ return firstScope === undefined158+ ? undefined159+ : checkpointRefForScopeOrdinal({160+ scopeId: firstScope.id,161+ ordinalWithinScope: 0,162+ });163+ })()164+ : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)165+ ?.ref;166+ if (fromCheckpointRef === undefined) {159167 return yield* new CheckpointRefUnavailableError({160168 operation,161169 threadId: input.threadId,162- turnCount: input.toTurnCount,163- checkpoint: "to",170+ turnCount: input.fromTurnCount,171+ checkpoint: "from",164172 });165173 }166174167175 const diff = yield* checkpointStore@@ -0,0 +502,21 @@502+ direction: "outgoing",503+ stage: "decoded",504+ payload: {505+ type: "query.open",506+ options: loggedClaudeQueryOptions(input.options),507+ },508+ });509+510+ return {511+ messages: Stream.fromAsyncIterable(queryRuntime, (cause) =>512+ queryRunnerError(cause, "fromAsyncIterable"),513+ ).pipe(514+ Stream.tap((message) =>515+ logProtocolEvent({516+ direction: "incoming",517+ stage: "decoded",518+ payload: message,519+ }),520+ ),521+ ),522+ offer: (message) =>@@ -0,0 +1577,21 @@1577+}1578+1579+function claudeToolResultBlocksFromUserMessage(1580+ message: SDKMessage,1581+): ReadonlyArray<ClaudeToolResultContentBlock> {1582+ if (message.type !== "user" || typeof message.message.content === "string") {1583+ return [];1584+ }1585+ return message.message.content.filter(isClaudeUserToolResultContentBlock);1586+}1587+1588+function claudeToolResultEntriesFromMessage(message: SDKMessage): ReadonlyArray<{1589+ readonly toolResult: ClaudeToolResultContentBlock;1590+ readonly output: ClaudeNativeToolOutput;1591+}> {1592+ const assistantResults = claudeToolResultBlocksFromAssistantMessage(message).map(1593+ (toolResult) => ({ toolResult, output: claudeNativeToolOutputFromToolResult(toolResult) }),1594+ );1595+ const userResults = claudeToolResultBlocksFromUserMessage(message);1596+ const structuredOutput =1597+ message.type === "user" && userResults.length === 1 ? message.tool_use_result : undefined;@@ -1356,15 +559,6 @@1356- copyText: [summary, detail, fullDetail]1357- .filter((value, index, values): value is string => {1358- return Boolean(value) && values.indexOf(value) === index;1359- })1360- .join("\n"),1361- toolLike: workLogEntryIsToolLike(entry),1362- status: workEntryStatus(entry),1363- },1364- };1365- }),1366- ],1367- (s) => new Date(s.createdAt),1368- Order.Date,1369- );1370-559+ id: item.messageId,560+ createdAt,561+ message: {562+ id: item.messageId,563+ role: item.type === "user_message" ? "user" : "assistant",564+ text: item.text,@@ -0,0 +1077,21 @@1077+ : undefined;1078+}1079+1080+function readOnlyPolicyAllowsGlobalReads(runtimePolicy: ProviderAdapterV2RuntimePolicy): boolean {1081+ return (1082+ runtimePolicy.sandboxPolicy !== undefined &&1083+ Schema.is(ClaudeRuntimeReadOnlyFullAccessSandboxPolicy)(runtimePolicy.sandboxPolicy)1084+ );1085+}1086+1087+function permissionModeForClaudeRuntimePolicy(1088+ runtimePolicy: ProviderAdapterV2RuntimePolicy,1089+): PermissionMode {1090+ if (runtimePolicy.interactionMode === "plan") {1091+ return "plan";1092+ }1093+ if (runtimePolicy.approvalPolicy !== undefined && runtimePolicy.approvalPolicy !== "never") {1094+ return "default";1095+ }1096+1097+ switch (sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy)) {@@ -0,0 +673,21 @@673+ : {}),674+ ...(input.environment === undefined ? {} : { env: input.environment }),675+ ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),676+ ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),677+ };678+ return input.cwd === null ? options : { ...options, cwd: input.cwd };679+}680+681+export function claudeMcpQueryOverrides(input: {682+ readonly threadId: ThreadId;683+ readonly allowedTools?: ReadonlyArray<string>;684+}): {685+ readonly allowedTools?: ReadonlyArray<string>;686+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];687+} {688+ const session = McpProviderSession.readMcpProviderSession(input.threadId);689+ if (session === undefined) {690+ return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };691+ }692+ return {693+ allowedTools: Array.from(new Set([...(input.allowedTools ?? []), "mcp__t3-code__*"])),@@ -0,0 +510,21 @@510+ };511+ }512+}513+514+export function buildCodexTurnStartParams(input: {515+ readonly nativeThreadId: string;516+ readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;517+ readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;518+ readonly modelSelection: ModelSelection;519+}) {520+ return Effect.gen(function* () {521+ const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);522+ const approvalPolicy =523+ input.runtimePolicy.approvalPolicy === undefined524+ ? runtimeModeDefaults.approvalPolicy525+ : yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);526+ const sandboxPolicy =527+ input.runtimePolicy.sandboxPolicy === undefined528+ ? runtimeModeDefaults.sandboxPolicy529+ : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);530+ const selectedEffort = getModelSelectionStringOptionValue(@@ -63,12 +62,9 @@6362 "thread user input response",6463 );6564 const { selectedThread: selectedThreadShell } = useThreadSelection();66- const selectedThread = useSelectedThreadDetail();65+ const selectedThread = useSelectedThreadProjection();6766 const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);68- const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);69- const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(70- null,71- );72-73- const activePendingApprovals = useMemo(74- () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),67+ const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);68+ const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);69+70+ const pendingRequests = useMemo(@@ -0,0 +157,21 @@157+ }),158+ );159+}160+161+const scenario = (readArgValue("--scenario") ?? process.env.T3_CURSOR_REPLAY_SCENARIO) as162+ | RecordingName163+ | undefined;164+if (scenario === undefined || RECORDINGS[scenario] === undefined) {165+ throw new Error(`Pass --scenario with one of: ${Object.keys(RECORDINGS).join(", ")}`);166+}167+168+const apiKey = process.env.CURSOR_API_KEY?.trim();169+if (!apiKey) {170+ throw new Error("CURSOR_API_KEY is required to record Cursor SDK replay fixtures.");171+}172+173+const recording = RECORDINGS[scenario];174+const workspace = await prepareWorkspace(scenario);175+if (scenario === "subagent" || scenario === "tool_call_read_only" || scenario === "todo_list") {176+ await writeFixtureFiles(workspace.cwd);177+}@@ -0,0 +504,21 @@504+ | { readonly status: "success"; readonly value: Value }505+ | { readonly status: "error"; readonly error: unknown }506+ | undefined {507+ const result = unknownRecord(rawResult);508+ if (result === undefined) {509+ return undefined;510+ }511+ const success = unknownRecord(result.success);512+ if (success !== undefined) {513+ return {514+ status: "success",515+ value: mapSuccess(success),516+ };517+ }518+ return {519+ status: "error",520+ error: result.error ?? result.permissionDenied ?? result,521+ };522+}523+524+function nestedGrepWorkspaceResults(success: Record<string, unknown>): Record<string, unknown> {@@ -0,0 +617,21 @@617+618+export function makeClaudeQueryOptions(input: {619+ readonly modelSelection: ModelSelection;620+ readonly nativeThreadId: string;621+ readonly resume: boolean;622+ readonly resumeSessionAt?: string;623+ readonly cwd: string | null;624+ readonly settings?: ClaudeSettings;625+ readonly sdkSettings?: string | ClaudeSdkSettings;626+ readonly environment?: NodeJS.ProcessEnv;627+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];628+ readonly tools?: ClaudeAgentSdkQueryTools;629+ readonly allowedTools?: ReadonlyArray<string>;630+ readonly disallowedTools?: ReadonlyArray<string>;631+ readonly permissionMode?: PermissionMode;632+ readonly canUseTool?: CanUseTool;633+ readonly allowDangerouslySkipPermissions?: boolean;634+}): ClaudeAgentSdkQueryOptions {635+ const compiledSelection = compileClaudeModelSelection(input.modelSelection);636+ const extraArgs =637+ input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;
- @@ -0,0 +193,21 @@193+ identity: {194+ nativeThreadIds: "strong",195+ nativeTurnIds: "strong",196+ nativeItemIds: "strong",197+ nativeRequestIds: "strong",198+ },199+} satisfies OrchestrationV2ProviderCapabilities;200+201+function toProtocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError {202+ return new ProviderAdapterProtocolError({203+ driver: CODEX_PROVIDER,204+ detail,205+ ...(payload === undefined ? {} : { payload }),206+ });207+}208+209+function normalizeCodexCause(error: unknown): unknown {210+ return error;211+}212+213+function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {@@ -0,0 +628,21 @@628+ lastRunOrdinal: null,629+ handoffIds: [],630+ forkedFrom: input.forkedFrom ?? null,631+ createdAt: codexTimestamp(input.thread.createdAt),632+ updatedAt: codexTimestamp(input.thread.updatedAt),633+ };634+}635+636+const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>637+ turn.status === "completed" ||638+ turn.status === "interrupted" ||639+ turn.status === "failed" ||640+ turn.status === "cancelled";641+642+const providerTurnsForThread = (643+ providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,644+ providerThread: OrchestrationV2ProviderThread,645+): ReadonlyArray<OrchestrationV2ProviderTurn> =>646+ providerTurns.filter((turn) => turn.providerThreadId === providerThread.id);647+648+const countTerminalTurnsAfterBoundary = (@@ -0,0 +562,21 @@562+ if (!requiresApproval && sandboxType === "readOnly") {563+ const access = recordValue(sandboxPolicy, "access");564+ if (recordString(access, "type") === "fullAccess") {565+ rules.push({ permission: "external_directory", pattern: "*", action: "allow" });566+ }567+ }568+569+ if (!requiresApproval && sandboxType === "workspaceWrite") {570+ const writableRoots = recordValue(sandboxPolicy, "writableRoots");571+ if (Array.isArray(writableRoots)) {572+ for (const root of writableRoots) {573+ if (typeof root === "string" && root.trim().length > 0) {574+ rules.push({575+ permission: "external_directory",576+ pattern: `${root.replace(/\/$/, "")}/*`,577+ action: "allow",578+ });579+ }580+ }581+ }582+ }@@ -0,0 +81,21 @@81+ >82+ <Text83+ selectable84+ className="text-2xs leading-[17px] text-foreground-muted"85+ style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}86+ >87+ {block.value}88+ </Text>89+ </ScrollView>90+ </View>91+ ))}92+93+ {model.fileLinks.length > 0 ? (94+ <View className="gap-1">95+ <Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">96+ Files97+ </Text>98+ {model.fileLinks.map((link) => {99+ const relativePath =100+ resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??101+ (link.path.startsWith("/") ? null : link.path);@@ -0,0 +26,21 @@26+ providerThreadId: ProviderThreadId,27+ checkpointId: CheckpointId,28+ cause: Schema.optional(Schema.Defect()),29+ },30+) {}31+32+export interface CheckpointRollbackServiceV2Shape {33+ readonly execute: (input: {34+ readonly threadId: ThreadId;35+ readonly providerThreadId: ProviderThreadId;36+ readonly checkpointId: CheckpointId;37+ readonly scopeId: CheckpointScopeId;38+ }) => Effect.Effect<void, CheckpointRollbackExecutionError>;39+}40+41+export class CheckpointRollbackServiceV2 extends Context.Service<42+ CheckpointRollbackServiceV2,43+ CheckpointRollbackServiceV2Shape44+>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}45+46+export const layer: Layer.Layer<@@ -0,0 +148,21 @@148+ >149+ <SymbolView150+ name="arrow.up.right.square"151+ size={13}152+ tintColor={props.iconColor}153+ type="monochrome"154+ />155+ <Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">156+ {link.label}157+ </Text>158+ </Pressable>159+ ))}160+ </View>161+ ) : null}162+163+ {model.rollbackTarget ? (164+ <Pressable165+ accessibilityRole="button"166+ accessibilityLabel="Roll back to this checkpoint"167+ disabled={rollingBack}168+ onPress={() => {@@ -0,0 +102,21 @@102+103+ const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];104+ const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;105+ const summary = primaryParent106+ ? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`107+ : "Agent session connected";108+109+ const openThread = (threadId: ThreadId, archivedThread: boolean) => {110+ setVisible(false);111+ void Haptics.selectionAsync();112+ if (archivedThread) {113+ navigation.navigate("SettingsSheet", { screen: "SettingsArchive" });114+ return;115+ }116+ navigation.navigate("Thread", {117+ environmentId: props.environmentId,118+ threadId,119+ });120+ };121+122+ const merge = async () => {@@ -0,0 +2192,21 @@2192+ (cause) =>2193+ new ProjectionStoreReadError({2194+ threadId: ThreadId.make("thread:shell"),2195+ cause,2196+ }),2197+ ),2198+ );2199+2200+ return {2201+ apply,2202+ getShellSnapshot,2203+ getThreadProjection,2204+ getThreadSnapshot,2205+ } satisfies ProjectionStoreV2Shape;2206+ }),2207+);2208+2209+export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(2210+ ProjectionStoreV2,2211+ Effect.gen(function* () {2212+ const replayState = yield* Ref.make(makeProjectionReplayState());@@ -0,0 +1088,21 @@1088+function isSensitiveCodexProtocolKey(key: string): boolean {1089+ const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase();1090+ return (1091+ normalized.endsWith("authorization") ||1092+ normalized.endsWith("apikey") ||1093+ normalized.endsWith("token") ||1094+ normalized.endsWith("password") ||1095+ normalized.endsWith("secret")1096+ );1097+}1098+1099+export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer<1100+ CodexAppServerClientFactory,1101+ never,1102+ ChildProcessSpawner.ChildProcessSpawner | ServerConfig1103+> = Layer.effect(1104+ CodexAppServerClientFactory,1105+ Effect.gen(function* () {1106+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1107+ const { providerEventLogPath } = yield* ServerConfig;1108+ const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {@@ -0,0 +94,21 @@94+ ? Sources95+ : never96+ : never;97+ readonly sandboxEnabled?: boolean;98+ readonly enableAgentRetries?: boolean;99+ readonly hasCustomTools?: boolean;100+ };101+ readonly agents?: ReadonlyArray<string>;102+}103+104+export interface CursorAgentSdkLoggedSendOptions {105+ readonly model?: SendOptions["model"];106+ readonly mode?: SendOptions["mode"];107+ readonly local?: {108+ readonly force?: boolean;109+ readonly hasCustomTools?: boolean;110+ };111+ readonly idempotencyKey?: string;112+}113+114+export type CursorAgentSdkProtocolLogEvent =@@ -0,0 +119,21 @@119+ `;120+ const expectedSequence = yield* eventStore.latestSequence();121+ const schemaVersion = metadata[0]?.schema_version ?? 0;122+ const projectionSequence = metadata[0]?.last_sequence ?? 0;123+ return {124+ valid:125+ schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&126+ projectionSequence === expectedSequence &&127+ missingThreadIds.length === 0 &&128+ unexpectedThreadIds.length === 0 &&129+ unreadableThreadIds.length === 0,130+ schemaVersion,131+ expectedSequence,132+ projectionSequence,133+ unreadableThreadIds,134+ missingThreadIds,135+ unexpectedThreadIds,136+ } satisfies ProjectionVerificationV2;137+ });138+139+ const rebuild = Effect.gen(function* () {@@ -0,0 +747,21 @@747+ (left, right) =>748+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),749+ )[0] ?? null;750+ return {751+ createdBy: projection.thread.createdBy,752+ creationSource: projection.thread.creationSource,753+ id: projection.thread.id,754+ projectId: projection.thread.projectId,755+ title: projection.thread.title,756+ providerInstanceId: projection.thread.providerInstanceId,757+ modelSelection: projection.thread.modelSelection,758+ runtimeMode: projection.thread.runtimeMode,759+ interactionMode: projection.thread.interactionMode,760+ branch: projection.thread.branch,761+ worktreePath: projection.thread.worktreePath,762+ lineage: projection.thread.lineage,763+ forkedFrom: projection.thread.forkedFrom,764+ activeProviderThreadId: projection.thread.activeProviderThreadId,765+ latestRunId: latestRun?.id ?? null,766+ activeRunId: activeRun?.id ?? null,767+ status: latestRun?.status ?? "idle",@@ -0,0 +1852,21 @@1852+ startedAt,1853+ completedAt: null,1854+ };1855+ const turn: ActiveOpenCodeTurn = {1856+ isRoot: false,1857+ threadId: state.appThread.id,1858+ runId: null,1859+ rootNodeId,1860+ appThread: state.appThread,1861+ modelSelection: state.appThread.modelSelection,1862+ runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy,1863+ providerTurnId,1864+ providerTurnOrdinal: providerTurn.ordinal,1865+ runOrdinal: state.parentSubagent.parentTurn.runOrdinal,1866+ runAttemptId: null,1867+ startedAt,1868+ itemOrdinals: new Map(),1869+ parts: new Map(),1870+ partIdsByMessage: new Map(),1871+ providerTurn,1872+ nextItemOrdinal: 1,apps/server/src/orchestration-v2/ProjectionStore.ts line 1985OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1965,21 @@1965+ Schema.is(ProjectionStoreThreadNotFoundError)(cause)1966+ ? cause1967+ : new ProjectionStoreReadError({1968+ threadId,1969+ cause,1970+ }),1971+ ),1972+ );1973+1974+ const readProjection = (1975+ threadId: ThreadId,1976+ seenThreadIds: ReadonlySet<ThreadId>,1977+ ): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>1978+ Effect.gen(function* () {1979+ const projection = yield* readCanonicalProjection(threadId);1980+ const forkedFrom = projection.thread.forkedFrom;1981+ if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {1982+ return withLocalVisibleTurnItems(projection);1983+ }1984+1985+ const sourceProjection = yield* readProjection(@@ -801,0 +269,21 @@269+ case "compaction":270+ case "handoff":271+ return item.summary ?? null;272+ case "fork":273+ case "thread_created":274+ return item.targetThreadId;275+ case "subagent":276+ return item.result ?? item.progress ?? item.prompt;277+ case "dynamic_tool":278+ return null;279+ case "proposed_plan":280+ return item.markdown || null;281+ case "todo_list":282+ return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;283+ case "user_message":284+ case "assistant_message":285+ return item.text || null;286+ }287+}288+289+function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
- @@ -0,0 +239,21 @@239+240+function handleMessage(message: JsonRpcMessage): void {241+ if (stopped) return;242+ const actual = logicalIncoming(message);243+ if (actual === undefined) {244+ stopWithFailure("Could not identify outbound ACP frame", message);245+ return;246+ }247+ const entry = transcript.entries[cursor];248+ if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {249+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {250+ send({251+ jsonrpc: "2.0",252+ id: message.id,253+ error: { code: -32603, message: "ACP replay frame mismatch" },254+ });255+ }256+ stopWithFailure("Unexpected outbound ACP frame", actual);257+ return;258+ }259+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {@@ -0,0 +326,21 @@326+ ...(workspaceRoot === existing.value.workspaceRoot ? {} : { workspaceRoot }),327+ ...(input.defaultModelSelection === undefined328+ ? {}329+ : { defaultModelSelection: input.defaultModelSelection }),330+ ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }),331+ },332+ (workspaceRoot === existing.value.workspaceRoot333+ ? Effect.void334+ : invalidateEnrichment(existing.value.workspaceRoot, workspaceRoot)335+ ).pipe(Effect.andThen(readCommitted(input.projectId))),336+ );337+ },338+ );339+340+ const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(341+ function* (input) {342+ const existing = yield* getByWorkspaceRoot(input.workspaceRoot);343+ if (Option.isSome(existing)) return { project: existing.value, created: false };344+ return { project: yield* create(input), created: true };345+ },346+ );@@ -106,15 +99,4 @@10699 return emptyDiff;107100 }108101109- const threadContext = yield* projectionSnapshotQuery110- .getThreadCheckpointContext(input.threadId)111- .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));112- if (Option.isNone(threadContext)) {113- return yield* new CheckpointThreadNotFoundError({114- operation,115- threadId: input.threadId,116- });117- }118-119- const maxTurnCount = threadContext.value.checkpoints.reduce(120- (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),102+ const projection = yield* threads.getThreadProjection(input.threadId).pipe(@@ -0,0 +15,21 @@15+) {}16+17+export interface TurnItemPositionStoreV2Shape {18+ readonly allocate: (input: {19+ readonly threadId: ThreadId;20+ readonly turnItemId: TurnItemId;21+ readonly runId: RunId | null;22+ readonly runOrdinal?: number;23+ }) => Effect.Effect<number, TurnItemPositionStoreError>;24+ readonly normalize: (25+ item: OrchestrationV2TurnItem,26+ runOrdinal?: number,27+ ) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;28+}29+30+export class TurnItemPositionStoreV2 extends Context.Service<31+ TurnItemPositionStoreV2,32+ TurnItemPositionStoreV2Shape33+>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}34+35+export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(@@ -0,0 +6,21 @@6+ *7+ * The original V2 schema used a single `provider` column for both configured8+ * instance routing and driver identity. Keep those columns in place for9+ * migration compatibility. They remain write-through shadows where the old10+ * schema declared them NOT NULL; all V2 reads and indexes use the explicit11+ * columns added here.12+ */13+export default Effect.gen(function* () {14+ const sql = yield* SqlClient.SqlClient;15+16+ yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN driver TEXT`;17+ yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN provider_instance_id TEXT`;18+ yield* sql`19+ UPDATE orchestration_v2_events20+ SET21+ driver = provider,22+ provider_instance_id = COALESCE(23+ json_extract(payload_json, '$.providerInstanceId'),24+ provider25+ )26+ `;@@ -0,0 +409,21 @@409+ Effect.gen(function* () {410+ const target = yield* getProjectThread(input);411+ const explicitRun =412+ input.runId === undefined413+ ? undefined414+ : target.runs.find((candidate) => candidate.id === input.runId);415+ if (input.runId !== undefined && explicitRun === undefined) {416+ return yield* managementError(417+ "run_not_found",418+ `Run ${input.runId} does not belong to thread ${input.threadId}.`,419+ );420+ }421+ if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {422+ return {423+ type: "already_terminal",424+ run: explicitRun as OrchestrationV2Run & {425+ readonly status: ThreadManagementTerminalRunStatus;426+ },427+ } as const;428+ }429+ const interruptibleRun = latestActiveRun(target);@@ -0,0 +68,21 @@68+ : adapters.get(instanceId).pipe(69+ Effect.flatMap((adapter) =>70+ adapter.getCapabilities().pipe(71+ Effect.map((capabilities) => ({72+ driver: adapter.driver,73+ continuationKey: `${adapter.driver}:instance:${instanceId}`,74+ enabled: true,75+ capabilities,76+ })),77+ ),78+ ),79+ );80+ const currentInstance = yield* Effect.option(getMetadata(current.instanceId));81+ const targetInstance = yield* Effect.option(getMetadata(targetModelSelection.instanceId));82+ const targetAdapter = yield* Effect.option(adapters.get(targetModelSelection.instanceId));83+ const currentSession = projection.providerSessions84+ .filter((session) => session.providerInstanceId === current.instanceId)85+ .toSorted(86+ (left, right) =>87+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),88+ )[0];@@ -0,0 +145,21 @@145+ type: "thread.created",146+ threadId: input.event.appThread.id,147+ payload: input.event.appThread,148+ }),149+ ];150+ case "provider_session.updated":151+ return [152+ yield* makeDomainEvent(input, {153+ type: "provider-session.updated",154+ payload: input.event.providerSession,155+ }),156+ ];157+ case "provider_thread.updated":158+ return [159+ yield* makeDomainEvent(input, {160+ type: "provider-thread.updated",161+ threadId: input.event.providerThread.appThreadId ?? input.threadId,162+ payload: input.event.providerThread,163+ }),164+ ];165+ case "provider_turn.updated":@@ -0,0 +657,21 @@657+ (row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",658+ )659+ .map((row) => ({660+ visibility: "inherited" as const,661+ sourceThreadId: row.sourceThreadId,662+ sourceItemId: row.sourceItemId,663+ item: row.item,664+ }));665+ const localPrefix = inheritedVisibleTurnItemsFromLocalItems(666+ input.sourceProjection.turnItems.filter((item) => {667+ if (668+ isOrchestrationV2SupersededInterrupt({669+ item,670+ attempts: input.sourceProjection.attempts,671+ })672+ ) {673+ return false;674+ }675+ if (item.runId === null) {676+ return false;677+ }@@ -0,0 +50,21 @@50+ : { defaultModelSelection: mutation.defaultModelSelection }),51+ ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),52+ })53+ : mutation.type === "project.update"54+ ? projects.update({55+ commandId: mutation.commandId,56+ projectId: mutation.projectId,57+ ...(mutation.title === undefined ? {} : { title: mutation.title }),58+ ...(mutation.workspaceRoot === undefined59+ ? {}60+ : { workspaceRoot: mutation.workspaceRoot }),61+ ...(mutation.defaultModelSelection === undefined62+ ? {}63+ : { defaultModelSelection: mutation.defaultModelSelection }),64+ ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),65+ })66+ : projects.delete({67+ commandId: mutation.commandId,68+ projectId: mutation.projectId,69+ });70+ return yield* startup@@ -0,0 +28,21 @@28+export interface OrchestrationEffectExecutorV2Shape {29+ readonly execute: (30+ effect: OrchestrationEffectV2,31+ ) => Effect.Effect<void, OrchestrationEffectExecutionError>;32+}33+34+export class OrchestrationEffectExecutorV2 extends Context.Service<35+ OrchestrationEffectExecutorV2,36+ OrchestrationEffectExecutorV2Shape37+>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}38+39+export const executorLayer: Layer.Layer<40+ OrchestrationEffectExecutorV2,41+ never,42+ | ProviderSessionManagerV243+ | RunFinalizationService44+ | CheckpointRollbackServiceV245+ | ProviderTurnControlServiceV246+ | ProviderTurnStartServiceV247+ | RuntimeRequestServiceV248+> = Layer.effect(@@ -0,0 +442,21 @@442+ text: step.text,443+ ...(step.attachments === undefined ? {} : { attachments: step.attachments }),444+ }),445+ shouldRunInBackground ? { await: false, key } : undefined,446+ );447+ if (shouldRunInBackground) {448+ activeRunDispatchKeys.add(key);449+ } else if (450+ !(451+ nextStep !== undefined &&452+ (nextStep.type === "steer" || nextStep.type === "restart") &&453+ nextStep.targetRunIndex === messageIndex454+ )455+ ) {456+ steps.push({ type: "await_thread_idle", threadId: ids.threadId });457+ }458+ }459+ break;460+ case "queue_message":461+ messageIndex += 1;462+ pushDispatch(@@ -0,0 +153,21 @@153+ isProviderTurnControlError(cause)154+ ? cause155+ : new ProviderTurnControlError({156+ threadId: input.threadId,157+ operation: "interrupt",158+ providerTurnId: input.providerTurnId,159+ cause,160+ }),161+ ),162+ ),163+ interruptAndAwaitTerminal: (input) =>164+ Effect.gen(function* () {165+ const loaded = yield* load({ ...input, operation: "restart" });166+ if (Option.isSome(loaded.session)) {167+ yield* loaded.session.value.interruptTurn({168+ providerThread: loaded.providerThread,169+ providerTurnId: loaded.providerTurn.id,170+ });171+ }172+173+ for (let remaining = 1_000; remaining > 0; remaining -= 1) {@@ -0,0 +38,21 @@38+ RuntimeRequestServiceV2Shape39+>()("t3/orchestration-v2/RuntimeRequestService/RuntimeRequestServiceV2") {}40+41+export const layer: Layer.Layer<42+ RuntimeRequestServiceV2,43+ never,44+ ProjectionStoreV2 | ProviderSessionManagerV245+> = Layer.effect(46+ RuntimeRequestServiceV2,47+ Effect.gen(function* () {48+ const projections = yield* ProjectionStoreV2;49+ const sessions = yield* ProviderSessionManagerV2;50+51+ return RuntimeRequestServiceV2.of({52+ respond: (input) =>53+ Effect.gen(function* () {54+ const projection = yield* projections.getThreadProjection(input.threadId);55+ const request = projection.runtimeRequests.find(56+ (candidate) => candidate.id === input.requestId,57+ );58+ if (request === undefined) {@@ -0,0 +168,21 @@168+ if (Option.isNone(row) || (row.value.deletedAt !== null && !options?.includeDeleted)) {169+ return Option.none();170+ }171+ return Option.some(yield* hydrateAvailable(row.value));172+ },173+ );174+175+ const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(176+ "ProjectService.getByWorkspaceRoot",177+ )(function* (workspaceRoot, options) {178+ const normalized = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(179+ Effect.mapError(180+ (cause) =>181+ new ProjectOperationError({182+ operation: "normalize-workspace",183+ workspaceRoot,184+ cause,185+ }),186+ ),187+ );188+ const row = (yield* readRows()).find(
- @@ -1099,16 +328,8 @@1099- discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;1100- } else if (discoveryExit.value.value.length === 0) {1101- discoveryWarning = "Cursor ACP model discovery returned no built-in models.";1102- } else {1103- discoveredModels = discoveryExit.value;1104- }1105- }328+329+ const snapshot = catalogResult.success.value;330+ const discoveredModels = buildCursorDiscoveredModelsFromSdk(snapshot.models);1106331 return buildCursorProviderSnapshot({1107332 checkedAt,1108333 cursorSettings,1109- parsed,1110- discoveredModels: Option.getOrElse(1111- Option.filter(discoveredModels, (models) => models.length > 0),1112- () => [] as const,1113- ),1114- ...(discoveryWarning ? { discoveryWarning } : {}),334+ parsed: {335+ version: null,@@ -0,0 +93,21 @@93+ });94+ const checkedAt = DateTime.formatIso(yield* DateTime.now);95+ const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({96+ instanceId,97+ displayName,98+ accentColor,99+ environment,100+ enabled,101+ config,102+ }).pipe(103+ Effect.mapError(104+ (cause) =>105+ new ProviderDriverError({106+ driver: DRIVER_KIND,107+ instanceId,108+ detail: "Failed to build ACP Registry orchestration adapter.",109+ cause,110+ }),111+ ),112+ );113+ const currentSnapshot = () =>@@ -94,20 +90 @@94- if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {95- return "failed";96- }97- if (thread.session?.status === "starting") {98- return "starting";99- }100- if (thread.session?.status === "running" || thread.latestTurn?.state === "running") {101- return "running";102- }103- if (thread.latestTurn?.state === "completed") {104- return "completed";105- }106- // A turn that finished can still read as "interrupted" here: session107- // teardown settles still-running turns by session status, and that write108- // can race the turn.completed one. completedAt survives the race — a turn109- // that has a completion timestamp finished, whatever the state column says.110- // Without this, quick finish-then-teardown threads resolve to null111- // persistently and get tombstoned instead of published as completed.112- if (thread.latestTurn?.state === "interrupted" && thread.latestTurn.completedAt !== null) {113- return "completed";90+ if (thread.pendingRuntimeRequest !== null) {@@ -351,0 +418,21 @@418+ unexpectedThreadCount: verification.unexpectedThreadIds.length,419+ unreadableThreadCount: verification.unreadableThreadIds.length,420+ },421+ ),422+ ),423+ ),424+ ),425+ rebuild: runStartupPhase(426+ "orchestration-v2.projections.rebuild",427+ projectionMaintenance.rebuild,428+ ),429+ recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),430+ startEffectWorker: runStartupPhase(431+ "orchestration-v2.effect-worker.start",432+ Effect.gen(function* () {433+ const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);434+ yield* Ref.set(effectWorkerFiber, workerFiber);435+ yield* agentAwarenessRelay.start();436+ }),437+ ),438+ autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd@@ -187,0 +427,21 @@427+ type: "root" as const,428+ ...(bootstrap?.branch === null || bootstrap?.branch === undefined429+ ? {}430+ : { branch: bootstrap.branch }),431+ };432+ return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {433+ commandId,434+ creationSource: input.creationSource ?? "web",435+ threadId: input.threadId,436+ ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),437+ projectId: thread.projectId,438+ title: thread.title,439+ modelSelection: input.modelSelection ?? thread.modelSelection,440+ runtimeMode: input.runtimeMode,441+ interactionMode: input.interactionMode,442+ workspaceStrategy,443+ initialMessage: {444+ messageId: input.message.messageId,445+ text: input.message.text,446+ attachments,447+ },@@ -0,0 +1,17 @@1+import { errorTag } from "@t3tools/shared/observability";2+3+export function structuralProtocolMethod(value: string): string {4+ return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";5+}6+7+/**8+ * Retain only bounded structural metadata for native protocol diagnostics.9+ * Provider payload values may contain prompts, credentials, or arbitrarily10+ * large tool output and must never be copied into the observability stream.11+ */12+export function summarizeNativeProtocolPayload(13+ payload: unknown,14+): Readonly<Record<string, unknown>> {15+ if (payload === null) return { valueType: "null" };16+ if (typeof payload === "string") {17+ return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };@@ -136,3 +149,17 @@136149 scheduler,137150 concurrency,138151 }),152+ forkFromRun: createEnvironmentCommand(runtime, {153+ label: "environment-data:commands:thread:fork-from-run",154+ execute: (input: ForkThreadFromRunInput) => forkThreadFromRun(input),155+ scheduler,156+ concurrency: {157+ mode: "serial",158+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),159+ },160+ }),161+ mergeBack: createEnvironmentCommand(runtime, {162+ label: "environment-data:commands:thread:merge-back",163+ execute: (input: MergeThreadBackInput) => mergeThreadBack(input),164+ scheduler,165+ concurrency: {@@ -0,0 +209,21 @@209+function taskToDraft(task: ScheduledTask): DraftState {210+ const schedule = task.schedule;211+ const weekdays =212+ schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0213+ ? new Set(schedule.weekdays)214+ : new Set(ALL_WEEKDAYS);215+ return {216+ editingId: task.id,217+ title: task.title,218+ prompt: task.prompt,219+ enabled: task.enabled,220+ scheduleMode: schedule.type === "interval" ? "interval" : "fixed",221+ intervalMinutes:222+ schedule.type === "interval"223+ ? String(Math.max(1, Math.round(schedule.everyMs / 60_000)))224+ : "15",225+ timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",226+ weekdays,227+ projectId: task.projectId,228+ threadId: task.threadId ?? "",229+ workspaceMode: task.workspaceStrategy.type,@@ -304,5 +379,5 @@304379 }305380306381 const foldsByAnchorEntryId = new Map<string, TurnFold>();307- for (const [turnId, group] of groupsByTurnId) {308- if (turnId === input.unsettledTurnId) {382+ for (const [runId, group] of groupsByRunId) {383+ if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) {@@ -0,0 +107,21 @@107+ const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted(108+ (left, right) =>109+ relationshipSortKey({110+ edge: left.edge,111+ threadId: left.threadId,112+ currentThreadId: props.threadId,113+ mergeTargetThreadId,114+ }) -115+ relationshipSortKey({116+ edge: right.edge,117+ threadId: right.threadId,118+ currentThreadId: props.threadId,119+ mergeTargetThreadId,120+ }),121+ );122+ const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;123+ const canDetach = projection ? canDetachThreadProviderSession(projection) : false;124+125+ if (relationshipRows.length === 0) {126+ return null;127+ }@@ -32,4 +35,4 @@3235 draftThread: DraftThreadState,3336 fallbackModelSelection: ModelSelection,3437 ): Thread {35- return {38+ const timestamp = DateTime.makeUnsafe(draftThread.createdAt);@@ -0,0 +38,21 @@38+39+/** Joins pending request entities to the request items that carry display data. */40+export function derivePendingThreadRequests(41+ projection: OrchestrationV2ThreadProjection,42+): PendingThreadRequests {43+ const approvals: ThreadPendingApproval[] = [];44+ const userInputs: ThreadPendingUserInput[] = [];45+46+ for (const request of projection.runtimeRequests) {47+ if (request.status !== "pending") continue;48+ const responseCapability = request.responseCapability.type;49+ if (request.kind === "user_input") {50+ const item = projection.turnItems.findLast(51+ (candidate) =>52+ candidate.type === "user_input_request" && candidate.requestId === request.id,53+ );54+ if (item === undefined || item.type !== "user_input_request") continue;55+ userInputs.push({56+ requestId: request.id,57+ createdAt: DateTime.formatIso(request.createdAt),58+ questions: item.questions.map((question) => ({ ...question, multiSelect: false })),@@ -495,9 +225,13 @@225+ return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));226+}495227496- if (497- activity.kind === "provider.user-input.respond.failed" &&498- requestId &&499- isStalePendingRequestFailureDetail(detail)500- ) {501- openByRequestId.delete(requestId);502- }503- }228+export function deriveActivePlanState(229+ projection: OrchestrationV2ThreadProjection | null,230+ latestRunId: RunId | undefined,231+): ActivePlanState | null {232+ if (projection === null) return null;233+ const plans = projection.plans.filter((plan) => plan.kind === "todo_list");234+ const plan =235+ [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??236+ plans.at(-1) ??237+ null;@@ -0,0 +77,21 @@77+ if (78+ previous.visibility === next.visibility &&79+ previous.sourceThreadId === next.sourceThreadId &&80+ previous.sourceItemId === next.sourceItemId &&81+ previous.item === item82+ ) {83+ return rows;84+ }85+ const updated = [...rows];86+ updated[index] = next;87+ return updated;88+}89+90+/** Applies one committed event to a matching thread projection. */91+export function applyOrchestrationV2ProjectionEvent(92+ projection: OrchestrationV2ThreadProjection | null,93+ event: OrchestrationV2DomainEvent,94+): OrchestrationV2ThreadProjection | null {95+ if (projection === null || event.threadId !== projection.thread.id) return projection;96+97+ const base = { ...projection, updatedAt: event.occurredAt };
- @@ -0,0 +8,21 @@8+9+export function useOpenFavoriteEditorShortcut({10+ enabled,11+ environmentId,12+ keybindings,13+ availableEditors,14+ openInCwd,15+}: {16+ enabled: boolean;17+ environmentId: EnvironmentId;18+ keybindings: ResolvedKeybindingsConfig;19+ availableEditors: ReadonlyArray<EditorId>;20+ openInCwd: string | null;21+}) {22+ const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");23+ const [preferredEditor] = usePreferredEditor(availableEditors);24+25+ useEffect(() => {26+ if (!enabled) return;27+ const handler = (event: globalThis.KeyboardEvent) => {28+ if (!isOpenFavoriteEditorShortcut(event, keybindings)) return;apps/server/src/orchestration-v2/ProjectionStore.ts line 846OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +832,21 @@832+ case "preparing":833+ case "queued":834+ case "starting":835+ case "running":836+ case "waiting":837+ case "completed":838+ case "interrupted":839+ case "failed":840+ case "cancelled":841+ case "rolled_back":842+ return status;843+ default:844+ return "failed";845+ }846+}847+848+function itemCountThroughRun(input: {849+ readonly state: ShellThreadState;850+ readonly runId: RunId;851+}): number {852+ const runOrdinal = input.state.runOrdinalById.get(input.runId);@@ -0,0 +89,21 @@89+ const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;90+ const canDetach = projection ? canDetachThreadProviderSession(projection) : false;91+ const [visible, setVisible] = useState(false);92+ const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);93+ const navigation = useNavigation();94+ const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");95+ const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");96+ const insets = useSafeAreaInsets();97+ const backdropColor = useThemeColor("--color-backdrop");98+ const sheetColor = useThemeColor("--color-sheet");99+ const iconColor = useThemeColor("--color-icon-subtle");100+101+ if (rows.length === 0 && !canDetach) return null;102+103+ const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];104+ const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;105+ const summary = primaryParent106+ ? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`107+ : "Agent session connected";108+109+ const openThread = (threadId: ThreadId, archivedThread: boolean) => {@@ -0,0 +246,21 @@246+ childrenByParentKey.set(parentKey, sortThreads(children, input.threadSortOrder));247+ }248+249+ const rows: SubagentThreadTreeRow<Thread>[] = [];250+ const visited = new Set<string>();251+ const visit = (thread: Thread, depth: number) => {252+ const key = subagentThreadKey(thread);253+ if (visited.has(key)) return;254+ visited.add(key);255+ const children = (childrenByParentKey.get(key) ?? []).filter(256+ (child) => !visited.has(subagentThreadKey(child)),257+ );258+ const hasSubagentChildren = children.length > 0;259+ const isSubagentBranchExpanded = hasSubagentChildren && input.expandedThreadKeys.has(key);260+ rows.push({ thread, depth, hasSubagentChildren, isSubagentBranchExpanded });261+ if (!isSubagentBranchExpanded) return;262+ for (const child of children) visit(child, depth + 1);263+ };264+265+ for (const root of input.roots) visit(root, 0);266+ return rows;@@ -0,0 +55,21 @@55+ const node =56+ item.nodeId === null57+ ? null58+ : (projection.nodes.find((candidate) => candidate.id === item.nodeId) ?? null);59+ const providerThread =60+ item.providerThreadId === null || item.providerThreadId === undefined61+ ? null62+ : (projection.providerThreads.find((candidate) => candidate.id === item.providerThreadId) ??63+ null);64+ const providerSession =65+ providerThread?.providerSessionId == null66+ ? null67+ : (projection.providerSessions.find(68+ (candidate) => candidate.id === providerThread.providerSessionId,69+ ) ?? null);70+ const providerTurn =71+ item.providerTurnId === null72+ ? null73+ : (projection.providerTurns.find((candidate) => candidate.id === item.providerTurnId) ??74+ null);75+ const requestId =@@ -157,4 +166,4 @@157166 availableEditors,158167 openInCwd,159168 compact = false,160- enableShortcut = true,169+ displayMode = "toolbar",@@ -0,0 +239,21 @@239+ );240+ yield* Effect.all(241+ [242+ hasRepositoryIdentity243+ ? Effect.void244+ : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),245+ hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),246+ ],247+ { concurrency: "unbounded", discard: true },248+ );249+ });250+251+ const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn(252+ "ProjectEnrichmentService.getAvailable",253+ )(function* (workspaceRoot) {254+ const available = yield* peek(workspaceRoot);255+ yield* request(workspaceRoot);256+ return available;257+ });258+259+ const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(@@ -0,0 +258,21 @@258+ return withLocalVisibleTurnItems({259+ ...base,260+ turnItems: upsertById(base.turnItems, event.payload),261+ });262+ case "plan.updated":263+ return {264+ ...base,265+ plans: upsertById(base.plans, event.payload),266+ };267+ case "checkpoint-scope.created":268+ return {269+ ...base,270+ checkpointScopes: upsertById(base.checkpointScopes, event.payload),271+ };272+ case "checkpoint.captured":273+ return {274+ ...base,275+ checkpoints: upsertById(base.checkpoints, event.payload),276+ };277+ case "checkpoint.rollback-requested":278+ return base;
- @@ -0,0 +27,21 @@27+>()("t3/orchestration-v2/CheckpointCleanupService/CheckpointCleanupServiceV2") {}28+29+export const layer: Layer.Layer<30+ CheckpointCleanupServiceV2,31+ never,32+ CheckpointServiceV2 | ProjectionStoreV233+> = Layer.effect(34+ CheckpointCleanupServiceV2,35+ Effect.gen(function* () {36+ const checkpoints = yield* CheckpointServiceV2;37+ const projections = yield* ProjectionStoreV2;38+39+ const cleanup = Effect.fn("orchestrationV2.checkpointCleanup.cleanup")(function* (40+ threadId: ThreadId,41+ ) {42+ const projection = yield* projections.getThreadProjection(threadId);43+ const throughOrdinal = Math.max(44+ 0,45+ ...projection.runs.map((run) => run.ordinal),46+ ...projection.checkpoints.map((checkpoint) => checkpoint.ordinalWithinScope),47+ );@@ -243,10 +249,20 @@243249 props.projectSortOrder,244250 props.searchQuery,245251 props.selectedEnvironmentId,252+ props.showSubagentThreads,246253 props.threadSortOrder,247254 props.threads,248255 ],249256 );250257251258 const hasSearchQuery = props.searchQuery.trim().length > 0;259+ const toggleSubagentBranch = useCallback((thread: EnvironmentThreadShell) => {260+ const key = subagentThreadKey(thread);261+ setExpandedSubagentThreadKeys((previous) => {262+ const next = new Set(previous);263+ if (next.has(key)) next.delete(key);264+ else next.add(key);265+ return next;266+ });267+ }, []);252268 const listLayout = useMemo(@@ -0,0 +280,21 @@280+/**281+ * IMPLEMENTATIONS282+ */283+export const layer: Layer.Layer<284+ RunExecutionServiceV2,285+ never,286+ | CheckpointServiceV2287+ | EventSinkV2288+ | IdAllocatorV2289+ | ProviderEventIngestorV2290+ | ServerSettingsService291+> = Layer.effect(292+ RunExecutionServiceV2,293+ Effect.gen(function* () {294+ const checkpointService = yield* CheckpointServiceV2;295+ const eventSink = yield* EventSinkV2;296+ const idAllocator = yield* IdAllocatorV2;297+ const providerEventIngestor = yield* ProviderEventIngestorV2;298+ const serverSettings = yield* ServerSettingsService;299+300+ const writeFinalRunEvents = (input: {@@ -0,0 +129,21 @@129+ rootNode === undefined ||130+ attempt === undefined ||131+ providerThread === undefined ||132+ providerThread.providerSessionId === null ||133+ message === undefined ||134+ checkpointScope === undefined135+ ) {136+ return yield* new ProviderTurnStartError({137+ runId,138+ cause: `Run ${runId} is missing its execution projection state.`,139+ });140+ }141+ const providerSessionId = providerThread.providerSessionId;142+ type CurrentAttemptState = "current" | "run_stale" | "thread_inactive";143+ const getCurrentAttemptState = Effect.fn(144+ "orchestrationV2.providerTurnStart.getCurrentAttemptState",145+ )(146+ function* (147+ expectedStatus: OrchestrationV2Run["status"],148+ ): Effect.fn.Return<CurrentAttemptState, never> {149+ const currentOption = yield* Effect.option(@@ -31,3 +38,6 @@3138 return "Could not delete thread";3239 }334041+function readThreadSubtree(thread: EnvironmentThreadShell): readonly EnvironmentThreadShell[] {42+ const snapshot = appAtomRegistry.get(environmentSnapshotAtom(thread.environmentId));43+ if (snapshot === null) return [thread];@@ -0,0 +671,21 @@671+ yield* Ref.set(latestProviderThread, event.providerThread);672+ }673+ }674+ if (675+ event.type === "turn_item.updated" &&676+ event.turnItem.providerTurnId ===677+ (yield* Ref.get(eventRouting)).rootProviderTurnId678+ ) {679+ yield* Ref.update(latestTurnItemOrdinal, (current) =>680+ Math.max(current, event.turnItem.ordinal),681+ );682+ }683+ if (event.type === "turn.terminal") {684+ yield* Ref.set(terminalEvent, event);685+ yield* Ref.set(rootTerminalSeen, true);686+ yield* finalizeRootRun(event);687+ }688+ yield* trackChildLifecycle(event);689+ }),690+ ),691+ Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),@@ -123,6 +142,17 @@123142 * When searching, pagination is suspended so every match stays visible.124143 */125144 readonly showAllThreads?: boolean;145+ /** Enables nested, collapsible subagent rows. Disabled by default. */146+ readonly showSubagentThreads?: boolean;147+ readonly expandedThreadKeys?: ReadonlySet<string>;148+ /**149+ * Key of an explicitly selected thread that must stay reachable. In nested150+ * mode, when its branch root falls past the pagination cut, that root is151+ * appended so the selection never disappears from the list.152+ */153+ readonly pinnedThreadKey?: string | null;154+ readonly threadSortOrder?: SidebarThreadSortOrder;126155 }): HomeListLayout {127156 const items: HomeListItem[] = [];128157 const stickyHeaderIndices: number[] = [];158+ const allThreads = input.groups.flatMap((group) => group.threads);@@ -0,0 +322,21 @@322+ },323+ },324+ ],325+ });326+ return replacement;327+ });328+ if (!(yield* continueIfCurrent("starting"))) {329+ return;330+ }331+ const now = yield* DateTime.now;332+ const runningProviderThread: OrchestrationV2ProviderThread = {333+ ...loadedProviderThread,334+ id: providerThread.id,335+ driver: session.driver,336+ providerInstanceId: run.providerInstanceId,337+ providerSessionId,338+ appThreadId: projection.thread.id,339+ ownerNodeId: providerThread.ownerNodeId,340+ firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,341+ lastRunOrdinal: run.ordinal,342+ handoffIds: providerThread.handoffIds,
- @@ -0,0 +1283,21 @@1283+ firstStep.type === "fork" ||1284+ secondStep.type === "rollback" ||1285+ secondStep.type === "fork"1286+ ) {1287+ throw new Error("provider_thread_resume replay recording requires two turn steps.");1288+ }1289+1290+ const firstThread = yield* Effect.gen(function* () {1291+ const client = yield* initializeClient;1292+ const thread = yield* client.request("thread/start", {});1293+ yield* runTurnStep(client, thread.thread.id, firstStep);1294+ return thread;1295+ }).pipe(1296+ Effect.provide(1297+ makeCodexLayer({1298+ recorder,1299+ }),1300+ ),1301+ );1302+1303+ yield* recorder.writeRecord({@@ -0,0 +223,21 @@223+ cursor: this.cursor,224+ remaining: this.transcript.entries.length - this.cursor,225+ });226+ }227+ }228+229+ private advance(): void {230+ this.cursor += 1;231+ for (const waiter of this.waiters) waiter();232+ this.waiters.clear();233+ }234+235+ private fail(cause: unknown): void {236+ this.failure = cause;237+ for (const waiter of this.waiters) waiter();238+ this.waiters.clear();239+ }240+241+ private throwFailure(): void {242+ if (this.failure !== null) throw this.failure;243+ }@@ -0,0 +55,21 @@55+ const session = resolveThreadProviderSession(projection);56+ const capabilities = session?.capabilities.turns;57+ const queuedRuns = projection.runs58+ .filter((run) => run.status === "queued")59+ .sort(60+ (left, right) =>61+ (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||62+ left.ordinal - right.ordinal,63+ )64+ .map((run) => ({65+ run,66+ text:67+ projection.messages.find((message) => message.id === run.userMessageId)?.text ??68+ "Queued message",69+ }));70+71+ return {72+ activeRun,73+ queuedRuns,74+ canReorder: capabilities?.supportsQueuedMessages === true,75+ canPromoteToSteer:@@ -0,0 +1 @@1+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";@@ -0,0 +204,21 @@204+ ...base,205+ attempts: upsertById(base.attempts, event.payload),206+ });207+ case "node.updated":208+ return {209+ ...base,210+ nodes: upsertById(base.nodes, event.payload),211+ };212+ case "subagent.updated":213+ return {214+ ...base,215+ subagents: upsertById(base.subagents, event.payload),216+ };217+ case "provider-session.attached":218+ case "provider-session.updated":219+ return {220+ ...base,221+ providerSessions: upsertById(base.providerSessions, event.payload),222+ };223+ case "provider-session.detached":224+ return {@@ -520,17 +133,4 @@520- normalizeCursorConfigOptionToken(requestedContextWindow) ||521- normalizeCursorConfigOptionToken(option.name) ===522- normalizeCursorConfigOptionToken(requestedContextWindow),523- );524- if (value) {525- updates.push({ configId: contextOption.id, value });526- }527- }528-529- const fastOption = configOptions.find(530- (option) => option.category === "model_config" && isCursorFastConfigOption(option),531- );532- const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode");533- if (fastOption && typeof requestedFastMode === "boolean") {534- const value = findCursorBooleanConfigValue(fastOption, requestedFastMode);535- if (value !== undefined) {536- updates.push({ configId: fastOption.id, value });133+ const label = parameter.displayName?.trim() || toTitleCaseWords(id);134+ const defaultValue = cursorSdkDefaultParameterValue(model, nativeId);135+ const normalizedValues = new Set(values.map((entry) => entry.value.toLowerCase()));136+ if (values.length === 2 && normalizedValues.has("true") && normalizedValues.has("false")) {@@ -0,0 +219,21 @@219+ ),220+ )221+ .toSorted((left, right) => right.ordinal - left.ordinal)[0];222+}223+224+function errorMessage(error: unknown): string {225+ return error instanceof Error ? error.message : String(error);226+}227+228+function managementError(229+ code: ThreadManagementError["code"],230+ message: string,231+ cause?: unknown,232+): ThreadManagementError {233+ return new ThreadManagementError({ code, message, ...(cause === undefined ? {} : { cause }) });234+}235+236+const make = Effect.gen(function* () {237+ const orchestrator = yield* OrchestratorV2;238+239+ const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>@@ -0,0 +540,21 @@540+ pushDispatch(541+ dispatchMessageCommand({542+ commandId: yield* idAllocator.allocate.command({543+ fixtureName: input.scenario,544+ commandName: `steer-${messageIndex}`,545+ }),546+ ids,547+ modelSelection: input.modelSelection,548+ messageId: yield* idAllocator.allocate.message({549+ threadId: ids.threadId,550+ ordinal: messageIndex,551+ }),552+ text: step.text,553+ ...(step.attachments === undefined ? {} : { attachments: step.attachments }),554+ dispatchMode: {555+ type: "steer_active",556+ targetRunId: runIdFor(step.targetRunIndex),557+ },558+ }),559+ );560+ if (input.fixtureInput.steps[stepIndex + 1]?.type !== "approve_next_runtime_request") {@@ -0,0 +51,21 @@51+ return {52+ provider: transcript.provider,53+ protocol: transcript.protocol,54+ scenario: transcript.scenario,55+ };56+}57+58+function makeReplayServerConfig(59+ scenario: string,60+): Effect.Effect<61+ ServerConfig["Service"],62+ PlatformError.PlatformError,63+ FileSystem.FileSystem | Path.Path64+> {65+ return Effect.gen(function* () {66+ const fs = yield* FileSystem.FileSystem;67+ const path = yield* Path.Path;68+ const baseDir = yield* fs.makeTempDirectory({69+ prefix: `t3-orchestration-v2-codex-${scenario}-`,70+ });71+ const stateDir = path.join(baseDir, "userdata");@@ -0,0 +51,21 @@51+import { layer as turnItemPositionStoreLayer } from "../TurnItemPositionStore.ts";52+import { layer as runtimeRequestServiceLayer } from "../RuntimeRequestService.ts";53+import { layer as threadForkServiceLayer } from "../ThreadForkService.ts";54+import {55+ runOrchestratorV2Scenario,56+ type OrchestratorV2ScenarioStepError,57+ type OrchestratorV2Scenario,58+ type OrchestratorV2ScenarioResult,59+} from "./OrchestratorScenario.ts";60+61+export function makeReplayServerConfig(62+ scenario: string,63+): Effect.Effect<64+ ServerConfig["Service"],65+ PlatformError.PlatformError,66+ FileSystem.FileSystem | Path.Path67+> {68+ const safeScenario = scenario.replace(/[^a-z0-9_-]+/gi, "-");69+ return Effect.gen(function* () {70+ const fs = yield* FileSystem.FileSystem;71+ const path = yield* Path.Path;
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
b0553413-3f04-4533-a286-02b3899e17a1You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share