feat(mobile): support orchestration V2 on Android #3870
ClosedPixPMusic(GitHub profile, opens in a new tab)wants to merge 99 commits into
android-dev-pr-3514 fromrefs/pull/3870/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
- @@ -0,0 +1,14 @@1+import type { RemoteClientConnectionState } from "../../lib/connection";2+3+export type ThreadComposerSendLabel = "Queue" | "Send" | "Steer";4+5+export function resolveThreadComposerSendLabel(input: {6+ readonly connectionState: RemoteClientConnectionState;7+ readonly activeThreadBusy: boolean;8+ readonly queueCount: number;9+}): ThreadComposerSendLabel {10+ if (input.connectionState !== "connected" || input.queueCount > 0) {11+ return "Queue";12+ }13+ return input.activeThreadBusy ? "Steer" : "Send";14+}@@ -0,0 +53,21 @@53+export function ThreadRelationshipsBanner(props: {54+ readonly environmentId: EnvironmentId;55+ readonly threadId: ThreadId;56+}) {57+ const scopedProjection = useThreadProjection(props);58+ const projection = scopedProjection?.projection ?? null;59+ const threadShells = useThreadShells();60+ const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);61+ const archived = useArchivedThreadSnapshots(environmentIds);62+ const archivedShells =63+ archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot64+ .threads ?? EMPTY_THREAD_SHELLS;65+ const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {66+ const environmentShells: OrchestrationV2ThreadShell[] = [];67+ for (const thread of threadShells) {68+ if (thread.environmentId === props.environmentId) {69+ environmentShells.push(thread.source);70+ }71+ }72+ environmentShells.push(...archivedShells);73+ return environmentShells;
- @@ -460,8 +461,4 @@460461 void navigation.navigate("Connections");461462 }, [navigation]);462463 const handleStopThread = useCallback(() => {463- if (464- !selectedThread ||465- (selectedThread.session?.status !== "running" &&466- selectedThread.session?.status !== "starting")467- ) {464+ const runtime = selectedThread?.runtime;@@ -440,3 +450,4 @@440450 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />441451 ) : null}442452453+ <ThreadQueueControl
- @@ -0,0 +155,21 @@155+ }),156+ );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") {@@ -0,0 +398,21 @@398+ readonly payload: SDKMessage;399+ };400+401+export type ClaudeAgentSdkProtocolLogger = (402+ event: ClaudeAgentSdkProtocolLogEvent,403+) => Effect.Effect<void>;404+405+export function loggedClaudeQueryOptions(406+ options: ClaudeAgentSdkQueryOptions,407+): ClaudeAgentSdkLoggedQueryOptions {408+ return {409+ model: options.model,410+ tools: options.tools,411+ permissionMode: options.permissionMode,412+ ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),413+ ...(options.resume === undefined ? {} : { resume: options.resume }),414+ ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),415+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),416+ ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),417+ ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),418+ ...(options.settings === undefined ? {} : { settings: options.settings }),@@ -0,0 +262,21 @@262+ supportsModelSwitchInSession: setup.models != null || hasModelConfig,263+ supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig,264+ },265+ threads: {266+ ...base.threads,267+ canReadThreadSnapshot: canLoad,268+ canForkThread: canFork,269+ canForkFromTurn: false,270+ },271+ tools: {272+ ...base.tools,273+ supportsMcpTools: supportsMcp,274+ },275+ checkpointing: {276+ ...base.checkpointing,277+ providerCanReadConversationSnapshot: canLoad,278+ },279+ };280+}281+282+function acpMcpServers(threadId: ThreadId): ReadonlyArray<EffectAcpSchema.McpServer> {@@ -0,0 +1118,21 @@1118+export interface ClaudeRuntimeQueryPolicy {1119+ readonly permissionMode: PermissionMode;1120+ readonly tools?: ClaudeAgentSdkQueryTools;1121+ readonly allowedTools?: ReadonlyArray<string>;1122+ readonly allowDangerouslySkipPermissions?: true;1123+ readonly installPermissionCallback: boolean;1124+}1125+1126+export function claudeRuntimeQueryPolicyForRuntimePolicy(1127+ runtimePolicy: ProviderAdapterV2RuntimePolicy,1128+): ClaudeRuntimeQueryPolicy {1129+ const permissionMode = permissionModeForClaudeRuntimePolicy(runtimePolicy);1130+ const readOnlyTools =1131+ permissionMode === "dontAsk" &&1132+ sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy) === "readOnly"1133+ ? CLAUDE_READ_ONLY_ALLOWED_TOOLS1134+ : undefined;1135+ const allowedTools =1136+ readOnlyTools !== undefined && readOnlyPolicyAllowsGlobalReads(runtimePolicy)1137+ ? readOnlyTools1138+ : undefined;@@ -0,0 +569,21 @@569+ },570+ ];571+ }),572+ );573+}574+575+function nestedToolCallFromEnvelope(576+ envelope: Record<string, unknown>,577+): { readonly callId: string; readonly toolCall: ToolCall } | undefined {578+ const callId = typeof envelope.toolCallId === "string" ? envelope.toolCallId : undefined;579+ const wrapperEntry = Object.entries(envelope).find(([key]) => key.endsWith("ToolCall"));580+ if (wrapperEntry === undefined) {581+ return undefined;582+ }583+ const [wrapperName, rawCall] = wrapperEntry;584+ const call = unknownRecord(rawCall);585+ if (call === undefined) {586+ return undefined;587+ }588+ const args = unknownRecord(call.args) ?? {};589+ const fallbackCallId = `nested-${wrapperName}`;@@ -0,0 +92,21 @@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) => {110+ setVisible(false);111+ void Haptics.selectionAsync();112+ if (archivedThread) {@@ -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) =>@@ -66,11 +65,13 @@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(71+ () =>72+ selectedThread === null73+ ? { approvals: [], userInputs: [] }74+ : derivePendingThreadRequests(selectedThread.projection),7575 [selectedThread],7676 );77+ const activePendingApprovals = pendingRequests.approvals;@@ -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:@@ -0,0 +1196,21 @@1196+const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record<1197+ string,1198+ {1199+ readonly itemType: ClaudeToolItemType;1200+ readonly requestKind: ProviderRequestKind;1201+ }1202+> = {1203+ agent: { itemType: "dynamic_tool", requestKind: "command" },1204+ bash: { itemType: "command_execution", requestKind: "command" },1205+ edit: { itemType: "file_change", requestKind: "file-change" },1206+ glob: { itemType: "dynamic_tool", requestKind: "file-read" },1207+ grep: { itemType: "dynamic_tool", requestKind: "file-read" },1208+ ls: { itemType: "dynamic_tool", requestKind: "file-read" },1209+ multiedit: { itemType: "file_change", requestKind: "file-change" },1210+ notebookedit: { itemType: "file_change", requestKind: "file-change" },1211+ read: { itemType: "dynamic_tool", requestKind: "file-read" },1212+ task: { itemType: "dynamic_tool", requestKind: "command" },1213+ todowrite: { itemType: "dynamic_tool", requestKind: "command" },1214+ toolsearch: { itemType: "dynamic_tool", requestKind: "command" },1215+ webfetch: { itemType: "web_search", requestKind: "command" },1216+ websearch: { itemType: "web_search", requestKind: "command" },@@ -0,0 +1067,21 @@1067+ type: Schema.Literal("fullAccess"),1068+ }),1069+});1070+1071+function sandboxPolicyKindForClaudeRuntimePolicy(1072+ runtimePolicy: ProviderAdapterV2RuntimePolicy,1073+): ClaudeRuntimeSandboxPolicyKindName | undefined {1074+ return runtimePolicy.sandboxPolicy !== undefined &&1075+ Schema.is(ClaudeRuntimeSandboxPolicyKind)(runtimePolicy.sandboxPolicy)1076+ ? runtimePolicy.sandboxPolicy.type1077+ : 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(@@ -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 +119,21 @@119+ canCreateEmptyThread: true,120+ canReadThreadSnapshot: true,121+ canRollbackThread: true,122+ canForkThread: true,123+ canForkFromTurn: true,124+ canForkFromSubagentThread: true,125+ exposesNativeThreadId: true,126+ },127+ turns: {128+ exposesNativeTurnId: true,129+ emitsTurnStarted: true,130+ emitsTurnCompleted: true,131+ supportsInterrupt: true,132+ supportsActiveSteering: true,133+ supportsSteeringByInterruptRestart: true,134+ supportsQueuedMessages: true,135+ terminalStatusQuality: "strong",136+ },137+ streaming: {138+ streamsAssistantText: true,139+ streamsReasoning: true,@@ -1043,13 +431,11 @@1043- const unsettledTurnId = deriveUnsettledTurnId(latestTurn);1044- const foldsByAnchorId = new Map<string, ThreadFeedTurnFold>();1045- for (const [turnId, group] of groupsByTurnId) {1046- const { entries } = group;1047- if (turnId === unsettledTurnId) {1048- continue;1049- }1050- if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) {431+ const activeRunId = unsettledRunId(latestRun);432+ const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();433+ for (const [runId, group] of groupsByRunId) {434+ if (435+ runId === activeRunId ||436+ group.entries.some((entry) => entry.type === "message" && entry.message.streaming)437+ ) {1051438 continue;1052439 }1053-1054- const terminalAssistantMessageId = terminalAssistantMessageIdByTurn.get(turnId);440+ const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);1055441 const hiddenEntryIds = new Set(@@ -1357,14 +559,7 @@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,565+ attachments: item.type === "user_message" ? item.attachments : [],
- @@ -0,0 +427,21 @@427+ normalized.includes("write") ||428+ normalized.includes("patch") ||429+ normalizedTool.includes("edit") ||430+ normalizedTool.includes("write") ||431+ normalizedTool.includes("patch")432+ ) {433+ return "file-change";434+ }435+ if (436+ normalized === "read" ||437+ normalized === "glob" ||438+ normalized === "grep" ||439+ normalized === "lsp" ||440+ normalized === "external_directory" ||441+ normalizedTool === "read" ||442+ normalizedTool.includes("glob") ||443+ normalizedTool.includes("grep") ||444+ normalizedTool.includes("search")445+ ) {446+ return "file-read";447+ }@@ -0,0 +2366,21 @@2366+ const providerThread = makeProviderThread({2367+ idAllocator,2368+ providerInstanceId: options.instanceId,2369+ providerSessionId: input.providerSessionId,2370+ appThreadId: threadInput.threadId,2371+ nativeSession,2372+ now: createdAt,2373+ });2374+ registerThread(nativeSession, providerThread, null);2375+ return providerThread;2376+ }).pipe(2377+ Effect.mapError(2378+ (cause) =>2379+ new ProviderAdapterEnsureThreadError({2380+ driver: OPENCODE_PROVIDER,2381+ threadId: threadInput.threadId,2382+ cause,2383+ }),2384+ ),2385+ ),2386+ resumeThread: (threadInput) =>@@ -0,0 +19,21 @@19+export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<OrchestrationEffectExecutionError>()(20+ "OrchestrationEffectExecutionError",21+ {22+ effectId: Schema.String,23+ effectType: Schema.String,24+ cause: Schema.optional(Schema.Defect()),25+ },26+) {}27+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<@@ -0,0 +2374,21 @@2374+ registerThread(nativeSession, providerThread, null);2375+ return providerThread;2376+ }).pipe(2377+ Effect.mapError(2378+ (cause) =>2379+ new ProviderAdapterEnsureThreadError({2380+ driver: OPENCODE_PROVIDER,2381+ threadId: threadInput.threadId,2382+ cause,2383+ }),2384+ ),2385+ ),2386+ resumeThread: (threadInput) =>2387+ Effect.gen(function* () {2388+ const sessionId = nativeThreadId(threadInput.providerThread);2389+ const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>2390+ client.session.get({ sessionID: sessionId }),2391+ );2392+ const nativeSession = unwrapData("session.get", response);2393+ const resumedAt = yield* DateTime.now;2394+ const providerThread = {@@ -0,0 +311,21 @@311+ open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {312+ const protocolLogger = makeCursorAgentSdkProtocolLogger({313+ nativeEventLogger,314+ threadId: input.threadId,315+ providerSessionId: input.providerSessionId,316+ });317+ const log = (event: CursorAgentSdkProtocolLogEvent) =>318+ protocolLogger === undefined ? Effect.void : protocolLogger(event);319+320+ yield* log({321+ direction: "outgoing",322+ stage: "decoded",323+ payload: {324+ type: "agent.open",325+ operation: input.operation,326+ ...(input.agentId === undefined ? {} : { agentId: input.agentId }),327+ options: loggedCursorAgentOptions(input.options),328+ },329+ });330+331+ const agent = yield* Effect.tryPromise({@@ -0,0 +47,21 @@47+ messageId: MessageId,48+ }),49+ Schema.Struct({50+ type: Schema.Literal("provider-turn.restart"),51+ providerSessionId: ProviderSessionId,52+ providerThreadId: ProviderThreadId,53+ providerTurnId: ProviderTurnId,54+ interruptedAttemptId: RunAttemptId,55+ runId: RunId,56+ sessionTransition: Schema.optional(57+ Schema.Union([58+ Schema.Struct({59+ type: Schema.Literal("replace"),60+ replacementProviderSessionId: ProviderSessionId,61+ }),62+ Schema.Struct({ type: Schema.Literal("detach") }),63+ ]),64+ ),65+ }),66+ Schema.Struct({67+ type: Schema.Literal("runtime-request.respond"),@@ -0,0 +532,21 @@532+ pattern: "*",533+ action: "deny" as const,534+ })),535+ ];536+537+ if (requiresApproval) {538+ rules.push({ permission: "*", pattern: "*", action: "ask" });539+ for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) {540+ rules.push({ permission, pattern: "*", action: "ask" });541+ }542+ }543+544+ rules.push(545+ ...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({546+ permission,547+ pattern: "*",548+ action: "allow" as const,549+ })),550+ );551+552+ if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") {@@ -0,0 +275,21 @@275+ randomId<ProviderSessionId, typeof input>({276+ kind: "provider_session",277+ prefix: "provider-session",278+ parts: ["provider-instance", input.providerInstanceId, "thread", input.threadId],279+ make: ProviderSessionId.make,280+ })(input),281+ runtimeRequest: (input) =>282+ randomId<RuntimeRequestId, typeof input>({283+ kind: "runtime_request",284+ prefix: "runtime-request",285+ parts: [286+ "provider",287+ input.driver,288+ ...(input.providerTurnId === undefined ? [] : ["provider-turn", input.providerTurnId]),289+ ...(input.nativeRequestId === undefined290+ ? []291+ : ["native-request", input.nativeRequestId]),292+ ],293+ make: RuntimeRequestId.make,294+ })(input),295+ checkpointScope: (input) =>@@ -0,0 +153,21 @@153+ >;154+ readonly getThreadEventSequence: (155+ threadId: ThreadId,156+ ) => Effect.Effect<number, OrchestratorV2Error>;157+ readonly streamStoredEvents: Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;158+ readonly streamStoredEventsFrom: (input?: {159+ readonly threadId?: ThreadId;160+ readonly afterSequence?: number;161+ }) => Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;162+ readonly streamDomainEvents: Stream.Stream<OrchestrationV2DomainEvent, OrchestratorV2Error>;163+}164+165+export class OrchestratorV2 extends Context.Service<OrchestratorV2, OrchestratorV2Shape>()(166+ "t3/orchestration-v2/Orchestrator/OrchestratorV2",167+) {}168+169+function nextRunOrdinal(projection: OrchestrationV2ThreadProjection): number {170+ return projection.runs.length + 1;171+}172+173+function commandThreadId(command: OrchestrationV2Command): ThreadId {@@ -0,0 +106,21 @@106+ readonly sourceThreadId: ThreadId;107+ readonly targetThreadId: ThreadId;108+ readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];109+ readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;110+}): string {111+ const itemLines = input.deltaItems.flatMap((item) => {112+ const line = summarizeDeltaItem(item);113+ return line === null ? [] : [line];114+ });115+ return [116+ "Merge-back context from forked conversation.",117+ `Source thread: ${input.sourceThreadId}`,118+ `Target thread: ${input.targetThreadId}`,119+ `Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,120+ "",121+ "Fork delta:",122+ ...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines),123+ ].join("\n");124+}125+126+function makeProviderHandoffSummary(input: {@@ -0,0 +626,21 @@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;638+ const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume639+ ? { resume: input.nativeThreadId }640+ : { sessionId: input.nativeThreadId };641+ const selectedTools = input.tools ?? CLAUDE_CODE_PRESET_TOOLS;642+ const selectionSettings =643+ Object.keys(compiledSelection.settings).length === 0644+ ? undefined645+ : (compiledSelection.settings as ClaudeSdkSettings);646+ const querySettings =@@ -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 +513,21 @@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(531+ input.modelSelection,532+ "reasoningEffort",533+ );@@ -0,0 +309,21 @@309+ input.capabilities.threads.canForkThread &&310+ (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&311+ input.capabilities.identity.nativeThreadIds === "strong";312+313+ if (canForkNatively) {314+ return Effect.succeed("native_fork");315+ }316+317+ return ensureContextHandoff({318+ commandId: input.commandId,319+ threadId: input.threadId,320+ providerInstanceId: input.providerInstanceId,321+ capabilities: input.capabilities,322+ strategy: "full_thread_summary",323+ }).pipe(Effect.as("portable_context"));324+};325+326+const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {327+ const activeRun = input.projection.runs.find(328+ (run) =>329+ run.status === "preparing" ||@@ -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 +330,21 @@330+ .pipe(Effect.as("cancelled" as const));331+ const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(332+ Effect.ensuring(outbox.clearCancellation(effect.id)),333+ );334+ if (Exit.isSuccess(exit) && exit.value === "cancelled") {335+ return true;336+ }337+ if (Exit.isSuccess(exit)) {338+ const completed = yield* outbox.succeed({ effectId: effect.id, workerId });339+ if (!completed) {340+ if (yield* wasCancelled(effect.id)) return true;341+ return yield* new OrchestrationEffectWorkerError({342+ operation: "complete",343+ effectId: effect.id,344+ cause: "The worker no longer owns the effect lease.",345+ });346+ }347+ return true;348+ }349+350+ const error = Cause.pretty(exit.cause);@@ -0,0 +2268,21 @@2268+ return withLocalVisibleTurnItems(projection);2269+ }2270+ const sourceProjection = readProjection(2271+ forkedFrom.threadId,2272+ new Set([...seenThreadIds, targetThreadId]),2273+ );2274+ return {2275+ ...projection,2276+ visibleTurnItems: buildVisibleTurnItems({2277+ projection,2278+ sourceProjection,2279+ }),2280+ };2281+ };2282+ const projection = readProjection(threadId, new Set());2283+ if (!projection) {2284+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });2285+ }2286+ return projection;2287+ }),2288+ getThreadSnapshot: (threadId) =>@@ -0,0 +258,21 @@258+ ...base,259+ plans: upsertById(base.plans, event.payload),260+ };261+ case "checkpoint-scope.created":262+ return {263+ ...base,264+ checkpointScopes: upsertById(base.checkpointScopes, event.payload),265+ };266+ case "checkpoint.captured":267+ return {268+ ...base,269+ checkpoints: upsertById(base.checkpoints, event.payload),270+ };271+ case "checkpoint.rollback-requested":272+ return base;273+ case "context-handoff.updated":274+ return {275+ ...base,276+ contextHandoffs: upsertById(base.contextHandoffs, event.payload),277+ };278+ case "context-transfer.created":@@ -0,0 +109,21 @@109+ readonly type: OrchestrationV2DomainEvent["type"];110+ readonly payload: OrchestrationV2DomainEvent["payload"];111+ readonly threadId?: ThreadId;112+ readonly runId?: RunId | null;113+ readonly nodeId?: NodeId | null;114+ },115+ ) =>116+ Effect.gen(function* () {117+ const threadId = payloadInput.threadId ?? input.threadId;118+ const eventId = yield* idAllocator.allocate.event({119+ threadId,120+ providerSessionId: input.providerSessionId,121+ });122+ const occurredAt = yield* DateTime.now;123+ return yield* decodeDomainEvent(124+ compactUndefined({125+ id: eventId,126+ type: payloadInput.type,127+ threadId,128+ runId: payloadInput.runId ?? input.runId,129+ nodeId: payloadInput.nodeId ?? input.nodeId,@@ -0,0 +119,21 @@119+ lease_owner TEXT,120+ lease_expires_at TEXT,121+ created_at TEXT NOT NULL,122+ updated_at TEXT NOT NULL,123+ completed_at TEXT,124+ last_error TEXT125+ )126+ `;127+ yield* sql`CREATE INDEX orchestration_v2_effect_outbox_claim_idx ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at)`;128+ yield* sql`CREATE INDEX orchestration_v2_effect_outbox_command_idx ON orchestration_v2_effect_outbox(command_id, effect_id)`;129+130+ yield* sql`131+ CREATE TABLE orchestration_v2_turn_item_positions (132+ thread_id TEXT NOT NULL,133+ turn_item_id TEXT NOT NULL,134+ ordinal INTEGER NOT NULL,135+ PRIMARY KEY (thread_id, turn_item_id),136+ UNIQUE (thread_id, ordinal)137+ )138+ `;139+ yield* sql`@@ -0,0 +439,21 @@439+ const { nativeEventLogger } = input;440+ if (nativeEventLogger === undefined) {441+ return undefined;442+ }443+444+ return (event) =>445+ nativeEventLogger446+ .write(447+ {448+ provider: CLAUDE_PROVIDER,449+ protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,450+ kind: "protocol",451+ providerSessionId: input.providerSessionId,452+ event,453+ },454+ input.threadId,455+ )456+ .pipe(Effect.ignore);457+}458+459+export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<@@ -0,0 +63,21 @@63+ const instanceChanged = current.instanceId !== targetModelSelection.instanceId;64+ const modelChanged = current.model !== targetModelSelection.model;65+ const getMetadata = (instanceId: typeof current.instanceId) =>66+ adapters.getMetadata !== undefined67+ ? adapters.getMetadata(instanceId)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.providerSessions@@ -0,0 +288,21 @@288+ .write(289+ {290+ provider: CURSOR_PROVIDER,291+ protocol: CURSOR_AGENT_SDK_PROTOCOL,292+ kind: "protocol",293+ providerSessionId: input.providerSessionId,294+ event,295+ },296+ input.threadId,297+ )298+ .pipe(Effect.ignore);299+}300+301+export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<CursorAgentSdkRunner, never, ServerConfig> =302+ Layer.effect(303+ CursorAgentSdkRunner,304+ Effect.gen(function* () {305+ const { providerEventLogPath } = yield* ServerConfig;306+ const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {307+ stream: "native",308+ });@@ -0,0 +165,21 @@165+ const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);166+ if (!belongs || event.node.providerThreadId === null) {167+ return [belongs, state];168+ }169+ return [true, addProviderThread(event.node.providerThreadId)];170+ }171+ case "subagent.updated":172+ return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];173+ case "message.updated":174+ return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];175+ case "turn_item.updated":176+ return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state];177+ case "plan.updated":178+ return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];179+ case "runtime_request.updated":180+ return [181+ (event.threadId !== undefined && ownsChildThread(event.threadId)) ||182+ (event.runtimeRequest.providerTurnId !== null &&183+ state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),184+ state,185+ ];@@ -0,0 +661,21 @@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+ }678+ const ordinal = runOrdinalById.get(item.runId);679+ return ordinal !== undefined && ordinal <= sourceRun.ordinal;680+ }),681+ );@@ -0,0 +110,21 @@110+ operation: input.operation,111+ providerTurnId: input.providerTurnId,112+ cause: "The recorded provider execution target is no longer valid.",113+ });114+ }115+ // A restart-session command commits the replacement binding before its116+ // process-bound effect runs. The old live runtime must still receive117+ // the interrupt, but only when the projection matches the exact118+ // replacement captured by that same durable effect.119+ const interruptProviderThread = targetsRecordedSession120+ ? providerThread121+ : { ...providerThread, providerSessionId: input.providerSessionId };122+ if (providerTurn.status !== "running") {123+ return {124+ projection,125+ providerThread: interruptProviderThread,126+ providerTurn,127+ session: Option.none(),128+ };129+ }130+ const session = yield* sessions.get(input.providerSessionId);@@ -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 +308,21 @@308+ onSome: (effect) => effect.status === "cancelled",309+ }),310+ ),311+ );312+313+ const runOnce = Effect.gen(function* () {314+ const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs });315+ if (Option.isNone(claimed)) {316+ return false;317+ }318+ const effect = claimed.value;319+ // Cancellation can commit after the durable claim but before the320+ // process-local Deferred is registered. Re-read the authoritative row321+ // once before starting external work; later cancellations use the322+ // Deferred raced below.323+ if (yield* wasCancelled(effect.id)) {324+ yield* outbox.clearCancellation(effect.id);325+ return true;326+ }327+ const execution = executor.execute(effect).pipe(Effect.as("executed" as const));328+ const cancellation = outbox@@ -0,0 +39,21 @@39+40+ const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({41+ threadId,42+ turnItemId,43+ runId,44+ runOrdinal: suppliedRunOrdinal,45+ }) =>46+ Effect.gen(function* () {47+ const runRows =48+ runId === null49+ ? []50+ : yield* sql<{ readonly ordinal: number }>`51+ SELECT ordinal52+ FROM orchestration_v2_projection_runs53+ WHERE thread_id = ${threadId} AND run_id = ${runId}54+ LIMIT 155+ `;56+ const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;57+ const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;58+ const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;59+ yield* sql`@@ -0,0 +208,21 @@208+ ...base,209+ subagents: upsertById(base.subagents, event.payload),210+ };211+ case "provider-session.attached":212+ case "provider-session.updated":213+ return {214+ ...base,215+ providerSessions: upsertById(base.providerSessions, event.payload),216+ };217+ case "provider-session.detached":218+ return {219+ ...base,220+ providerSessions: base.providerSessions.filter(221+ (session) => session.id !== event.payload.providerSessionId,222+ ),223+ };224+ case "provider-thread.updated":225+ return {226+ ...base,227+ thread:228+ event.payload.appThreadId === base.thread.id
- @@ -52,14 +46,14 @@46+ }>,5247 ): ContextWindowSnapshot | null {53- for (let index = activities.length - 1; index >= 0; index -= 1) {54- const activity = activities[index];55- if (!activity || activity.kind !== "context-window.updated") {48+ for (let index = entries.length - 1; index >= 0; index -= 1) {49+ const entry = entries[index];50+ if (!entry || entry.item.type !== "compaction") {5651 continue;5752 }58-59- const payload = asRecord(activity.payload);60- const usedTokens = asFiniteNumber(payload?.usedTokens);53+ const payload = entry.item;54+ const usedTokens = asFiniteNumber(payload.afterTokenCount);6155 if (usedTokens === null || usedTokens < 0) {6256 continue;6357 }645865- const maxTokens = asFiniteNumber(payload?.maxTokens);59+ const maxTokens = null;@@ -907,3 +960,4 @@907960 markdownCwd={ctx.markdownCwd}908961 />909962 </div>963+ {(row.message.inputIntent && row.message.inputIntent !== "turn_start") ||@@ -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 +40,21 @@40+ Dialog,41+ DialogClose,42+ DialogDescription,43+ DialogFooter,44+ DialogHeader,45+ DialogPanel,46+ DialogPopup,47+ DialogTitle,48+} from "../ui/dialog";49+import { Input } from "../ui/input";50+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";51+import { Switch } from "../ui/switch";52+import { Textarea } from "../ui/textarea";53+import { stackedThreadToast, toastManager } from "../ui/toast";54+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";55+import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";56+57+type ScheduleMode = "fixed" | "interval";58+type WorkspaceMode = "root" | "worktree" | "existing_worktree";59+60+interface DraftState {@@ -0,0 +172,21 @@172+ causation_event_id,173+ correlation_id,174+ actor_kind,175+ payload_json,176+ metadata_json,177+ application_event_version178+ )179+ VALUES (180+ ${createdEventId},181+ 'project',182+ ${project.project_id},183+ COALESCE(184+ (185+ SELECT MAX(stream_version) + 1186+ FROM orchestration_events187+ WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id}188+ ),189+ 0190+ ),191+ 'project.created',192+ ${project.updated_at},@@ -131,6 +133,15 @@131- typeof cause.message === "string"132- ) {133- return cause.message;134- }135- return String(cause);136-}133+const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {134+ readonly threadId: ThreadId;135+ readonly messageId: MessageId;136+ readonly attachments: ReadonlyArray<{137+ readonly type: "image";138+ readonly name: string;139+ readonly mimeType: string;140+ readonly sizeBytes: number;141+ readonly dataUrl: string;142+ }>;143+}) {144+ const config = yield* ServerConfig.ServerConfig;145+ const fileSystem = yield* FileSystem.FileSystem;146+ const path = yield* Path.Path;147+ return yield* Effect.forEach(@@ -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 +324,21 @@324+ projectId: input.projectId,325+ ...(input.title === undefined ? {} : { title: input.title }),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 };@@ -0,0 +1,4 @@1+import * as Effect from "effect/Effect";2+import * as SqlClient from "effect/unstable/sql/SqlClient";3+4+export default Effect.gen(function* () {@@ -157,4 +166,4 @@157166 availableEditors,158167 openInCwd,159168 compact = false,160- enableShortcut = true,169+ displayMode = "toolbar",@@ -0,0 +95,21 @@95+ EffectAcpErrors.AcpError,96+ Scope.Scope97+ >;98+ readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;99+}100+101+export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({102+ runtime,103+ requestUserInput,104+}) =>105+ Effect.forEach(106+ ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,107+ (method) =>108+ runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => {109+ const identity = extractXAiAskUserQuestionIdentity(params);110+ const questions = extractXAiAskUserQuestions(params).map((question) => ({111+ id: question.id,112+ header: question.header,113+ question: question.question,114+ options: [...question.options],115+ }));@@ -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@@ -0,0 +158,21 @@158+ function* (workspaceRoot: string) {159+ const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);160+ yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);161+ const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);162+ yield* PubSub.publish(changes, {163+ workspaceRoot,164+ repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),165+ enrichment: {166+ repositoryIdentity: availableValue(Option.some(repositoryIdentity)),167+ faviconPath: availableValue(faviconPath),168+ },169+ });170+ },171+ );172+173+ const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (174+ workspaceRoot: string,175+ ) {176+ const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);177+ yield* logFailure(workspaceRoot, "faviconPath", faviconPath);178+ });@@ -0,0 +138,21 @@138+ `;139+ yield* sql`140+ INSERT OR IGNORE INTO orchestration_v2_turn_item_positions (141+ thread_id,142+ turn_item_id,143+ ordinal144+ )145+ SELECT thread_id, turn_item_id, ordinal146+ FROM orchestration_v2_projection_turn_items147+ ORDER BY thread_id, ordinal, turn_item_id148+ `;149+150+ yield* sql`151+ CREATE TABLE orchestration_v2_projection_metadata (152+ projection_name TEXT PRIMARY KEY,153+ schema_version INTEGER NOT NULL,154+ last_sequence INTEGER NOT NULL,155+ updated_at TEXT NOT NULL156+ )157+ `;158+ yield* sql`@@ -0,0 +140,21 @@140+ {item.output !== undefined ? <StructuredValue value={item.output} /> : null}141+ {item.exitCode !== undefined ? (142+ <p className={item.exitCode === 0 ? "text-emerald-600" : "text-destructive"}>143+ Process exited with code {item.exitCode}144+ </p>145+ ) : null}146+ </div>147+ ) : null}148+149+ {item.type === "file_change" ? (150+ <div className="flex flex-wrap items-center gap-2">151+ <span className="font-mono text-muted-foreground">152+ {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)}153+ </span>154+ {item.additions !== undefined || item.deletions !== undefined ? (155+ <span>156+ <span className="text-emerald-600">+{item.additions ?? 0}</span>{" "}157+ <span className="text-destructive">-{item.deletions ?? 0}</span>158+ </span>159+ ) : null}160+ {item.runId !== null ? (
- @@ -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) {@@ -29,8 +132,18 @@29132 return { ...project, environmentId };30133 }3113432-export function scopeThreadShell(135+export function presentThreadShell(33136 environmentId: EnvironmentId,34- thread: OrchestrationThreadShell,137+ thread: OrchestrationV2ThreadShell,35138 ): EnvironmentThreadShell {36- return { ...thread, environmentId };139+ const updatedAt = iso(thread.updatedAt);140+ const latestRun =141+ thread.latestRunId === null142+ ? null143+ : ({144+ runId: thread.latestRunId,145+ status: thread.status === "idle" ? "completed" : thread.status,146+ requestedAt: null,147+ startedAt: null,148+ completedAt:149+ thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,@@ -0,0 +15,21 @@15+ readonly checkpointTurnCount: number;16+ readonly checkpointRef: CheckpointRef;17+ readonly status: "ready" | "missing" | "error" | "stale";18+ readonly files: ReadonlyArray<{19+ readonly path: string;20+ readonly kind: string;21+ readonly additions: number;22+ readonly deletions: number;23+ }>;24+ readonly assistantMessageId: MessageId | null;25+ readonly completedAt: string;26+}27+28+/** Derives the checkpoint/diff rows needed by review UIs from native V2 entities. */29+export function deriveThreadCheckpointSummaries(30+ projection: OrchestrationV2ThreadProjection,31+): ReadonlyArray<ThreadCheckpointSummary> {32+ return projection.checkpoints.flatMap((checkpoint) => {33+ if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return [];34+ const assistantMessageId =35+ projection.messages.findLast(@@ -187,0 +428,21 @@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+ },448+ });@@ -136,3 +149,11 @@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+ },@@ -0,0 +23,21 @@23+ readonly nodes: ReadonlyMap<ThreadId, ThreadRelationshipNode>;24+ readonly edges: ReadonlyArray<ThreadRelationshipEdge>;25+}26+27+export interface ThreadRelationshipWalkRow {28+ readonly threadId: ThreadId;29+ readonly fromThreadId: ThreadId;30+ readonly depth: number;31+ readonly edge: ThreadRelationshipEdge;32+}33+34+export function resolveMergeBackTargetThreadId(35+ projection: Pick<OrchestrationV2ThreadProjection, "thread"> | null,36+): ThreadId | null {37+ if (projection?.thread.lineage.relationshipToParent !== "fork") return null;38+ return projection.thread.forkedFrom?.type === "run"39+ ? projection.thread.forkedFrom.threadId40+ : projection.thread.lineage.parentThreadId;41+}42+43+function edgeKey(edge: ThreadRelationshipEdge): string {
- @@ -0,0 +114,21 @@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+ }128+129+ const openThread = (threadId: ThreadId) => {130+ void navigate({131+ to: "/$environmentId/$threadId",132+ params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),133+ });134+ };@@ -1098,17 +328,7 @@1098- } else if (Option.isNone(discoveryExit.value)) {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: {@@ -0,0 +21,21 @@21+ readonly canReorder: boolean;22+ readonly canPromoteToSteer: boolean;23+}24+25+export function resolveActiveThreadRun(projection: Projection): Run | null {26+ return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;27+}28+29+export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {30+ const activeRun = resolveActiveThreadRun(projection);31+ const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;32+ const activeProviderThread =33+ providerThreadId === null34+ ? null35+ : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);36+ const attachedProviderThread =37+ activeProviderThread ??38+ projection.providerThreads.find(39+ (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,40+ ) ??41+ null;
- @@ -0,0 +99,21 @@99+ status: transfer.status,100+ });101+ }102+ }103+104+ return { nodes, edges: [...edgesByKey.values()] };105+}106+107+export function relatedThreadIds(108+ graph: ThreadRelationshipGraph,109+ threadId: ThreadId,110+): ReadonlyArray<ThreadId> {111+ const ids = new Set<ThreadId>();112+ for (const edge of graph.edges) {113+ if (edge.sourceThreadId === threadId) ids.add(edge.targetThreadId);114+ if (edge.targetThreadId === threadId) ids.add(edge.sourceThreadId);115+ }116+ return [...ids];117+}118+119+export function walkThreadRelationships(
- @@ -0,0 +2374,21 @@2374+ registerThread(nativeSession, providerThread, null);2375+ return providerThread;2376+ }).pipe(2377+ Effect.mapError(2378+ (cause) =>2379+ new ProviderAdapterEnsureThreadError({2380+ driver: OPENCODE_PROVIDER,2381+ threadId: threadInput.threadId,2382+ cause,2383+ }),2384+ ),2385+ ),2386+ resumeThread: (threadInput) =>2387+ Effect.gen(function* () {2388+ const sessionId = nativeThreadId(threadInput.providerThread);2389+ const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>2390+ client.session.get({ sessionID: sessionId }),2391+ );2392+ const nativeSession = unwrapData("session.get", response);2393+ const resumedAt = yield* DateTime.now;2394+ const providerThread = {@@ -0,0 +2366,21 @@2366+ const providerThread = makeProviderThread({2367+ idAllocator,2368+ providerInstanceId: options.instanceId,2369+ providerSessionId: input.providerSessionId,2370+ appThreadId: threadInput.threadId,2371+ nativeSession,2372+ now: createdAt,2373+ });2374+ registerThread(nativeSession, providerThread, null);2375+ return providerThread;2376+ }).pipe(2377+ Effect.mapError(2378+ (cause) =>2379+ new ProviderAdapterEnsureThreadError({2380+ driver: OPENCODE_PROVIDER,2381+ threadId: threadInput.threadId,2382+ cause,2383+ }),2384+ ),2385+ ),2386+ resumeThread: (threadInput) =>
- @@ -0,0 +44,21 @@44+ null;45+ if (item === null) return EMPTY_V2_ITEM_SUPPORT;46+47+ const run =48+ item.runId === null49+ ? null50+ : (projection.runs.find((candidate) => candidate.id === item.runId) ?? null);51+ const attempts =52+ item.runId === null53+ ? EMPTY_V2_ITEM_SUPPORT.attempts54+ : projection.attempts.filter((candidate) => candidate.runId === item.runId);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 =
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:
28a012fa-6522-46d9-8e3c-3d1f38bb31c5You 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