From b0a4eb1abb67c6e8dfc128840377a995b7d75571 Mon Sep 17 00:00:00 2001 From: Lance Wang Date: Wed, 7 Oct 2026 08:56:48 +0800 Subject: [PATCH 1/2] fix(dsh): retain and recover timed Ask User questions --- .changeset/recover-dsh-questions.md | 5 + packages/orbis-remote-dsh/README.md | 28 +- .../src/adapter/dsh-local-backend.test.ts | 335 +++++++++++++++++- .../src/adapter/dsh-local-backend.ts | 278 +++++---------- .../src/adapter/dsh-projection.ts | 4 + .../src/adapter/dsh-question-bridge.ts | 125 +++++++ .../src/adapter/dsh-question-projection.ts | 144 ++++++++ .../orbis-remote-dsh/src/adapter/dsh-types.ts | 23 ++ .../orbis-remote-dsh/src/adapter/index.ts | 1 + .../src/host/orbis-remote-dsh-host.test.ts | 100 ++++++ .../orbis-remote-dsh/src/plugin/dsh-plugin.ts | 11 +- .../src/testkit/native-projections.ts | 19 +- 12 files changed, 883 insertions(+), 190 deletions(-) create mode 100644 .changeset/recover-dsh-questions.md create mode 100644 packages/orbis-remote-dsh/src/adapter/dsh-question-bridge.ts create mode 100644 packages/orbis-remote-dsh/src/adapter/dsh-question-projection.ts diff --git a/.changeset/recover-dsh-questions.md b/.changeset/recover-dsh-questions.md new file mode 100644 index 0000000..25544f3 --- /dev/null +++ b/.changeset/recover-dsh-questions.md @@ -0,0 +1,5 @@ +--- +"@orbisapp/remote-dsh": patch +--- + +Keep phone-owned timed Ask User questions waiting through DSH's native wait claim, recover continued questions after reconnect or restart, and submit late answers through the native question service without duplicate replies. diff --git a/packages/orbis-remote-dsh/README.md b/packages/orbis-remote-dsh/README.md index 37369b2..7464a7f 100644 --- a/packages/orbis-remote-dsh/README.md +++ b/packages/orbis-remote-dsh/README.md @@ -202,10 +202,11 @@ Every candidate must complete the pinned host handshake before it can connect. DSH Web for mobile because `orbis.sessions.create` requires an opaque registered `workspaceRef`. -On open, Orbis renders its encrypted per-host cache first and makes exactly one -`once` snapshot/replay refresh. It retains `live` delivery only for the session -where this phone submitted an unfinished run; navigating to another session or -away from the chat removes only the UI observer, never cancels that DSH run. +On open, Orbis renders its encrypted per-host cache first and keeps a `live` +subscription while the chat is mounted, including desktop-started sessions. +A phone-submitted unfinished run also retains live delivery after navigating +away. Detaching the last subscriber releases remote interaction ownership; +it never cancels the DSH run. The present mobile configuration intentionally does not enable broad Android cleartext traffic. Therefore validate this plain-LAN `ws://` path on iOS; an @@ -267,6 +268,25 @@ Closing a mobile page or an encrypted socket only detaches the remote observer; it never cancels/disposes a DSH run. Only plugin/host shutdown closes the owned DSH controllers. +## Ask User questions + +The plugin claims new questions while their session has a live subscriber. +For DSH's opt-in timed questions, it attaches to the native wait so the +unattended deadline pauses while the phone owns the question. Detaching the +last subscriber releases that wait and delegates to the next native answerer. + +Timed questions that have already continued after a timeout or session repair +are recovered from DSH's durable `userQuestions` projection, including after +reconnect or plugin restart. Replies use the native question service and agent +inbox. A queued reply hides the question until admission; discarding the reply +makes it answerable again. Continued questions support answering or skipping; +DSH does not provide cancellation for them. + +A still-open question already held by the desktop cannot be transferred through +DSH's current API. Ordinary indefinite questions have no durable continued +state, so opening the phone later cannot recover them. This requires an upstream +shared ownership/answer contract. + ## Real DSH profile E2E (explicit opt-in) The package includes a repeatable LAN-only runner at diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.test.ts b/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.test.ts index af06a0e..3687ac0 100644 --- a/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.test.ts +++ b/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.test.ts @@ -1,3 +1,7 @@ +import { Context } from "@deepseek-ai/cordis"; +import type { Agent } from "@deepseek-ai/dsh-agent"; +import { ToolCallId } from "@deepseek-ai/dsh-llm"; +import { UserQuestionService } from "@deepseek-ai/dsh-user-questions"; import { agentDriverId, agentRunId, @@ -33,6 +37,7 @@ import { type DshPromptReferenceProvider, type DshSessionSubagentProvider, type DshUserMessage, + type DshUserQuestions, } from "./dsh-types"; const FIXED_TIME = agentTimestamp("2026-08-10T00:00:00.000Z"); @@ -143,6 +148,7 @@ class TestAgent implements DshAgent { steer(message: DshUserMessage): void { this.steers.push(message); + if (message.source?.kind === "user-question-reply") this.inbox.nextStep.push(message); } } @@ -196,9 +202,20 @@ class TestDsh { private interactionAvailable: boolean; private readonly materialized = new Set(); - constructor(readonly approvals = false) { + constructor( + readonly approvals = false, + userQuestions: DshUserQuestions = { + attachWait: () => { + throw new Error("Unexpected timed question"); + }, + answer: () => { + throw new Error("Unexpected continued question"); + }, + }, + ) { this.interactionAvailable = approvals; this.context = { + userQuestions, sessionController: { create: async (payload) => { this.sessionCreateCalls.push(payload); @@ -501,6 +518,14 @@ class TestDsh { ); } + receiveQuestion( + request: DshQuestionRequest, + next: () => Promise, + ): Promise { + if (this.questionListener === undefined) throw new Error("No DSH question listener"); + return this.questionListener(request, next); + } + setInteractionAvailable(available: boolean, sessionId?: string): void { if (sessionId !== undefined) { this.sessionAvailability.set(sessionId, available); @@ -2890,3 +2915,311 @@ describe("DSH local backend", () => { expect(changes).toEqual(["web-session"]); }); }); + +/** Real upstream wait/answer operations, with only the Agent and Session fixtures substituted. */ +async function nativeQuestionFixture(available = true, ptc = false) { + const ctx = new Context(); + let service: UserQuestionService; + const dsh = new TestDsh(true, { + attachWait: (agent, callId, signal) => + service.attachWait(agent as Agent, ToolCallId(callId), signal), + answer: (agent, callId, answer) => + service.answer(agent as Agent, ToolCallId(callId), { + answers: answer.answers.map((item) => ({ ...item, selected: [...item.selected] })), + }), + }); + ctx.provide("agents", { + get: (id: unknown) => dsh.context.agents.get(id), + roots: () => [...dsh.liveAgents.values()], + } as unknown as Context["agents"]); + ctx.provide("sessionProjections", { + register: () => {}, + stateOf: (session: DshSession) => ({ + questions: dsh.context.sessionProjections.snapshot(session).values.userQuestions, + }), + } as unknown as Context["sessionProjections"]); + service = new UserQuestionService(ctx); + ctx.on( + "user-questions/request", + async (request, next) => { + const answer = await dsh.receiveQuestion(request, next); + return { answers: answer.answers.map((item) => ({ ...item, selected: [...item.selected] })) }; + }, + { global: true, prepend: true }, + ); + dsh.setInteractionAvailable(available); + const backend = createBackend(dsh); + const record = await backend.createSession({ + driverId: agentDriverId("dsh"), + workspaceRef: "workspace-1", + }); + const runtime = await backend.connectRuntime(record.ref); + const events: AgentSessionEvent[] = []; + runtime.subscribe((event) => events.push(event)); + const agent = dsh.agent("created-session"); + const questions = [ + { id: "color", question: "Choose a color", options: [{ label: "Blue" }, { label: "Green" }] }, + ]; + const callId = ToolCallId("timed-color-call"); + dsh.emit( + "created-session", + event("request/header", 0, { + header: { + config: { model: "test-model", provider: "test-provider" }, + tools: [ + { + name: "ask_user_question", + parameters: { properties: { timeout: { type: "integer" } } }, + }, + ], + }, + }), + ); + if (!ptc) + dsh.emit( + "created-session", + event("tool/call", 1, { + name: "ask_user_question", + callId, + arguments: JSON.stringify({ questions }), + }), + ); + return { + agent, + backend, + callId, + ctx, + dsh, + events, + questions, + record, + runtime, + service, + continueQuestion: () => + dsh.emit( + "created-session", + event("tool/result", 2, { + message: { + role: "tool", + source: { kind: "tool", callId }, + toolCallId: callId, + content: [{ type: "text", text: JSON.stringify({ pending: true, callId }) }], + }, + }), + ), + close: async () => { + await backend.close(); + await ctx.fiber.dispose(); + }, + }; +} + +describe("native DSH timed questions", () => { + test("recovers a continued PTC sub-call using its native dispatch identity", async () => { + const f = await nativeQuestionFixture(false, true); + try { + f.dsh.emit( + "created-session", + event("tool/ptc-dispatch", 1, { + name: "ask_user_question", + subCallId: f.callId, + arguments: { questions: f.questions }, + content: [{ type: "text", text: JSON.stringify({ pending: true, callId: f.callId }) }], + }), + ); + const request = (await f.backend.readSession(f.record.ref)).pendingQuestions![0]!; + expect(pendingQuestions(f.events)).toEqual([request]); + expect( + await f.runtime.respondQuestion({ + requestId: request.requestId, + response: { + kind: "answered", + answers: [{ questionId: "color", customText: "Red", optionIds: [] }], + }, + }), + ).toEqual({ accepted: true }); + expect(JSON.parse((f.agent.steers[0]!.content![0] as { text: string }).text)).toMatchObject({ + callId: f.callId, + answers: [{ id: "color", custom: "Red", selected: [] }], + }); + } finally { + await f.close(); + } + }); + + test("keeps native reply admission exclusive and restores a discarded answer until durable settlement", async () => { + const f = await nativeQuestionFixture(false); + try { + await f.service.askTimed( + { agent: f.agent as unknown as Agent, questions: f.questions }, + f.callId, + 5, + ); + f.continueQuestion(); + const requestId = (await f.backend.readSession(f.record.ref)).pendingQuestions![0]!.requestId; + const response = { + requestId, + response: { + kind: "answered" as const, + answers: [{ questionId: "color", optionIds: ["dsh-option-0-0"] }], + }, + }; + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: true }); + const message = f.agent.inbox.nextStep.shift()!; + // Native claims remove the reply from the visible inbox before admission. + f.ctx.emit("agent/inbox/claimed", { + agent: f.agent as unknown as Agent, + message: message as Agent["inbox"]["nextStep"][number], + turn: 1, + }); + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: false }); + expect(f.agent.steers).toHaveLength(1); + f.ctx.emit("agent/inbox/discarded", { + agent: f.agent as unknown as Agent, + message: message as Agent["inbox"]["nextStep"][number], + }); + expect((await f.backend.readSession(f.record.ref)).pendingQuestions).toHaveLength(1); + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: true }); + const admitted = f.agent.inbox.nextStep.shift()!; + f.dsh.emit("created-session", event("user/message", 3, admitted)); + expect(pendingQuestions(f.events)).toEqual([]); + expect((await f.backend.readSession(f.record.ref)).pendingQuestions).toEqual([]); + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: false }); + await f.backend.close(); + const restarted = createBackend(f.dsh); + try { + expect((await restarted.readSession(f.record.ref)).pendingQuestions).toEqual([]); + } finally { + await restarted.close(); + } + } finally { + await f.close(); + } + }); + + test("holds a mobile question beyond the unattended deadline and releases the claim after answering", async () => { + const f = await nativeQuestionFixture(); + try { + let settled = false; + const ask = f.service + .askTimed({ agent: f.agent as unknown as Agent, questions: f.questions }, f.callId, 60) + .finally(() => { + settled = true; + }); + await waitFor(() => pendingQuestions(f.events).length === 1); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(settled).toBe(false); + const request = pendingQuestions(f.events)[0]!; + expect( + await f.runtime.respondQuestion({ + requestId: request.requestId, + response: { + kind: "answered", + answers: [{ questionId: "color", optionIds: ["dsh-option-0-0"] }], + }, + }), + ).toEqual({ accepted: true }); + expect(await ask).toEqual({ answers: [{ id: "color", selected: ["Blue"] }] }); + expect(pendingQuestions(f.events)).toEqual([]); + } finally { + await f.close(); + } + }); + + test("recovers a desktop timed question after timeout, then submits a native late reply once", async () => { + const f = await nativeQuestionFixture(false); + try { + expect( + await f.service.askTimed( + { agent: f.agent as unknown as Agent, questions: f.questions }, + f.callId, + 10, + ), + ).toEqual({ pending: true, callId: f.callId }); + f.continueQuestion(); + f.dsh.setInteractionAvailable(true); + const projection = await f.backend.readSession(f.record.ref); + expect(projection.pendingQuestions).toHaveLength(1); + const request = projection.pendingQuestions[0]!; + const response = { + requestId: request.requestId, + response: { + kind: "answered" as const, + answers: [{ questionId: "color", optionIds: ["dsh-option-0-1"] }], + }, + }; + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: true }); + expect(f.agent.steers).toHaveLength(1); + expect(f.agent.steers[0]?.source).toMatchObject({ + kind: "user-question-reply", + callId: f.callId, + }); + const text = (f.agent.steers[0]!.content![0] as { text: string }).text; + expect(JSON.parse(text)).toMatchObject({ answers: [{ id: "color", selected: ["Green"] }] }); + expect((await f.backend.readSession(f.record.ref)).pendingQuestions).toEqual([]); + expect(pendingQuestions(f.events)).toEqual([]); + expect(await f.runtime.respondQuestion(response)).toEqual({ accepted: false }); + } finally { + await f.close(); + } + }); + + test("releases the mobile wait on disconnect and restores the same request identity after timeout and backend recreation", async () => { + const f = await nativeQuestionFixture(); + try { + const ask = f.service.askTimed( + { agent: f.agent as unknown as Agent, questions: f.questions }, + f.callId, + 40, + ); + await waitFor(() => pendingQuestions(f.events).length === 1); + const requestId = pendingQuestions(f.events)[0]!.requestId; + f.dsh.setInteractionAvailable(false); + expect(await ask).toEqual({ pending: true, callId: f.callId }); + f.continueQuestion(); + await f.backend.close(); + const restarted = createBackend(f.dsh); + try { + // No controller exists yet: this exercises the native cold read cut. + const snapshot = await restarted.readSession(f.record.ref); + expect(snapshot.pendingQuestions?.[0]?.requestId).toBe(requestId); + f.dsh.setInteractionAvailable(true); + const runtime = await restarted.connectRuntime(f.record.ref); + expect( + await runtime.respondQuestion({ + requestId, + response: { + kind: "answered", + answers: [{ questionId: "color", optionIds: [] }], + }, + }), + ).toEqual({ accepted: true }); + expect(f.agent.steers).toHaveLength(1); + } finally { + await restarted.close(); + } + } finally { + await f.close(); + } + }); + + test("does not translate cancellation of a continued question into a skipped answer", async () => { + const f = await nativeQuestionFixture(false); + try { + await f.service.askTimed( + { agent: f.agent as unknown as Agent, questions: f.questions }, + f.callId, + 5, + ); + f.continueQuestion(); + const requestId = (await f.backend.readSession(f.record.ref)).pendingQuestions![0]!.requestId; + await expect( + f.runtime.respondQuestion({ requestId, response: { kind: "cancelled" } }), + ).rejects.toMatchObject({ code: "unsupported" }); + expect(f.agent.steers).toEqual([]); + expect((await f.backend.readSession(f.record.ref)).pendingQuestions).toHaveLength(1); + } finally { + await f.close(); + } + }); +}); diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.ts b/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.ts index 2b24115..96cd346 100644 --- a/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.ts +++ b/packages/orbis-remote-dsh/src/adapter/dsh-local-backend.ts @@ -12,8 +12,6 @@ import { isAgentBackendError, isSameAgentSessionRef, nextAgentDeliveryCursor, - validateAgentQuestionRequest, - validateAgentQuestionResponseForRequest, validateAgentSessionSubagentList, validateAgentPromptInput, validateAgentPromptReferenceCompletionInput, @@ -91,6 +89,13 @@ import { runStartForDshEvent, titleForDshEvent, } from "./dsh-projection"; +import { DshQuestionBridge } from "./dsh-question-bridge"; +import { + dshQuestionAnswer, + dshQuestionRequestId, + isDshQuestionCall, + projectDshContinuedQuestions, +} from "./dsh-question-projection"; import { lastDshSessionEvent } from "./dsh-types"; import type { DshAgent, @@ -237,181 +242,6 @@ class DshPermissionInteraction { } } -interface DshQuestionPending { - readonly optionLabels: ReadonlyMap; - readonly request: AgentQuestionRequest; - readonly resolve: (answer: DshQuestionAnswer) => void; - readonly reject: (reason: unknown) => void; - readonly next: () => Promise; - readonly removeAbort: () => void; -} - -/** Maps one DSH Ask User batch to the canonical, opaque-id question domain. */ -class DshQuestionBridge { - private readonly pending = new Map(); - - constructor( - private readonly nextRequestId: () => string, - private readonly onChanged: (pending: readonly AgentQuestionRequest[]) => void, - ) {} - - requested( - native: DshQuestionRequest, - next: () => Promise, - requestedAt: AgentTimestamp, - ): Promise { - const requestId = this.nextRequestId(); - const optionLabels = new Map(); - const questions = native.questions.map((raw, questionIndex) => { - if (typeof raw.id !== "string" || !raw.id.trim() || raw.id !== raw.id.trim()) { - throw new AgentBackendError("protocol", "DSH question id is invalid"); - } - if (typeof raw.question !== "string" || !raw.question.trim()) { - throw new AgentBackendError("protocol", "DSH question text is invalid"); - } - const nativeOptions = raw.options ?? []; - if (!Array.isArray(nativeOptions)) { - throw new AgentBackendError("protocol", "DSH question options are invalid"); - } - const labels = new Set(); - const options = nativeOptions.map((option, optionIndex) => { - if (typeof option.label !== "string" || !option.label.trim()) { - throw new AgentBackendError("protocol", "DSH question option is invalid"); - } - if (labels.has(option.label)) { - throw new AgentBackendError("protocol", "DSH question option labels must be unique"); - } - labels.add(option.label); - const optionId = `dsh-option-${questionIndex}-${optionIndex}`; - optionLabels.set(`${raw.id}\u0000${optionId}`, option.label); - return { - ...(option.description === undefined ? {} : { description: option.description }), - label: option.label, - optionId, - }; - }); - const intent = - raw.intent === undefined - ? undefined - : (() => { - if (raw.intent.kind !== "plan-review" || typeof raw.intent.approve !== "string") { - throw new AgentBackendError("protocol", "DSH question intent is invalid"); - } - const approveIndex = nativeOptions.findIndex( - (option) => option.label === raw.intent?.approve, - ); - if (approveIndex < 0) { - throw new AgentBackendError( - "protocol", - "DSH plan-review intent references an unknown option", - ); - } - return { - approveOptionId: `dsh-option-${questionIndex}-${approveIndex}`, - kind: "plan-review" as const, - }; - })(); - return { - ...(raw.detail === undefined ? {} : { detail: raw.detail }), - ...(raw.header === undefined ? {} : { header: raw.header }), - ...(intent === undefined ? {} : { intent }), - multiSelect: raw.multiSelect ?? false, - options, - question: raw.question, - questionId: raw.id, - }; - }); - const request = validateAgentQuestionRequest({ - questions, - requestedAt, - requestId, - }); - const result = new Promise((resolve, reject) => { - const abort = () => this.reject(requestId, questionError("ASK_ABORTED")); - native.signal?.addEventListener("abort", abort, { once: true }); - this.pending.set(requestId, { - next, - optionLabels, - reject, - removeAbort: () => native.signal?.removeEventListener("abort", abort), - request, - resolve, - }); - }); - this.publish(); - return result; - } - - async respond(input: AgentQuestionResponseInput): Promise { - const pending = this.pending.get(input.requestId); - if (pending === undefined) return { accepted: false }; - const validated = validateAgentQuestionResponseForRequest(input, pending.request); - if (validated.response.kind === "cancelled") { - this.reject(input.requestId, questionError("ASK_CANCELLED")); - return { accepted: true }; - } - const answers = validated.response.answers.map((answer) => ({ - ...(answer.customText === undefined ? {} : { custom: answer.customText }), - id: answer.questionId, - selected: answer.optionIds.map((optionId) => { - const label = pending.optionLabels.get(`${answer.questionId}\u0000${optionId}`); - if (label === undefined) { - throw new AgentBackendError("protocol", "DSH question option mapping is invalid"); - } - return label; - }), - })); - this.finish(input.requestId, { answers }); - return { accepted: true }; - } - - delegate(): void { - for (const requestId of [...this.pending.keys()]) this.delegateOne(requestId); - } - - snapshot(): readonly AgentQuestionRequest[] { - return [...this.pending.values()].map((item) => item.request); - } - - private publish(): void { - this.onChanged(this.snapshot()); - } - - private finish(requestId: string, answer: DshQuestionAnswer): void { - const pending = this.pending.get(requestId); - if (pending === undefined) return; - this.pending.delete(requestId); - pending.removeAbort(); - this.publish(); - pending.resolve(answer); - } - - private reject(requestId: string, reason: unknown): void { - const pending = this.pending.get(requestId); - if (pending === undefined) return; - this.pending.delete(requestId); - pending.removeAbort(); - this.publish(); - pending.reject(reason); - } - - private delegateOne(requestId: string): void { - const pending = this.pending.get(requestId); - if (pending === undefined) return; - this.pending.delete(requestId); - pending.removeAbort(); - this.publish(); - void pending.next().then(pending.resolve, pending.reject); - } -} - -function questionError(code: "ASK_ABORTED" | "ASK_CANCELLED"): Error & { readonly code: string } { - return Object.assign(new Error("The DSH user question was cancelled"), { - code, - name: "UserQuestionError", - }); -} - export interface DshLocalBackendOptions { /** Defaults to the local product backend: `local` / `This device`. */ readonly backend?: { @@ -468,6 +298,11 @@ export interface DshLocalCatalogChange { export type DshLocalCatalogListener = (change: DshLocalCatalogChange) => void; interface DshLocalControllerHost { + questionSnapshot(agent: DshAgent): readonly AgentQuestionRequest[]; + respondContinuedQuestion( + agent: DshAgent, + input: AgentQuestionResponseInput, + ): AgentQuestionResponseResult; readonly driverDescriptor: AgentDriverDescriptor; readonly attachments?: DshSessionAttachmentPort; @@ -1170,8 +1005,12 @@ export class DshLocalBackend implements AgentBackend, DshLocalControllerHost { } } const permissionOptions = this.permissionOptions(ref); + const agent = this.options.context.agents.get(this.options.toSessionId(ref.nativeSessionId)); return { ...decorated, + ...(agent === undefined || this.options.interactionAvailability === undefined + ? {} + : { pendingQuestions: this.questionSnapshot(agent) }), ...(permissionOptions === undefined ? {} : { configOptions: [permissionOptions] }), workspaceRef: await this.workspaceRefFor(ref), }; @@ -1380,6 +1219,57 @@ export class DshLocalBackend implements AgentBackend, DshLocalControllerHost { return dshProjectionState(this.options.context.sessionProjections.snapshot(session).values); } + questionSnapshot(agent: DshAgent): readonly AgentQuestionRequest[] { + const queuedCalls = new Set( + [...agent.inbox.nextStep, ...agent.inbox.nextTurn].flatMap((message) => + message.source?.kind === "user-question-reply" && message.source.callId !== undefined + ? [dshQuestionRequestId(message.source.callId)] + : [], + ), + ); + const continued = projectDshContinuedQuestions( + this.options.context.sessionProjections.snapshot(agent.session).values, + (callId) => { + for (let seq = agent.session.seq - 1; seq >= 0; seq -= 1) { + const event = agent.session.eventAt(seq); + if (event !== undefined && isDshQuestionCall(event, callId)) return event; + } + return undefined; + }, + ).filter((request) => !queuedCalls.has(request.requestId)); + const foreground = this.questionInteractions.get(String(agent.session.id))?.snapshot() ?? []; + const foregroundIds = new Set(foreground.map((request) => request.requestId)); + return [...foreground, ...continued.filter((request) => !foregroundIds.has(request.requestId))]; + } + + respondContinuedQuestion( + agent: DshAgent, + input: AgentQuestionResponseInput, + ): AgentQuestionResponseResult { + const question = this.options.context.sessionProjections + .snapshot(agent.session) + .values.userQuestions?.active.find( + (question) => + question.state === "continued" && + dshQuestionRequestId(question.callId) === input.requestId, + ); + const request = this.questionSnapshot(agent).find( + (request) => request.requestId === input.requestId, + ); + if (question === undefined || request === undefined) return { accepted: false }; + const answer = dshQuestionAnswer(request, input); + try { + return { + accepted: this.options.context.userQuestions.answer(agent, question.callId, answer), + }; + } catch (error) { + // A reply claimed by the agent has left its inbox but is not yet in the + // durable projection. The native service still owns this admission gap. + if (dshRemoteFailureCode(error) === "REPLY_QUEUED") return { accepted: false }; + throw error; + } + } + async readCurrentModel(ref: AgentSessionRef): Promise { const values = await this.options.context.sessionReader.projections( this.options.toSessionId(ref.nativeSessionId), @@ -1427,6 +1317,8 @@ export class DshLocalBackend implements AgentBackend, DshLocalControllerHost { typeof options.context?.sessionReader?.projections !== "function" || typeof options.context?.sessionReader?.list !== "function" || typeof options.context?.sessionProjections?.snapshot !== "function" || + typeof options.context?.userQuestions?.attachWait !== "function" || + typeof options.context?.userQuestions?.answer !== "function" || typeof options.context?.workspace?.get !== "function" ) { throw new AgentBackendError( @@ -1487,7 +1379,12 @@ export class DshLocalBackend implements AgentBackend, DshLocalControllerHost { if (existing !== undefined) return existing; const created = new DshQuestionBridge( () => this.nextInteractionId("question"), - (pending) => this.controllerForInteraction(sessionId)?.publishQuestionState(pending), + this.options.context.userQuestions, + () => { + const controller = this.controllerForInteraction(sessionId); + if (controller !== undefined) + controller.publishQuestionState(controller.questionSnapshot()); + }, ); this.questionInteractions.set(sessionId, created); return created; @@ -1669,7 +1566,8 @@ export class DshLocalBackend implements AgentBackend, DshLocalControllerHost { this.controllers.set(key, controller); if (permissionBridge !== undefined) controller.publishPermissionState(permissionBridge.snapshot()); - if (questionBridge !== undefined) controller.publishQuestionState(questionBridge.snapshot()); + if (questionBridge !== undefined) + controller.publishQuestionState(controller.questionSnapshot()); return controller; } @@ -2009,6 +1907,7 @@ export class DshLocalSessionRuntime implements AgentSessionRuntime { /** Owns one DSH agent acquisition and survives runtime-façade/page switches. */ class DshLocalSessionController { + private publishedQuestions: string | undefined; readonly ref: AgentSessionRef; private cursor = agentDeliveryCursor(0); @@ -2091,7 +1990,7 @@ class DshLocalSessionController { } questionSnapshot(): readonly AgentQuestionRequest[] { - return this.questionBridge?.snapshot() ?? []; + return this.host.questionSnapshot(this.agent); } async initializeModelSelection(selection: AgentModelSelection): Promise { @@ -2208,7 +2107,7 @@ class DshLocalSessionController { ? {} : { pendingPermissions: this.permissionBridge.snapshot() }; const questions = - this.questionBridge === undefined ? {} : { pendingQuestions: this.questionBridge.snapshot() }; + this.questionBridge === undefined ? {} : { pendingQuestions: this.questionSnapshot() }; if (!this.modelInitialized || this.selectedModel === undefined) { return { ...projection, @@ -2356,7 +2255,11 @@ class DshLocalSessionController { if (this.questionBridge === undefined) { throw new AgentBackendError("unsupported", "DSH question responses are unavailable"); } - return this.questionBridge.respond(input); + const foreground = await this.questionBridge.respond(input); + if (foreground.accepted) return foreground; + const result = this.host.respondContinuedQuestion(this.agent, input); + if (result.accepted) this.publishQuestionState(this.questionSnapshot()); + return result; } publishPermissionState(pending: readonly AgentPermissionRequest[]): void { @@ -2371,12 +2274,15 @@ class DshLocalSessionController { publishQuestionState(pending: readonly AgentQuestionRequest[]): void { if (this.disposed || this.questionBridge === undefined) return; + const key = JSON.stringify(pending); + if (this.publishedQuestions === key) return; const native = lastDshSessionEvent(this.agent.session) ?? ({ data: {}, seq: 0, time: Date.now(), type: "question/state" } satisfies DshSessionEvent); this.emitState(native, `question-${this.stateRevision + 1}`, { pendingQuestions: pending, }); + this.publishedQuestions = key; } receive(event: DshSessionEvent): void { @@ -2412,6 +2318,13 @@ class DshLocalSessionController { if (event.type === "goal/change" || event.type === "todo/write") { this.emitState(event, "work-state", { workState: state.workState }); } + if ( + event.type === "tool/result" || + event.type === "tool/ptc-dispatch" || + event.type === "user/message" + ) { + this.publishQuestionState(this.questionSnapshot()); + } if (isDshPermissionConfigEvent(event)) { const permissionOptions = this.host.permissionOptions(this.ref); @@ -2498,6 +2411,7 @@ class DshLocalSessionController { this.emitState(native, `inbox-${this.stateRevision + 1}`, { pendingInputs: this.pendingInputs(), }); + this.publishQuestionState(this.questionSnapshot()); } catch (error) { this.host.report( isAgentBackendError(error) diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-projection.ts b/packages/orbis-remote-dsh/src/adapter/dsh-projection.ts index dc3dc6c..1da9b4d 100644 --- a/packages/orbis-remote-dsh/src/adapter/dsh-projection.ts +++ b/packages/orbis-remote-dsh/src/adapter/dsh-projection.ts @@ -32,6 +32,7 @@ import { type AgentUsage, } from "@orbisapp/orbis-agent-backend"; +import { isDshQuestionCall, projectDshContinuedQuestions } from "./dsh-question-projection"; import type { DshSessionEvent, DshSessionInspection, @@ -811,6 +812,9 @@ export function readDshSessionProjection( }), ...(run.lastRun === undefined ? {} : { lastRun: run.lastRun }), mode: state.mode, + pendingQuestions: projectDshContinuedQuestions(inspection.projections, (callId) => + inspection.events.findLast((event) => isDshQuestionCall(event, callId)), + ), revision: inspection.events.length, state: run.state, workState: state.workState, diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-question-bridge.ts b/packages/orbis-remote-dsh/src/adapter/dsh-question-bridge.ts new file mode 100644 index 0000000..b3ac702 --- /dev/null +++ b/packages/orbis-remote-dsh/src/adapter/dsh-question-bridge.ts @@ -0,0 +1,125 @@ +import { + validateAgentQuestionResponseForRequest, + type AgentQuestionRequest, + type AgentQuestionResponseInput, + type AgentQuestionResponseResult, + type AgentTimestamp, +} from "@orbisapp/orbis-agent-backend"; + +import { + dshQuestionAnswer, + dshQuestionRequestId, + projectDshQuestionRequest, +} from "./dsh-question-projection"; +import type { DshQuestionAnswer, DshQuestionRequest, DshUserQuestions } from "./dsh-types"; + +interface PendingQuestion { + readonly request: AgentQuestionRequest; + readonly resolve: (answer: DshQuestionAnswer) => void; + readonly reject: (reason: unknown) => void; + readonly next: () => Promise; + readonly release: () => void; +} + +/** Owns only foreground waterfall promises; continued questions remain native state. */ +export class DshQuestionBridge { + private readonly pending = new Map(); + + constructor( + private readonly nextRequestId: () => string, + private readonly native: DshUserQuestions, + private readonly onChanged: () => void, + ) {} + + requested( + native: DshQuestionRequest, + next: () => Promise, + requestedAt: AgentTimestamp, + ): Promise { + if (native.signal?.aborted) return Promise.reject(questionError("ASK_ABORTED")); + const requestId = + native.wait === undefined ? this.nextRequestId() : dshQuestionRequestId(native.wait.callId); + const request = projectDshQuestionRequest(native, requestId, requestedAt); + const claim = new AbortController(); + const result = new Promise((resolve, reject) => { + const abort = () => this.reject(requestId, questionError("ASK_ABORTED")); + native.signal?.addEventListener("abort", abort, { once: true }); + this.pending.set(requestId, { + next, + reject, + request, + resolve, + release: () => { + native.signal?.removeEventListener("abort", abort); + claim.abort(); + }, + }); + }); + if (native.wait?.timed === true && native.agent !== undefined) { + // The native stream claim stops the unattended host timer. Releasing the + // final mobile subscriber releases this claim before desktop delegation. + void this.holdWait(native.agent, native.wait.callId, claim.signal, requestId); + } + this.onChanged(); + return result; + } + + async respond(input: AgentQuestionResponseInput): Promise { + const pending = this.pending.get(input.requestId); + if (pending === undefined) return { accepted: false }; + validateAgentQuestionResponseForRequest(input, pending.request); + if (input.response.kind === "cancelled") { + this.reject(input.requestId, questionError("ASK_CANCELLED")); + } else { + const answer = dshQuestionAnswer(pending.request, input); + this.remove(input.requestId)?.resolve(answer); + } + return { accepted: true }; + } + + delegate(): void { + for (const requestId of [...this.pending.keys()]) { + const pending = this.remove(requestId); + if (pending !== undefined) void pending.next().then(pending.resolve, pending.reject); + } + } + + snapshot(): readonly AgentQuestionRequest[] { + return [...this.pending.values()].map(({ request }) => request); + } + + private remove(requestId: string): PendingQuestion | undefined { + const pending = this.pending.get(requestId); + if (pending === undefined) return undefined; + this.pending.delete(requestId); + pending.release(); + this.onChanged(); + return pending; + } + + private reject(requestId: string, reason: unknown): void { + this.remove(requestId)?.reject(reason); + } + + private async holdWait( + agent: NonNullable, + callId: string, + signal: AbortSignal, + requestId: string, + ): Promise { + try { + for await (const _frame of this.native.attachWait(agent, callId, signal)) { + // Consuming the business stream retains the claim until release/settlement. + } + } catch (error) { + if (!signal.aborted) this.reject(requestId, error); + } + } +} + +function questionError(code: "ASK_ABORTED" | "ASK_CANCELLED"): Error & { readonly code: string } { + return Object.assign(new Error("The DSH user question was cancelled"), { + code, + name: "UserQuestionError", + }); +} diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-question-projection.ts b/packages/orbis-remote-dsh/src/adapter/dsh-question-projection.ts new file mode 100644 index 0000000..6413d64 --- /dev/null +++ b/packages/orbis-remote-dsh/src/adapter/dsh-question-projection.ts @@ -0,0 +1,144 @@ +import { + AgentBackendError, + agentTimestamp, + validateAgentQuestionRequest, + validateAgentQuestionResponseForRequest, + type AgentQuestionRequest, + type AgentQuestionResponseInput, + type AgentTimestamp, +} from "@orbisapp/orbis-agent-backend"; + +import type { + DshQuestionAnswer, + DshQuestionRequest, + DshSessionEvent, + DshSessionProjectionValues, +} from "./dsh-types"; + +export function dshQuestionRequestId(callId: string): string { + return `orbis-dsh-question-call:${encodeURIComponent(callId)}`; +} + +export function projectDshQuestionRequest( + native: Pick, + requestId: string, + requestedAt: AgentTimestamp, +): AgentQuestionRequest { + const questions = native.questions.map((raw, questionIndex) => { + if (typeof raw.id !== "string" || !raw.id.trim() || raw.id !== raw.id.trim()) { + throw new AgentBackendError("protocol", "DSH question id is invalid"); + } + if (typeof raw.question !== "string" || !raw.question.trim()) { + throw new AgentBackendError("protocol", "DSH question text is invalid"); + } + const nativeOptions = raw.options ?? []; + if (!Array.isArray(nativeOptions)) { + throw new AgentBackendError("protocol", "DSH question options are invalid"); + } + const labels = new Set(); + const options = nativeOptions.map((option, optionIndex) => { + if (typeof option.label !== "string" || !option.label.trim()) { + throw new AgentBackendError("protocol", "DSH question option is invalid"); + } + if (labels.has(option.label)) { + throw new AgentBackendError("protocol", "DSH question option labels must be unique"); + } + labels.add(option.label); + const optionId = `dsh-option-${questionIndex}-${optionIndex}`; + return { + ...(option.description === undefined ? {} : { description: option.description }), + label: option.label, + optionId, + }; + }); + const intent = + raw.intent === undefined + ? undefined + : (() => { + if (raw.intent.kind !== "plan-review" || typeof raw.intent.approve !== "string") { + throw new AgentBackendError("protocol", "DSH question intent is invalid"); + } + const approveIndex = nativeOptions.findIndex( + (option) => option.label === raw.intent?.approve, + ); + if (approveIndex < 0) { + throw new AgentBackendError( + "protocol", + "DSH plan-review intent references an unknown option", + ); + } + return { + approveOptionId: `dsh-option-${questionIndex}-${approveIndex}`, + kind: "plan-review" as const, + }; + })(); + return { + ...(raw.detail === undefined ? {} : { detail: raw.detail }), + ...(raw.header === undefined ? {} : { header: raw.header }), + ...(intent === undefined ? {} : { intent }), + multiSelect: raw.multiSelect ?? false, + options, + question: raw.question, + questionId: raw.id, + }; + }); + return validateAgentQuestionRequest({ + questions, + requestedAt, + requestId, + }); +} + +export function dshQuestionAnswer( + request: AgentQuestionRequest, + input: AgentQuestionResponseInput, +): DshQuestionAnswer { + const validated = validateAgentQuestionResponseForRequest(input, request); + if (validated.response.kind === "cancelled") { + throw new AgentBackendError( + "unsupported", + "A continued question can be answered or skipped, but cannot be cancelled", + ); + } + const answers = validated.response.answers.map((answer) => ({ + ...(answer.customText === undefined ? {} : { custom: answer.customText }), + id: answer.questionId, + selected: answer.optionIds.map((optionId) => { + const label = request.questions + .find((question) => question.questionId === answer.questionId) + ?.options.find((option) => option.optionId === optionId)?.label; + if (label === undefined) { + throw new AgentBackendError("protocol", "DSH question option mapping is invalid"); + } + return label; + }), + })); + return { answers }; +} + +/** Only native continued questions accept replies through userQuestions.answer. */ +export function projectDshContinuedQuestions( + values: DshSessionProjectionValues, + eventForCall: (callId: string) => DshSessionEvent | undefined, +): readonly AgentQuestionRequest[] { + return (values.userQuestions?.active ?? []) + .filter((question) => question.state === "continued") + .map((question) => { + const event = eventForCall(question.callId); + if (event === undefined || !Number.isFinite(event.time)) { + throw new AgentBackendError("protocol", "DSH continued question has no recorded tool call"); + } + return projectDshQuestionRequest( + question, + dshQuestionRequestId(question.callId), + agentTimestamp(new Date(event.time).toISOString()), + ); + }); +} + +export function isDshQuestionCall(event: DshSessionEvent, callId: string): boolean { + if (event.type !== "tool/call" && event.type !== "tool/ptc-dispatch") return false; + if (typeof event.data !== "object" || event.data === null) return false; + const data = event.data as { readonly callId?: unknown; readonly subCallId?: unknown }; + return (event.type === "tool/call" ? data.callId : data.subCallId) === callId; +} diff --git a/packages/orbis-remote-dsh/src/adapter/dsh-types.ts b/packages/orbis-remote-dsh/src/adapter/dsh-types.ts index 617ddd7..30f6db9 100644 --- a/packages/orbis-remote-dsh/src/adapter/dsh-types.ts +++ b/packages/orbis-remote-dsh/src/adapter/dsh-types.ts @@ -148,6 +148,7 @@ export interface DshSessionReader { export interface DshUserMessage { readonly content?: readonly unknown[]; readonly id: unknown; + readonly source?: { readonly kind: string; readonly callId?: string }; } /** DSH's provider-neutral durable image reference. */ @@ -262,12 +263,29 @@ export interface DshQuestionRequest { readonly agent?: DshAgent; readonly questions: readonly DshQuestionItem[]; readonly signal?: AbortSignal; + readonly wait?: { readonly callId: string; readonly timed?: boolean }; } export interface DshQuestionAnswer { readonly answers: readonly DshQuestionAnswerItem[]; } +/** Native business operations; DSH owns foreground waits and admitted late replies. */ +export interface DshUserQuestions { + attachWait( + agent: DshAgent, + callId: string, + signal: AbortSignal, + ): AsyncIterable<{ readonly remainingMs: number }>; + answer(agent: DshAgent, callId: string, answer: DshQuestionAnswer): boolean; +} + +export interface DshProjectedQuestion { + readonly callId: string; + readonly questions: readonly DshQuestionItem[]; + readonly state: "open" | "continued"; +} + /** Host-owned presence seam used to claim DSH interactions only while Orbis can answer. */ export interface DshInteractionAvailability { isAvailable(sessionId: string): boolean; @@ -297,6 +315,10 @@ export interface DshSessionController { /** Native domain values; optional keys mean the owning plugin is not installed. */ export interface DshSessionProjectionValues { + readonly userQuestions?: { + readonly active: readonly DshProjectedQuestion[]; + readonly settled: readonly unknown[]; + }; readonly plan?: { readonly active: boolean; readonly pending: boolean }; readonly goal?: unknown; readonly todos?: unknown; @@ -396,6 +418,7 @@ export type DshAssistantStreamFrame = export interface DshContext { readonly agents: DshAgentRegistry; + readonly userQuestions: DshUserQuestions; readonly planMode?: DshSessionModeProvider; readonly sessionController: DshSessionController; readonly sessionReader: DshSessionReader; diff --git a/packages/orbis-remote-dsh/src/adapter/index.ts b/packages/orbis-remote-dsh/src/adapter/index.ts index f09504e..056ddae 100644 --- a/packages/orbis-remote-dsh/src/adapter/index.ts +++ b/packages/orbis-remote-dsh/src/adapter/index.ts @@ -48,6 +48,7 @@ export type { DshSessionProjectionRegistry, DshSessionProjectionValues, DshUserMessage, + DshUserQuestions, DshUserMessageContent, DshWorkspace, DshWorkspaceId, diff --git a/packages/orbis-remote-dsh/src/host/orbis-remote-dsh-host.test.ts b/packages/orbis-remote-dsh/src/host/orbis-remote-dsh-host.test.ts index ad406e1..66d06ce 100644 --- a/packages/orbis-remote-dsh/src/host/orbis-remote-dsh-host.test.ts +++ b/packages/orbis-remote-dsh/src/host/orbis-remote-dsh-host.test.ts @@ -123,6 +123,14 @@ test("composes a remote DSH catalog behind the v2 request handler", async () => const host = new OrbisRemoteDshHost({ dsh: { context: { + userQuestions: { + attachWait: () => { + throw new Error("Unexpected timed question"); + }, + answer: () => { + throw new Error("Unexpected continued question"); + }, + }, sessionController: { create: async (payload) => { const id = String(payload.sessionId); @@ -693,6 +701,7 @@ test("delivers DSH v2 live entries through the attached host transport", async ( const sessions = new Map(); const sessionEvents = new Map(); const agents = new Map(); + const lateAnswers: { callId: string; answer: DshQuestionAnswer }[] = []; const nativeListeners = new Set<(session: DshSession, event: DshSessionEvent) => void>(); let questionListener: | (( @@ -703,6 +712,19 @@ test("delivers DSH v2 live entries through the attached host transport", async ( const host = new OrbisRemoteDshHost({ dsh: { context: { + userQuestions: { + attachWait: () => { + throw new Error("Unexpected timed question"); + }, + answer: (agent, callId, answer) => { + lateAnswers.push({ callId, answer }); + (agent.inbox.nextStep as DshUserMessage[]).push({ + id: "late-reply", + source: { kind: "user-question-reply", callId }, + }); + return true; + }, + }, sessionController: { create: async (payload) => { const id = String(payload.sessionId); @@ -1006,6 +1028,68 @@ test("delivers DSH v2 live entries through the attached host transport", async ( await expect(questionResult).resolves.toEqual({ answers: [{ id: "host-question", selected: ["Yes"] }], }); + // A timed call that continued before the phone opened must survive the + // normal wire snapshot and route its answer through the native service. + const callId = "host-continued-call"; + const questions = [{ id: "late-question", question: "Continue?", options: [{ label: "Yes" }] }]; + emitNative({ + type: "request/header", + seq: 5, + time: Date.parse("2026-08-10T00:00:08.000Z"), + data: { + header: { + config: { model: "test-model", provider: "test-provider" }, + tools: [ + { + name: "ask_user_question", + parameters: { properties: { timeout: { type: "integer" } } }, + }, + ], + }, + }, + }); + emitNative({ + type: "tool/call", + seq: 6, + time: Date.parse("2026-08-10T00:00:09.000Z"), + data: { name: "ask_user_question", callId, arguments: JSON.stringify({ questions }) }, + }); + emitNative({ + type: "tool/result", + seq: 7, + time: Date.parse("2026-08-10T00:00:10.000Z"), + data: { + message: { + role: "tool", + toolCallId: callId, + source: { kind: "tool", callId }, + content: [{ type: "text", text: JSON.stringify({ pending: true, callId }) }], + }, + }, + }); + const continued = await client.sync({ mode: "live", ref: created.ref }); + expect(continued.state.pendingQuestions).toHaveLength(1); + const continuedId = continued.state.pendingQuestions![0]!.requestId; + const lateResponse = { + ref: created.ref, + requestId: continuedId, + response: { + kind: "answered" as const, + answers: [{ questionId: "late-question", optionIds: ["dsh-option-0-0"] }], + }, + }; + expect( + await client.respondQuestion({ ...lateResponse, idempotencyKey: "host-late-answer" }), + ).toEqual({ accepted: true }); + expect(lateAnswers).toEqual([ + { callId, answer: { answers: [{ id: "late-question", selected: ["Yes"] }] } }, + ]); + expect((await client.sync({ mode: "live", ref: created.ref })).state.pendingQuestions).toEqual( + [], + ); + expect( + await client.respondQuestion({ ...lateResponse, idempotencyKey: "host-late-duplicate" }), + ).toEqual({ accepted: false }); expect(deliveries.some((delivery) => delivery.event.type === "host.session.added")).toBe(true); } finally { removeDeliveries(); @@ -1034,6 +1118,14 @@ test("pushes a catalog row created outside the host to a listening client", asyn const host = new OrbisRemoteDshHost({ dsh: { context: { + userQuestions: { + attachWait: () => { + throw new Error("Unexpected timed question"); + }, + answer: () => { + throw new Error("Unexpected continued question"); + }, + }, sessionController: { create: async () => { throw new Error("unused"); @@ -1201,6 +1293,14 @@ test("reads the full transcript on the first cold sync of a session DSH web crea const host = new OrbisRemoteDshHost({ dsh: { context: { + userQuestions: { + attachWait: () => { + throw new Error("Unexpected timed question"); + }, + answer: () => { + throw new Error("Unexpected continued question"); + }, + }, sessionController: { create: async (payload) => { const id = String(payload.sessionId); diff --git a/packages/orbis-remote-dsh/src/plugin/dsh-plugin.ts b/packages/orbis-remote-dsh/src/plugin/dsh-plugin.ts index 99e522d..d41653a 100644 --- a/packages/orbis-remote-dsh/src/plugin/dsh-plugin.ts +++ b/packages/orbis-remote-dsh/src/plugin/dsh-plugin.ts @@ -15,7 +15,7 @@ import type {} from "@deepseek-ai/dsh-file-reference"; import { resolveDshHome } from "@deepseek-ai/dsh-home-paths"; import type { DirectoryPickerBrowseCapability } from "@deepseek-ai/dsh-host-directory-picker"; import type {} from "@deepseek-ai/dsh-host-webserver"; -import { createUserMessage } from "@deepseek-ai/dsh-llm"; +import { createUserMessage, ToolCallId } from "@deepseek-ai/dsh-llm"; import type { ContentBlock } from "@deepseek-ai/dsh-llm/types"; import type {} from "@deepseek-ai/dsh-plan-mode"; import { scopeTarget } from "@deepseek-ai/dsh-scope"; @@ -45,6 +45,7 @@ import type { DshSessionModeProvider, DshSessionPermissionProvider, DshSessionSubagentProvider, + DshUserQuestions, } from "../adapter"; import { OrbisRemoteDshHost, type OrbisRemoteDshHostDshOptions } from "../host"; import { ORBIS_DSH_DRIVER_VERSION } from "./constants"; @@ -341,6 +342,14 @@ function createOrbisDshContext(context: Context): OrbisRemoteDshHostDshOptions[" const planMode = dshPlanMode(context); return { agents: context.agents, + userQuestions: { + attachWait: (agent, callId, signal) => + context.userQuestions.attachWait(agent as Agent, ToolCallId(callId), signal), + answer: (agent, callId, answer) => + context.userQuestions.answer(agent as Agent, ToolCallId(callId), { + answers: answer.answers.map((item) => ({ ...item, selected: [...item.selected] })), + }), + } satisfies DshUserQuestions, ...(planMode === undefined ? {} : { planMode }), on: context.on.bind(context), sessionController: (context as unknown as { readonly sessionController: unknown }) diff --git a/packages/orbis-remote-dsh/src/testkit/native-projections.ts b/packages/orbis-remote-dsh/src/testkit/native-projections.ts index b138dfb..3d4db96 100644 --- a/packages/orbis-remote-dsh/src/testkit/native-projections.ts +++ b/packages/orbis-remote-dsh/src/testkit/native-projections.ts @@ -1,14 +1,24 @@ -import type { Context } from "@deepseek-ai/cordis"; +import { Context } from "@deepseek-ai/cordis"; import { goalProjectionDefinition } from "@deepseek-ai/dsh-goal"; import { planProjectionDefinition, type PlanUnitState } from "@deepseek-ai/dsh-plan-mode"; -import type { SessionEvent } from "@deepseek-ai/dsh-session"; +import { SessionLogOffset, type SessionEvent, type SessionHeader } from "@deepseek-ai/dsh-session"; import type { ProjectionDefinition } from "@deepseek-ai/dsh-session-projection"; import { apply as applyTodo } from "@deepseek-ai/dsh-tool-todo"; import type { TodoItem } from "@deepseek-ai/dsh-tool-todo"; +import { UserQuestionService } from "@deepseek-ai/dsh-user-questions"; import type { DshSessionEvent, DshSessionProjectionValues } from "../adapter/dsh-types"; let todosDefinition: ProjectionDefinition<"todos", TodoItem[] | null>; +const questionContext = new Context(); +const questionsRegistered = new Promise>((resolve) => { + questionContext.provide("sessionProjections", { + register: resolve, + } as unknown as Context["sessionProjections"]); +}); +new UserQuestionService(questionContext); +const questionsDefinition = await questionsRegistered; +await questionContext.fiber.dispose(); applyTodo( { sessionProjections: { @@ -28,15 +38,20 @@ export function nativeWorkStateValues( let plan: PlanUnitState = planProjectionDefinition.init(); let goal: Parameters[0] = goalProjectionDefinition.init(); let todos: TodoItem[] | null = null; + let questions = questionsDefinition.init({} as SessionHeader, SessionLogOffset(0)); for (const event of events) { const native = event as SessionEvent; plan = planProjectionDefinition.apply(plan, native); goal = goalProjectionDefinition.apply(goal, native); todos = todosDefinition.apply(todos, native); + questions = questionsDefinition.apply(questions, native); } return { plan: planProjectionDefinition.wire.viewSchema.parse(planProjectionDefinition.wire.view(plan)), goal: goalProjectionDefinition.wire.viewSchema.parse(goalProjectionDefinition.wire.view(goal)), todos: todosDefinition.wire!.viewSchema.parse(todosDefinition.wire!.view(todos)), + userQuestions: questionsDefinition.wire!.viewSchema.parse( + questionsDefinition.wire!.view(questions), + ), }; } From b307fda050ec98da72649f247439621a1c39c34e Mon Sep 17 00:00:00 2001 From: Lance Wang Date: Wed, 7 Oct 2026 09:39:56 +0800 Subject: [PATCH 2/2] fix(remote-dsh): disable replay E2E providers by id --- packages/orbis-remote-dsh/scripts/real-profile-e2e-provider.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/orbis-remote-dsh/scripts/real-profile-e2e-provider.ts b/packages/orbis-remote-dsh/scripts/real-profile-e2e-provider.ts index 7c1eeed..315fb8c 100644 --- a/packages/orbis-remote-dsh/scripts/real-profile-e2e-provider.ts +++ b/packages/orbis-remote-dsh/scripts/real-profile-e2e-provider.ts @@ -23,10 +23,8 @@ export function createRealProfileOverlay(options: RealProfileOverlayOptions): st options.providerMode === "replay" ? [ "- id: llm-deepseek", - ' name: "@deepseek-ai/dsh-llm-deepseek"', " disabled: true", "- id: session-title-llm", - ' name: "@deepseek-ai/dsh-session-title-first-prompt-llm"', " disabled: true", "- insert:", " - id: orbis-e2e-llm-replay",