Merge branch 'worktree/process-plugin-streaming-72f9b3' into worktree/job-kill-delivery
# Conflicts: # docs/event-producer-consumer.i18n.yaml # docs/event-producer-consumer.md # docs/event-producer-consumer.zh.md # packages/api/session-controller/src/client/sessions/session.ts # packages/extensions/cordis-client-runner/src/client/api-catalog.ts # packages/extensions/tool-cordis/src/api-catalog.ts # packages/host/apiproxy/src/api/rpc.schema.ts # packages/session/session-projection-cache/tests/cache.spec.ts # packages/shell/tool-bash/tests/observe.spec.ts # packages/shell/tool-pwsh/tests/observe.spec.ts # snapshots/web/approval-composer/session.jsonl # snapshots/web/code-mode-round/session.jsonl # snapshots/web/cordis-tool-round/session.jsonl # snapshots/web/feedback-command/session.jsonl # snapshots/web/fresh-round-trip/session.jsonl # snapshots/web/goal-multi-turn-actions/session.jsonl # snapshots/web/lifecycle-chrome/session.jsonl # snapshots/web/live-interactions/session.jsonl # snapshots/web/minimal-preset/session.jsonl # snapshots/web/permission-policy-context/session.jsonl # snapshots/web/plan-review/session.jsonl # snapshots/web/question-composer/session.jsonl # snapshots/web/steering/session.jsonl # snapshots/web/turn-tail-actions/session.jsonl # snapshots/web/web-search-round/session.jsonl
This commit is contained in:
commit
e5d5d16dd2
1578 files changed
+56300
-13839
No files matched your search
@@ -1,10 +1,11 @@
|
||||
/** Client operation results spanning Session Remote calls and the legacy subagent carrier. */
|
||||
/** Client operation results spanning the Session and subagent Remote calls. */
|
||||
|
||||
import type { RpcError } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentControlError } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { SessionError } from '../../types.ts'
|
||||
|
||||
/** Failure surfaced by the Client Session object layer. */
|
||||
export type ClientFailure = RpcError | SessionError
|
||||
export type ClientFailure = RpcError | SessionError | SubagentControlError
|
||||
|
||||
/** Success or failure returned by a Client Session operation. */
|
||||
export type ClientResult<T> =
|
||||
@@ -13,7 +14,7 @@ export type ClientResult<T> =
|
||||
|
||||
/**
|
||||
* Fold a rejected carrier operation into the Client Session failure vocabulary.
|
||||
* @param error - rejection from a legacy subagent or local carrier call.
|
||||
* @param error - rejection from a Remote or local carrier call.
|
||||
* @returns the failure branch of a Client Session result.
|
||||
*/
|
||||
export function transportResult<T>(error: unknown): ClientResult<T> {
|
||||
|
||||
@@ -12,9 +12,37 @@ import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
|
||||
import type { PromptContentPart, QueueAction } from '../../types.ts'
|
||||
import type { PromptContentPart, QueueAction, SessionRequestId } from '../../types.ts'
|
||||
import type { ClientResult } from './result.ts'
|
||||
import type { SessionSnapshot } from './snapshot.ts'
|
||||
import type { PendingSubmissionImage, SessionSnapshot } from './snapshot.ts'
|
||||
|
||||
/**
|
||||
* Why a local submission echo left the snapshot: `observed` when its durable
|
||||
* `user/message` event or host queue occurrence arrived (with the admitted
|
||||
* image references in prompt order), `failed` when the prompt was rejected,
|
||||
* threw, or was aborted before acceptance.
|
||||
*/
|
||||
export type PendingSubmissionRetirement =
|
||||
| { readonly reason: 'observed'; readonly attachments: readonly ImageAttachmentRef[] }
|
||||
| { readonly reason: 'failed' }
|
||||
|
||||
/** Input registering one local submission echo ahead of its prompt call. */
|
||||
export interface BeginSubmissionInput {
|
||||
/** Prompt text exactly as the upcoming prompt will send it. */
|
||||
readonly text: string
|
||||
/** Ordered image previews matching the upcoming prompt's image parts. */
|
||||
readonly images: readonly PendingSubmissionImage[]
|
||||
/** Settlement callback fired exactly once when the echo retires. */
|
||||
readonly onRetire?: (retirement: PendingSubmissionRetirement) => void
|
||||
}
|
||||
|
||||
/** One registered submission echo: the identity its prompt must carry, and the pre-prompt escape hatch. */
|
||||
export interface SubmissionHandle {
|
||||
/** The prompt RPC identity; pass it to {@link ISession.prompt}. */
|
||||
readonly requestId: SessionRequestId
|
||||
/** Retire the echo as failed when the caller cannot reach prompt() (serialization failure); no-op after any other settlement. */
|
||||
abandon(): void
|
||||
}
|
||||
|
||||
/** Key-addressed projection read face (the useProjection resolution path; see ProjectionValueStore). */
|
||||
export interface ProjectionsFace {
|
||||
@@ -33,16 +61,29 @@ export interface ISession {
|
||||
readonly sessionId: SessionId
|
||||
/** Host-computed projection values by key (the useProjection seat). */
|
||||
readonly projections: ProjectionsFace
|
||||
/**
|
||||
* Register one local submission echo in `snapshot.pendingSubmissions`,
|
||||
* synchronously, before the caller serializes and sends the prompt. The
|
||||
* echo retires when a durable `user/message` event or queue occurrence
|
||||
* carrying the returned identity arrives, or when the identified prompt
|
||||
* call fails.
|
||||
* @param input - echo content and the optional settlement callback.
|
||||
* @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
|
||||
*/
|
||||
beginSubmission(input: BeginSubmissionInput): SubmissionHandle
|
||||
/**
|
||||
* Send a prompt into the session.
|
||||
* @param content - text plus browser-owned temporary image uploads.
|
||||
* @param mode - 'queue' appends a turn; 'steer' interrupts the running one.
|
||||
* @param signal - optional caller cancellation for the complete admission round-trip.
|
||||
* @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
|
||||
* @returns acceptance, or the business error (also mirrored into snapshot.promptError).
|
||||
*/
|
||||
prompt(
|
||||
content: PromptContentPart[],
|
||||
mode: 'queue' | 'steer',
|
||||
signal?: AbortSignal,
|
||||
requestId?: SessionRequestId,
|
||||
): Promise<ClientResult<{ accepted: true }>>
|
||||
/**
|
||||
* Resolve one durable image referenced by this session.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* explicit act of widening what features may do to the sessions domain.
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
import type { AgentContext } from '../scope.ts'
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
|
||||
import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { SessionRequestId } from '../../types.ts'
|
||||
import type { ClientFailure } from './result.ts'
|
||||
|
||||
/** One transient inbox occurrence from the authoritative queue snapshot. */
|
||||
@@ -10,11 +11,42 @@ export interface QueuedMessage {
|
||||
readonly id: MessageId
|
||||
readonly messageId: MessageId
|
||||
readonly placement: 'queued' | 'steering' | 'context'
|
||||
/** Prompt-RPC identity of a browser-submitted occurrence; correlates the local submission echo. */
|
||||
readonly rpcId?: SessionRequestId
|
||||
readonly content: readonly ContentBlock[]
|
||||
readonly preview: string
|
||||
readonly text: string | null
|
||||
}
|
||||
|
||||
/** One image displayed by a local submission echo before durable admission. */
|
||||
export interface PendingSubmissionImage {
|
||||
/** Browser-owned preview URL; its lifecycle belongs to the submitter, never this snapshot. */
|
||||
readonly previewUrl: string
|
||||
/** Browser file name, when the file had one. */
|
||||
readonly name?: string
|
||||
/** Intrinsic pixel width, when the submitter has probed it. */
|
||||
readonly width?: number
|
||||
/** Intrinsic pixel height, when the submitter has probed it. */
|
||||
readonly height?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* One local prompt-submission echo: inserted synchronously when a submission
|
||||
* begins, so the conversation can show the message before serialization,
|
||||
* transport, and durable admission complete. Client-memory only — reload and
|
||||
* reconnect rebuild the conversation from durable events alone.
|
||||
*/
|
||||
export interface PendingSubmission {
|
||||
/** The prompt RPC identity; the durable `user/message` source echoes it as `rpcId`. */
|
||||
readonly requestId: SessionRequestId
|
||||
/** Client wall-clock ms when the submission began. */
|
||||
readonly time: number
|
||||
/** Prompt text exactly as it will be sent (one text block). */
|
||||
readonly text: string
|
||||
/** Ordered image previews matching the prompt's image parts. */
|
||||
readonly images: readonly PendingSubmissionImage[]
|
||||
}
|
||||
|
||||
/** History-open lifecycle of a Session event window. */
|
||||
export type OpenState = 'cold' | 'loading' | 'open' | 'error'
|
||||
|
||||
@@ -28,6 +60,8 @@ export interface PromptError {
|
||||
export interface SessionSnapshot {
|
||||
readonly sessionId: SessionId
|
||||
readonly queue: readonly QueuedMessage[]
|
||||
/** Local prompt-submission echoes not yet observed as durable events or queue occurrences. */
|
||||
readonly pendingSubmissions: readonly PendingSubmission[]
|
||||
readonly running: boolean
|
||||
readonly subagent: {
|
||||
readonly address: SubagentAddress
|
||||
|
||||
@@ -40,7 +40,14 @@ export type {
|
||||
SessionProjectionMap,
|
||||
UseProjection,
|
||||
} from './sessions/projection-store.ts'
|
||||
export type { ISession, ProjectionsFace, SessionFace } from './contract/session.ts'
|
||||
export type {
|
||||
BeginSubmissionInput,
|
||||
ISession,
|
||||
PendingSubmissionRetirement,
|
||||
ProjectionsFace,
|
||||
SessionFace,
|
||||
SubmissionHandle,
|
||||
} from './contract/session.ts'
|
||||
export type { ISessions } from './contract/sessions.ts'
|
||||
export { MutableSessionEventSource } from './contract/events.ts'
|
||||
export type {
|
||||
@@ -53,6 +60,8 @@ export type {
|
||||
} from './contract/events.ts'
|
||||
export type {
|
||||
OpenState,
|
||||
PendingSubmission,
|
||||
PendingSubmissionImage,
|
||||
PromptError,
|
||||
QueuedMessage,
|
||||
SessionSnapshot,
|
||||
@@ -73,6 +82,7 @@ export const inject = [
|
||||
'remote',
|
||||
'remote.commands',
|
||||
'remote.session',
|
||||
'remote.subagents',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -82,7 +92,7 @@ export const inject = [
|
||||
export function apply(ctx: Context): void {
|
||||
const connection = ctx.get('connection') as ConnectionHandle
|
||||
const remotes = ctx.remote as unknown as SessionRemotes
|
||||
const sessions = new ClientSessions(ctx, connection.api, remotes)
|
||||
const sessions = new ClientSessions(ctx, remotes)
|
||||
ctx.remote.$on('api-session/added', (summary) => { sessions.handleSessionAdded(summary) })
|
||||
ctx.remote.$on('api-session/removed', (sessionId) => { sessions.handleSessionRemoved(sessionId) })
|
||||
ctx.remote.$on('api-session/status', (sessionId, running) => {
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
// dispatch entry + list state, constructed and held by ClientSessions (one per browser client).
|
||||
// List data never enters zustand; React connects via subscribe/getListSnapshot.
|
||||
|
||||
import type {
|
||||
IApiClient, SubagentAddress, SubagentCatalog,
|
||||
} from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentAddress, SubagentCatalog } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
import type {
|
||||
@@ -145,11 +143,10 @@ export class SessionManager {
|
||||
})
|
||||
|
||||
/**
|
||||
* @param api - shared wire client.
|
||||
* @param remote - generated Remote namespaces the Session cluster calls.
|
||||
* @param restoredSelection - persisted real-Session selection candidate.
|
||||
*/
|
||||
constructor(
|
||||
private readonly api: IApiClient,
|
||||
private readonly remote: SessionRemotes,
|
||||
restoredSelection?: SessionId,
|
||||
restoredAddress?: SubagentAddress,
|
||||
@@ -321,7 +318,7 @@ export class SessionManager {
|
||||
const parentAvailable = address === undefined
|
||||
? undefined
|
||||
: this.catalogs.get(address.parentSessionId)?.parentAvailable
|
||||
return new Session(sessionId, this.api, this.remote, {
|
||||
return new Session(sessionId, this.remote, {
|
||||
...(address === undefined ? {} : {
|
||||
address,
|
||||
...catalogAvailability(parentAvailable),
|
||||
@@ -369,7 +366,7 @@ export class SessionManager {
|
||||
this.notifier.markDirty()
|
||||
const operation = (async () => {
|
||||
try {
|
||||
const { result } = await this.api.subagents.list({ parentSessionId })
|
||||
const result = toSessionResult(await this.remote.subagents.list(parentSessionId))
|
||||
if (result.ok) {
|
||||
const parentAvailable = this.catalogInflight.get(parentSessionId)?.parentAvailableOverride
|
||||
?? result.value.parentAvailable
|
||||
|
||||
@@ -43,6 +43,7 @@ export class SessionQueueMirror {
|
||||
id: item.id,
|
||||
messageId: item.message.id,
|
||||
placement: item.placement,
|
||||
...(item.rpcId === undefined ? {} : { rpcId: item.rpcId }),
|
||||
content,
|
||||
preview: previewOf(content),
|
||||
text: textOf(content),
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
import type { EncodedImageAttachment } from '@deepseek-ai/dsh-attachment/types'
|
||||
import type { ClientRemote } from '@deepseek-ai/dsh-api-gateway/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type {
|
||||
SubagentCatalog, SubagentInterruptReceipt, SubagentPromptReceipt, SubagentPromptRequest,
|
||||
} from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { SessionRemote } from '../transport.ts'
|
||||
|
||||
@@ -21,9 +24,24 @@ export interface SessionCommandsRemote {
|
||||
): Promise<RemoteResult<object | undefined>>
|
||||
}
|
||||
|
||||
/** Narrow subagent namespace consumed by a Client Session and its manager. */
|
||||
export interface SessionSubagentsRemote {
|
||||
list(parentSessionId: SessionId, signal?: AbortSignal): Promise<RemoteResult<SubagentCatalog>>
|
||||
prompt(
|
||||
request: SubagentPromptRequest,
|
||||
signal?: AbortSignal,
|
||||
): Promise<RemoteResult<SubagentPromptReceipt>>
|
||||
interruptByParent(
|
||||
childSessionId: SessionId,
|
||||
parentSessionId: SessionId,
|
||||
mode: 'continuable',
|
||||
): Promise<RemoteResult<SubagentInterruptReceipt>>
|
||||
}
|
||||
|
||||
/** Generated Remote namespaces consumed by the Client Session object layer. */
|
||||
export interface SessionRemotes {
|
||||
readonly $stream: ClientRemote['$stream']
|
||||
readonly commands: SessionCommandsRemote
|
||||
readonly session: SessionRemote
|
||||
readonly subagents: SessionSubagentsRemote
|
||||
}
|
||||
@@ -15,9 +15,7 @@
|
||||
* survives frozen (read-only view) until the stage moves on.
|
||||
*/
|
||||
import type { Context, Fiber } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
IApiClient, SubagentAddress,
|
||||
} from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { workspaceTitleOf } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
@@ -218,12 +216,10 @@ export class ClientSessions implements ISessions {
|
||||
|
||||
/**
|
||||
* @param ctx - client root context (scope fibers mount under it).
|
||||
* @param api - wire client shared with every Session.
|
||||
* @param remote - generated Remote namespaces shared with every Session.
|
||||
*/
|
||||
constructor(
|
||||
private readonly rootCtx: Context,
|
||||
api: IApiClient,
|
||||
remote: SessionRemotes,
|
||||
) {
|
||||
this.selection = createSnapshotStore<SessionSelection>(
|
||||
@@ -231,7 +227,6 @@ export class ClientSessions implements ISessions {
|
||||
{ persist: { name: 'dsh.sessions.current' } })
|
||||
const restored = this.selection.getSnapshot()
|
||||
this.manager = new SessionManager(
|
||||
api,
|
||||
remote,
|
||||
restored.sessionId,
|
||||
restored.subagentAddress,
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
|
||||
import type { AttachmentIdType, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
|
||||
import type {
|
||||
IApiClient, SubagentAddress,
|
||||
} from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
|
||||
import type { JobId } from '@deepseek-ai/dsh-jobs/brand'
|
||||
import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
@@ -25,9 +23,11 @@ import type {
|
||||
} from '../../types.ts'
|
||||
import type { ClientFailure, ClientResult } from '../contract/result.ts'
|
||||
import { transportResult } from '../contract/result.ts'
|
||||
import type { SessionFace } from '../contract/session.ts'
|
||||
import type {
|
||||
OpenState, PromptError, SessionSnapshot,
|
||||
BeginSubmissionInput, PendingSubmissionRetirement, SessionFace, SubmissionHandle,
|
||||
} from '../contract/session.ts'
|
||||
import type {
|
||||
OpenState, PendingSubmission, PromptError, SessionSnapshot,
|
||||
} from '../contract/snapshot.ts'
|
||||
import { MutableSessionEventSource } from '../contract/events.ts'
|
||||
import type {
|
||||
@@ -102,6 +102,14 @@ export class Session implements SessionFace {
|
||||
private removed = false
|
||||
private promptError: PromptError | null = null
|
||||
private lastAgentError: string | null = null
|
||||
/** Local submission echoes, insertion-ordered (see SessionSnapshot.pendingSubmissions). */
|
||||
private pendingSubmissions: readonly PendingSubmission[] = []
|
||||
/** Per-echo settlement state; `retiring` latches the first observation so a
|
||||
* queue frame and its durable event cannot both retire one echo. */
|
||||
private readonly submissionSettlements = new Map<SessionRequestId, {
|
||||
readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined
|
||||
retiring: boolean
|
||||
}>()
|
||||
/** Owns the addressed page/follow lifecycle while this Session is open. */
|
||||
private events: SessionEventStream | undefined
|
||||
|
||||
@@ -134,13 +142,11 @@ export class Session implements SessionFace {
|
||||
|
||||
/**
|
||||
* @param sessionId - Host session identity (client sessions are always Host-born).
|
||||
* @param api - shared wire client.
|
||||
* @param remote - generated Remote namespaces this session calls.
|
||||
* @param options - optional manager-owned state observers.
|
||||
*/
|
||||
constructor(
|
||||
readonly sessionId: SessionId,
|
||||
private readonly api: IApiClient,
|
||||
private readonly remote: SessionRemotes,
|
||||
private readonly options: SessionOptions = {},
|
||||
) {
|
||||
@@ -173,16 +179,42 @@ export class Session implements SessionFace {
|
||||
|
||||
// ---- Operations ----
|
||||
|
||||
/**
|
||||
* Register one local submission echo (see the ISession declaration).
|
||||
* Synchronous through markDirty: the echo is in the very next snapshot, so
|
||||
* the conversation can paint it before the caller starts serializing.
|
||||
* @param input - echo content and the optional settlement callback.
|
||||
* @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
|
||||
*/
|
||||
beginSubmission(input: BeginSubmissionInput): SubmissionHandle {
|
||||
const requestId = randomUUID() as SessionRequestId
|
||||
this.pendingSubmissions = [...this.pendingSubmissions, {
|
||||
requestId,
|
||||
time: Date.now(),
|
||||
text: input.text,
|
||||
images: input.images,
|
||||
}]
|
||||
this.submissionSettlements.set(requestId, { onRetire: input.onRetire, retiring: false })
|
||||
// The blank → engaging edge flips here, ahead of prompt(): the composer
|
||||
// docks and the echo renders on the click's own frame.
|
||||
this.promptAttempted = true
|
||||
this.notifier.markDirty()
|
||||
return { requestId, abandon: () => { this.retireFailedSubmission(requestId) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Send (queue/steer passed through 1:1); failures land in the snapshot's promptError.
|
||||
* @param content - text plus browser-owned temporary image uploads.
|
||||
* @param mode - queue appends after the current turn; steer interrupts it.
|
||||
* @param signal - optional caller cancellation for the complete admission round-trip.
|
||||
* @param requestId - identity from {@link beginSubmission}; a failed identified prompt retires its echo.
|
||||
* @returns the prompt result (also mirrored into promptError on failure).
|
||||
*/
|
||||
async prompt(
|
||||
content: PromptContentPart[],
|
||||
mode: 'queue' | 'steer',
|
||||
signal?: AbortSignal,
|
||||
requestId?: SessionRequestId,
|
||||
): Promise<ClientResult<{ accepted: true }>> {
|
||||
this.promptError = null
|
||||
this.lastAgentError = null
|
||||
@@ -197,7 +229,7 @@ export class Session implements SessionFace {
|
||||
if (this.address === undefined) {
|
||||
const clientTimeZone = resolvedClientTimeZone()
|
||||
result = toSessionResult(await this.remote.session.prompt({
|
||||
requestId: randomUUID() as SessionRequestId,
|
||||
requestId: requestId ?? randomUUID() as SessionRequestId,
|
||||
sessionId: this.sessionId,
|
||||
mode,
|
||||
content,
|
||||
@@ -223,13 +255,16 @@ export class Session implements SessionFace {
|
||||
},
|
||||
}
|
||||
} else {
|
||||
const routed = (await this.api.subagents.prompt({
|
||||
...this.address,
|
||||
const routed = toSessionResult(await this.remote.subagents.prompt({
|
||||
requestId: randomUUID() as SessionRequestId,
|
||||
parentSessionId: this.address.parentSessionId,
|
||||
childSessionId: this.address.childSessionId,
|
||||
mode: this.address.mode,
|
||||
content: content.flatMap(part => part.type === 'text'
|
||||
? [{ type: 'text' as const, text: part.text }]
|
||||
: []),
|
||||
clientTimeZone: resolvedClientTimeZone(),
|
||||
}, signal)).result
|
||||
}, signal))
|
||||
result = routed.ok ? { ok: true, value: { accepted: true } } : routed
|
||||
}
|
||||
}
|
||||
@@ -237,6 +272,7 @@ export class Session implements SessionFace {
|
||||
result = transportResult(error)
|
||||
}
|
||||
if (!result.ok) {
|
||||
if (requestId !== undefined) this.retireFailedSubmission(requestId)
|
||||
this.promptError = { op: 'send', error: result.error }
|
||||
this.notifier.markDirty()
|
||||
return result
|
||||
@@ -291,7 +327,7 @@ export class Session implements SessionFace {
|
||||
/**
|
||||
* Stop the active turn while the Host preserves pending inbox work; failures
|
||||
* land in promptError (same error-strip display slot). A continuable
|
||||
* subagent address routes through `subagent.interrupt`, whose durable
|
||||
* subagent address routes through `subagents.interruptByParent`, whose durable
|
||||
* parent-address authority works without a live parent Agent; a one-shot
|
||||
* address stays uncancellable (the UI offers no stop action, so this arm is
|
||||
* defensive).
|
||||
@@ -315,7 +351,11 @@ export class Session implements SessionFace {
|
||||
let result: ClientResult<{ accepted: true }>
|
||||
try {
|
||||
result = address !== undefined
|
||||
? (await this.api.subagents.interrupt(address)).result
|
||||
? toSessionResult(await this.remote.subagents.interruptByParent(
|
||||
address.childSessionId,
|
||||
address.parentSessionId,
|
||||
address.mode,
|
||||
))
|
||||
: toSessionResult(await this.remote.session.cancel({ sessionId: this.sessionId }))
|
||||
} catch (error) {
|
||||
result = transportResult(error)
|
||||
@@ -452,6 +492,7 @@ export class Session implements SessionFace {
|
||||
*/
|
||||
replaceControl(queue: readonly SessionQueuedItem[]): void {
|
||||
this.queueMirror.replace(queue)
|
||||
this.observeSubmissionQueue(queue)
|
||||
this.notifier.markDirty()
|
||||
}
|
||||
|
||||
@@ -461,6 +502,7 @@ export class Session implements SessionFace {
|
||||
*/
|
||||
handleControlFrame(frame: Extract<SessionControlFrame, { type: 'queue' }>): void {
|
||||
this.queueMirror.replace(frame.items)
|
||||
this.observeSubmissionQueue(frame.items)
|
||||
this.notifier.markDirty()
|
||||
}
|
||||
|
||||
@@ -541,6 +583,12 @@ export class Session implements SessionFace {
|
||||
* @returns when the Remote iterator has completed teardown.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
// Unsettled echoes retire as failed so their owners can restore or
|
||||
// release browser resources; echoes already scheduled as observed keep
|
||||
// that settlement.
|
||||
for (const requestId of [...this.submissionSettlements.keys()]) {
|
||||
this.retireFailedSubmission(requestId)
|
||||
}
|
||||
this.openGeneration++
|
||||
const events = this.events
|
||||
this.events = undefined
|
||||
@@ -599,6 +647,7 @@ export class Session implements SessionFace {
|
||||
if (entries.some(entry => entry.event.type === 'turn/start')) this.firstPromptPendingTurn = false
|
||||
if (projections !== undefined) this.projections.seed(projections)
|
||||
this.eventSource.replace(entries, hasMore)
|
||||
for (const entry of entries) this.observeSubmissionEvent(entry.event)
|
||||
this.notifier.markDirty()
|
||||
}
|
||||
|
||||
@@ -616,9 +665,70 @@ export class Session implements SessionFace {
|
||||
if (event.type === 'turn/start') this.firstPromptPendingTurn = false
|
||||
const queueChanged = this.queueMirror.acceptDurable(event)
|
||||
this.eventSource.append(entry)
|
||||
// After the feed append: the conversation assembly's animation frame is
|
||||
// registered by the feed subscribers above, so the echo-retirement frame
|
||||
// scheduled here always runs after the durable node became renderable.
|
||||
this.observeSubmissionEvent(event)
|
||||
return queueChanged || awaitingFirstTurn !== this.firstPromptPendingTurn
|
||||
}
|
||||
|
||||
/** Retire the matching echo when a durable browser-prompt `user/message` becomes visible. */
|
||||
private observeSubmissionEvent(event: { readonly type: string; readonly data?: unknown }): void {
|
||||
if (this.submissionSettlements.size === 0 || event.type !== 'user/message') return
|
||||
// Structural read: window entries may be compact history records, so the
|
||||
// fields are narrowed rather than trusted (same posture as Conversation
|
||||
// assembly matchers).
|
||||
const data = event.data as { readonly source?: unknown; readonly content?: unknown } | undefined
|
||||
const source = data?.source as { readonly kind?: unknown; readonly rpcId?: unknown } | undefined
|
||||
if (source?.kind !== 'user' || typeof source.rpcId !== 'string') return
|
||||
this.scheduleObservedRetirement(source.rpcId as SessionRequestId, imageRefsIn(data?.content))
|
||||
}
|
||||
|
||||
/** Retire echoes whose prompts landed in the host inbox instead of the log (running-turn submissions). */
|
||||
private observeSubmissionQueue(items: readonly SessionQueuedItem[]): void {
|
||||
if (this.submissionSettlements.size === 0) return
|
||||
for (const item of items) {
|
||||
if (item.rpcId !== undefined) {
|
||||
this.scheduleObservedRetirement(item.rpcId, imageRefsIn(item.message.content))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Latch one observed settlement and remove the echo an animation frame
|
||||
* later. The delay keeps the echo in the snapshot until the frame in which
|
||||
* the durable node (whose assembly frame was registered first) is
|
||||
* renderable; the render-time rpcId dedupe hides the one-frame overlap.
|
||||
*/
|
||||
private scheduleObservedRetirement(
|
||||
requestId: SessionRequestId,
|
||||
attachments: readonly ImageAttachmentRef[],
|
||||
): void {
|
||||
const settlement = this.submissionSettlements.get(requestId)
|
||||
if (settlement === undefined || settlement.retiring) return
|
||||
settlement.retiring = true
|
||||
scheduleFrame(() => { this.finishSubmission(requestId, { reason: 'observed', attachments }) })
|
||||
}
|
||||
|
||||
/** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
|
||||
private retireFailedSubmission(requestId: SessionRequestId): void {
|
||||
const settlement = this.submissionSettlements.get(requestId)
|
||||
if (settlement === undefined || settlement.retiring) return
|
||||
settlement.retiring = true
|
||||
this.finishSubmission(requestId, { reason: 'failed' })
|
||||
}
|
||||
|
||||
/** Single removal point: drop the echo, publish, then notify the owner. */
|
||||
private finishSubmission(requestId: SessionRequestId, retirement: PendingSubmissionRetirement): void {
|
||||
const settlement = this.submissionSettlements.get(requestId)
|
||||
/* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
|
||||
if (settlement === undefined) return
|
||||
this.submissionSettlements.delete(requestId)
|
||||
this.pendingSubmissions = this.pendingSubmissions.filter(echo => echo.requestId !== requestId)
|
||||
this.notifier.markDirty()
|
||||
settlement.onRetire?.(retirement)
|
||||
}
|
||||
|
||||
/** Publish a terminal background failure only while this stream still owns the Session. */
|
||||
private failEventStream(events: SessionEventStream, generation: number, error: unknown): void {
|
||||
if (generation !== this.openGeneration || this.events !== events) return
|
||||
@@ -635,6 +745,7 @@ export class Session implements SessionFace {
|
||||
return {
|
||||
sessionId: this.sessionId,
|
||||
queue: this.queueMirror.snapshot(),
|
||||
pendingSubmissions: this.pendingSubmissions,
|
||||
running: this.running,
|
||||
subagent: this.address === undefined
|
||||
? null
|
||||
@@ -662,6 +773,26 @@ export class Session implements SessionFace {
|
||||
}
|
||||
}
|
||||
|
||||
/** Run one callback on the next animation frame, or a macrotask where no frame clock exists. */
|
||||
function scheduleFrame(fn: () => void): void {
|
||||
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => { fn() })
|
||||
else setTimeout(fn, 0)
|
||||
}
|
||||
|
||||
/** Image attachment references in one structurally-read content block list, in block order. */
|
||||
function imageRefsIn(content: unknown): readonly ImageAttachmentRef[] {
|
||||
if (!Array.isArray(content)) return []
|
||||
const refs: ImageAttachmentRef[] = []
|
||||
for (const block of content) {
|
||||
if (typeof block !== 'object' || block === null) continue
|
||||
const candidate = block as { readonly type?: unknown; readonly attachment?: unknown }
|
||||
if (candidate.type === 'image' && typeof candidate.attachment === 'object' && candidate.attachment !== null) {
|
||||
refs.push(candidate.attachment as ImageAttachmentRef)
|
||||
}
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
/** Convert a terminal Session stream failure to the Client error vocabulary. */
|
||||
function openFailure(error: unknown): ClientFailure {
|
||||
const failure = sessionStreamFailure(error)
|
||||
|
||||
@@ -188,16 +188,24 @@ function queueItems(
|
||||
...project('next-turn').map(message => ({
|
||||
id: message.id,
|
||||
placement: 'queued' as const,
|
||||
...promptRpcId(message),
|
||||
message: { id: message.id, content: message.content as unknown as JsonValue[] },
|
||||
})),
|
||||
...project('next-step').map(message => ({
|
||||
id: message.id,
|
||||
placement: message.source.kind === 'user' ? 'steering' as const : 'context' as const,
|
||||
...promptRpcId(message),
|
||||
message: { id: message.id, content: message.content as unknown as JsonValue[] },
|
||||
})),
|
||||
]
|
||||
}
|
||||
|
||||
/** Prompt-RPC identity carried by a browser-submitted message's user source. */
|
||||
function promptRpcId(message: UserMessage): Pick<SessionQueuedItem, 'rpcId'> {
|
||||
const source = message.source
|
||||
return source.kind === 'user' && 'rpcId' in source ? { rpcId: source.rpcId } : {}
|
||||
}
|
||||
|
||||
function jobView(job: JobSnapshot): SessionJob {
|
||||
return {
|
||||
id: job.id,
|
||||
|
||||
@@ -445,6 +445,8 @@ export type SessionFollowFrame =
|
||||
export interface SessionQueuedItem {
|
||||
readonly id: MessageId
|
||||
readonly placement: 'queued' | 'steering' | 'context'
|
||||
/** Prompt-RPC identity from the queued message's user source; clients retire the matching local submission echo on it. */
|
||||
readonly rpcId?: SessionRequestId
|
||||
/** JSON-safe message fields consumed by pending-queue presentation. */
|
||||
readonly message: {
|
||||
readonly id: MessageId
|
||||
|
||||
Reference in new issue
Block a user