diff --git a/packages/app/src/context/global-sync.test.ts b/packages/app/src/context/global-sync.test.ts index f40bb2cb3..9723ff9dd 100644 --- a/packages/app/src/context/global-sync.test.ts +++ b/packages/app/src/context/global-sync.test.ts @@ -10,6 +10,7 @@ const globalStoreFixture = (): GlobalStore => ({ path: { state: "", config: "", worktree: "", directory: "", home: "" }, project: [], session_todo: {}, + pendingQuestions: {}, provider: { all: [], connected: [], default: {} }, provider_auth: {}, config: {}, diff --git a/packages/app/src/context/global-sync.tsx b/packages/app/src/context/global-sync.tsx index df90624e0..5c176a8d5 100644 --- a/packages/app/src/context/global-sync.tsx +++ b/packages/app/src/context/global-sync.tsx @@ -32,6 +32,8 @@ import { createRefreshQueue } from "./global-sync/queue" import { clearSessionPrefetchDirectory } from "./global-sync/session-prefetch" import { estimateRootSessionTotal, loadRootSessionsWithFallback } from "./global-sync/session-load" import { trimSessions } from "./global-sync/session-trim" +import { createPendingQuestionController } from "./global-sync/pending-question-controller" +import { pendingSessionIDsForDirectory, type PendingQuestionIndex } from "./global-sync/pending-question-index" import { applyAutomationDefinition, applyAutomationRun, @@ -77,6 +79,11 @@ export type GlobalStore = { session_todo: { [sessionID: string]: SessionTodoSnapshot } + // The single live index of question tool calls awaiting the user, across every + // directory the global event stream touches. Non-persisted (a condition, not a + // log); the dock/sidebar render from parts, this feeds the Dock badge, + // session-trim preserve, and the rising-edge alert. + pendingQuestions: PendingQuestionIndex provider: ProviderListResponse provider_auth: ProviderAuthResponse config: Config @@ -111,6 +118,7 @@ function createGlobalSync() { path: { state: "", config: "", worktree: "", directory: "", home: "" }, project: projectCache.value, session_todo: {}, + pendingQuestions: {}, provider: { all: [], connected: [], default: {} }, provider_auth: {}, config: {}, @@ -239,6 +247,24 @@ function createGlobalSync() { translate: language.t, }) + // Owns the global pending-question index (see GlobalStore.pendingQuestions). + // resolveParentID walks one step up the session tree to attribute a question + // to its root session: in-memory for an open project, falling back to the + // network for a background project whose sessions were never bootstrapped. + const questions = createPendingQuestionController({ + read: () => globalStore.pendingQuestions, + write: (mutate) => setGlobalStore("pendingQuestions", produce(mutate)), + resolveParentID: (directory, sessionID) => { + const existing = children.peekExisting(directory) + const local = existing?.[0].session.find((session) => session.id === sessionID) + if (local) return local.parentID + return globalSDK.client.session + .get({ directory, sessionID }) + .then((result) => result.data?.parentID) + .catch(() => undefined) + }, + }) + const sdkFor = (directory: string) => { const cached = sdkCache.get(directory) if (cached) return cached @@ -261,7 +287,7 @@ function createGlobalSync() { const next = trimSessions(store.session, { limit: store.limit, permission: store.permission, - externalResultQuestion: store.external_result_question, + preserveSessionIDs: pendingSessionIDsForDirectory(globalStore.pendingQuestions, directory), }) if (next.length !== store.session.length) { cleanupDroppedSessionCaches(store, setStore, next, { @@ -293,7 +319,7 @@ function createGlobalSync() { const sessions = trimSessions([...nonArchived, ...childSessions], { limit, permission: store.permission, - externalResultQuestion: store.external_result_question, + preserveSessionIDs: pendingSessionIDsForDirectory(globalStore.pendingQuestions, directory), }) setStore( "sessionTotal", @@ -432,6 +458,7 @@ function createGlobalSync() { loadSessions, translate: language.t, queryClient, + pendingQuestions: { reconcile: questions.reconcile }, }) }) @@ -474,6 +501,10 @@ function createGlobalSync() { return } + // Maintain the global pending-question index for every directory event, + // including detached background projects that have no child store. + questions.applyEvent(directory, event) + const targets = directoryEventTargets({ directory, event, @@ -655,6 +686,9 @@ function createGlobalSync() { peek: children.peek, peekExisting: children.peekExisting, retainDirectory, + // Register a rising-edge side effect for live question arrivals (the + // notification provider hooks OS notify / sound / Dock attention here). + onQuestionAlert: questions.onAlert, bootstrap, updateConfig, project: projectApi, diff --git a/packages/app/src/context/global-sync/bootstrap.test.ts b/packages/app/src/context/global-sync/bootstrap.test.ts index 98c7a2d6d..3c62fbe75 100644 --- a/packages/app/src/context/global-sync/bootstrap.test.ts +++ b/packages/app/src/context/global-sync/bootstrap.test.ts @@ -32,7 +32,6 @@ function createState(): State { turn_change_aggregate: {}, todo: {}, permission: {}, - external_result_question: {}, mcp_ready: false, mcp: {}, lsp_ready: false, @@ -118,22 +117,12 @@ describe("bootstrapDirectory", () => { }) }) - test("tolerates undefined pending question slots while pruning stale questions", async () => { + test("reconciles the external-result snapshot into the global question index", async () => { const directory = "/repo" const queryClient = new QueryClient() const [store, setStore] = createStore(createState()) - setStore("external_result_question", "ses_undefined", undefined as never) - setStore("external_result_question", "ses_stale", [ - { - id: "msg_stale:call_stale", - sessionID: "ses_stale", - questions: [{ question: "Continue?" }], - messageID: "msg_stale", - callID: "call_stale", - partID: "part_stale", - }, - ]) let externalResultCalls = 0 + const reconciled: Array<{ directory: string; entries: unknown[] }> = [] const warnings: unknown[] = [] const originalWarn = console.warn console.warn = mock((...args: unknown[]) => { @@ -170,6 +159,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile: (dir, entries) => reconciled.push({ directory: dir, entries }) }, translate: (key) => key, global: { config: {} as Config, @@ -180,7 +170,8 @@ describe("bootstrapDirectory", () => { queryClient, }) await waitFor(() => externalResultCalls === 1) - await waitFor(() => store.external_result_question.ses_stale === undefined) + await waitFor(() => reconciled.length === 1) + expect(reconciled[0]).toEqual({ directory, entries: [] }) expect(warnings).toEqual([]) } finally { console.warn = originalWarn @@ -240,6 +231,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -266,6 +258,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -320,6 +313,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -412,6 +406,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -464,6 +459,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -520,6 +516,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -574,6 +571,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -633,6 +631,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key) => key, global: { config: {} as Config, @@ -707,6 +706,7 @@ describe("bootstrapDirectory", () => { setStore, vcsCache: createVcsCache(), loadSessions: () => undefined, + pendingQuestions: { reconcile() {} }, translate: (key: string) => key, global: { config: {} as Config, @@ -769,9 +769,9 @@ describe("hydratePendingExternalResults", () => { }, } as any - test("writes session, message, and part entries for a child agent's pending question", () => { + test("writes session, message, and part entries and returns the active question", () => { const [store, setStore] = createStore(createState()) - hydratePendingExternalResults({ + const active = hydratePendingExternalResults({ store, setStore, entries: [{ session: childSession, message: childMessage, part: childPart }], @@ -779,18 +779,7 @@ describe("hydratePendingExternalResults", () => { expect(store.session.map((s) => s.id)).toEqual(["ses_child"]) expect(store.message.ses_child?.map((m) => m.id)).toEqual(["msg_child"]) expect(store.part.msg_child?.map((p) => p.id)).toEqual(["part_child"]) - expect(store.external_result_question.ses_child?.[0]).toMatchObject({ - id: "msg_child:call_child", - sessionID: "ses_child", - messageID: "msg_child", - callID: "call_child", - partID: "part_child", - }) - }) - - test("prunes indexed pending questions that are absent from the pending hydrate snapshot", () => { - const [store, setStore] = createStore(createState()) - setStore("external_result_question", "ses_child", [ + expect(active).toEqual([ { id: "msg_child:call_child", sessionID: "ses_child", @@ -800,66 +789,36 @@ describe("hydratePendingExternalResults", () => { partID: "part_child", }, ]) - hydratePendingExternalResults({ - store, - setStore, - entries: [], - pruneQuestionIDs: new Set(["msg_child:call_child"]), - }) - expect(store.external_result_question.ses_child).toBeUndefined() }) - test("removes pruned ready question parts so fallback traversal cannot reopen the dock", () => { + test("removes pruned ready question parts so the part-derived dock stops showing them", () => { const [store, setStore] = createStore(createState()) setStore("message", "ses_child", [childMessage]) setStore("part", "msg_child", [childPart]) - setStore("external_result_question", "ses_child", [ - { - id: "msg_child:call_child", - sessionID: "ses_child", - questions: [{ header: "h", question: "q?", options: [] }], - messageID: "msg_child", - callID: "call_child", - partID: "part_child", - }, - ]) - hydratePendingExternalResults({ + const active = hydratePendingExternalResults({ store, setStore, entries: [], - pruneQuestionIDs: new Set(["msg_child:call_child"]), + pruneCandidateIDs: new Set(["msg_child:call_child"]), }) - expect(store.external_result_question.ses_child).toBeUndefined() + expect(active).toEqual([]) expect(store.part.msg_child).toBeUndefined() }) - test("does not prune questions added after the pending hydrate request snapshot", () => { + test("does not prune ready question parts that arrived after the request snapshot", () => { const [store, setStore] = createStore(createState()) - setStore("external_result_question", "ses_child", [ - { - id: "msg_old:call_old", - sessionID: "ses_child", - questions: [{ header: "h", question: "old?", options: [] }], - messageID: "msg_old", - callID: "call_old", - partID: "part_old", - }, - { - id: "msg_new:call_new", - sessionID: "ses_child", - questions: [{ header: "h", question: "new?", options: [] }], - messageID: "msg_new", - callID: "call_new", - partID: "part_new", - }, - ]) + const oldPart = { ...childPart, id: "part_old", callID: "call_old", messageID: "msg_old" } + const newPart = { ...childPart, id: "part_new", callID: "call_new", messageID: "msg_new" } + setStore("part", "msg_old", [oldPart]) + setStore("part", "msg_new", [newPart]) hydratePendingExternalResults({ store, setStore, entries: [], - pruneQuestionIDs: new Set(["msg_old:call_old"]), + pruneCandidateIDs: new Set(["msg_old:call_old"]), }) - expect(store.external_result_question.ses_child?.map((question) => question.id)).toEqual(["msg_new:call_new"]) + expect(store.part.msg_old).toBeUndefined() + expect(store.part.msg_new?.map((p) => p.id)).toEqual(["part_new"]) }) test("merges into existing session list and existing message list without duplicating", () => { @@ -902,15 +861,15 @@ describe("hydratePendingExternalResults", () => { state: { ...childPart.state, status: "completed" }, } as any setStore("part", "msg_child", [terminalPart]) - hydratePendingExternalResults({ + const active = hydratePendingExternalResults({ store, setStore, entries: [{ session: childSession, message: childMessage, part: childPart }], - pruneQuestionIDs: new Set(["msg_child:call_child"]), + pruneCandidateIDs: new Set(["msg_child:call_child"]), }) + expect(active).toEqual([]) expect(store.session.map((s) => s.id)).toEqual(["ses_child"]) expect(store.message.ses_child?.map((m) => m.id)).toEqual(["msg_child"]) - expect(store.external_result_question.ses_child).toBeUndefined() const updated = store.part.msg_child?.[0] as any expect(updated?.state?.status).toBe("completed") }) diff --git a/packages/app/src/context/global-sync/bootstrap.ts b/packages/app/src/context/global-sync/bootstrap.ts index 7f04e508c..3d9a154b0 100644 --- a/packages/app/src/context/global-sync/bootstrap.ts +++ b/packages/app/src/context/global-sync/bootstrap.ts @@ -7,10 +7,8 @@ import type { Path, PermissionRequest, Project, - ProviderAuthResponse, ProviderListResponse, Session, - TodoSnapshot, } from "@opencode-ai/sdk/v2/client" import { showToast } from "@opencode-ai/ui/toast" import { getFilename } from "@opencode-ai/util/path" @@ -19,28 +17,11 @@ import { batch } from "solid-js" import { produce, reconcile, type SetStoreFunction, type Store } from "solid-js/store" import type { State, VcsCache } from "./types" import { mergeAutomationList } from "./automation-store" -import { - pendingExternalResultQuestionFromPart, - type PendingExternalResultQuestion, - upsertPendingExternalResultQuestion, -} from "./external-result-question" +import { pendingExternalResultQuestionFromPart, type PendingExternalResultQuestion } from "./external-result-question" import { cmp, normalizeAgentList, normalizeProviderList } from "./utils" import { formatServerError } from "@/utils/server-errors" import { QueryClient, queryOptions } from "@tanstack/solid-query" -import { loadSessionsQuery } from "../global-sync" - -type GlobalStore = { - ready: boolean - path: Path - project: Project[] - session_todo: { - [sessionID: string]: TodoSnapshot - } - provider: ProviderListResponse - provider_auth: ProviderAuthResponse - config: Config - reload: undefined | "pending" | "complete" -} +import { loadSessionsQuery, type GlobalStore } from "../global-sync" function waitForPaint() { return new Promise((resolve) => { @@ -238,19 +219,27 @@ function filterGroupedByWarmSessions(grouped: Record, result: { return filtered } -// Hydrate session/message/part trios returned by GET /external-result. The -// dock walks `sync.data.session` + `sync.data.message[child]` + `part[msg]` -// to surface a pending question on a parent route. SSE message.part.updated -// is intentionally not in the replay buffer (high-volume), so a reload after -// the SSE cursor expires loses the dock without this hydrate. +// Hydrate session/message/part trios returned by GET /external-result so the +// dock — which renders purely from parts — recovers after a reload (SSE +// message.part.updated is intentionally not in the replay buffer). Returns the +// questions the server still lists as pending, for the caller to reconcile into +// the global condition index. +// +// `pruneCandidateIDs` is the set of running-ready question part identities known +// locally *before* the fetch. Any of those the server no longer lists is a +// question answered while the app was away whose terminal event was missed; its +// stale local part is dropped here so the part-derived dock stops showing it. +// Scoping the prune to the pre-fetch snapshot keeps a question that arrived +// during the fetch from being pruned by a slightly older server view. export function hydratePendingExternalResults(input: { store: Store setStore: SetStoreFunction entries: ReadonlyArray<{ session: Session; message: Message; part: Part }> - pruneQuestionIDs?: ReadonlySet -}) { + pruneCandidateIDs?: ReadonlySet +}): PendingExternalResultQuestion[] { + const active: PendingExternalResultQuestion[] = [] batch(() => { - const activeQuestionIDs = new Set() + const activeIDs = new Set() for (const entry of input.entries) { const session = entry.session const message = entry.message @@ -265,10 +254,8 @@ export function hydratePendingExternalResults(input: { localPart.tool === "question" && localPart.state.status !== "running" if (pendingQuestion && !localTerminalQuestion) { - activeQuestionIDs.add(pendingQuestion.id) - input.setStore("external_result_question", pendingQuestion.sessionID, (list) => - upsertPendingExternalResultQuestion(list, pendingQuestion), - ) + activeIDs.add(pendingQuestion.id) + active.push(pendingQuestion) } const messages = input.store.message[session.id] @@ -308,51 +295,44 @@ export function hydratePendingExternalResults(input: { } } } - if (input.pruneQuestionIDs?.size) { + if (input.pruneCandidateIDs?.size) { input.setStore( produce((draft) => { - const prunedQuestions: PendingExternalResultQuestion[] = [] - for (const sessionID of Object.keys(draft.external_result_question)) { - const questions = draft.external_result_question[sessionID] - if (!questions) { - delete draft.external_result_question[sessionID] - continue - } - const next: PendingExternalResultQuestion[] = [] - for (const question of questions) { - if (input.pruneQuestionIDs!.has(question.id) && !activeQuestionIDs.has(question.id)) { - prunedQuestions.push(question) - continue - } - next.push(question) - } - if (next.length > 0) draft.external_result_question[sessionID] = next - else delete draft.external_result_question[sessionID] - } - for (const question of prunedQuestions) { - const parts = draft.part[question.messageID] + for (const messageID of Object.keys(draft.part)) { + const parts = draft.part[messageID] if (!parts) continue const next = parts.filter((part) => { - if (part.id !== question.partID) return true if (part.type !== "tool" || part.tool !== "question") return true - if (part.callID !== question.callID) return true if (part.state.status !== "running") return true - return part.state.metadata?.externalResultReady !== true + if (part.state.metadata?.externalResultReady !== true) return true + const id = `${part.messageID}:${part.callID}` + if (!input.pruneCandidateIDs!.has(id)) return true + return activeIDs.has(id) }) - if (next.length > 0) draft.part[question.messageID] = next - else delete draft.part[question.messageID] + if (next.length === parts.length) continue + if (next.length > 0) draft.part[messageID] = next + else delete draft.part[messageID] } }), ) } }) + return active } -function snapshotExternalResultQuestionIDs(store: Store) { +// Identities (messageID:callID) of running-ready question parts in the local +// cache, captured before a GET /external-result fetch so the reconcile can tell +// an answered-while-away question (drop its stale part) from one that arrived +// mid-fetch (keep). +function snapshotRunningQuestionPartIDs(store: Store) { const ids = new Set() - for (const list of Object.values(store.external_result_question)) { - if (!list) continue - for (const question of list) ids.add(question.id) + for (const parts of Object.values(store.part)) { + for (const part of parts ?? []) { + if (part.type !== "tool" || part.tool !== "question") continue + if (part.state.status !== "running") continue + if (part.state.metadata?.externalResultReady !== true) continue + ids.add(`${part.messageID}:${part.callID}`) + } } return ids } @@ -380,6 +360,7 @@ export async function bootstrapDirectory(input: { provider: ProviderListResponse } queryClient: QueryClient + pendingQuestions: { reconcile: (directory: string, entries: PendingExternalResultQuestion[]) => void } }) { const loading = input.store.status !== "complete" const seededProject = projectID(input.directory, input.global.project) @@ -540,19 +521,19 @@ export async function bootstrapDirectory(input: { ), () => retry(() => { - const pruneQuestionIDs = snapshotExternalResultQuestionIDs(input.store) + const pruneCandidateIDs = snapshotRunningQuestionPartIDs(input.store) return input.sdk.externalResult.list().then((x) => { const entries = (x.data ?? []).filter( (entry): entry is { session: Session; message: Message; part: Part } => !!entry?.session?.id && !!entry.message?.id && !!entry.part?.id, ) - if (entries.length === 0 && pruneQuestionIDs.size === 0) return - hydratePendingExternalResults({ + const active = hydratePendingExternalResults({ store: input.store, setStore: input.setStore, entries, - pruneQuestionIDs, + pruneCandidateIDs, }) + input.pendingQuestions.reconcile(input.directory, active) }) }).catch((err) => { // Hydrate is best-effort: a transient failure should not surface diff --git a/packages/app/src/context/global-sync/child-store.ts b/packages/app/src/context/global-sync/child-store.ts index 289131c3a..cc3caf630 100644 --- a/packages/app/src/context/global-sync/child-store.ts +++ b/packages/app/src/context/global-sync/child-store.ts @@ -192,7 +192,6 @@ export function createChildStoreManager(input: { turn_change_aggregate: {}, todo: {}, permission: {}, - external_result_question: {}, mcp_ready: false, mcp: {}, lsp_ready: false, diff --git a/packages/app/src/context/global-sync/event-reducer.test.ts b/packages/app/src/context/global-sync/event-reducer.test.ts index efcdec141..8b05810b6 100644 --- a/packages/app/src/context/global-sync/event-reducer.test.ts +++ b/packages/app/src/context/global-sync/event-reducer.test.ts @@ -68,28 +68,6 @@ const todoToolPart = (id: string, sessionID: string, messageID: string, metadata }, }) as Part -const questionToolPart = ( - id: string, - sessionID: string, - messageID: string, - status: "running" | "completed" | "error" = "running", -) => - ({ - id, - sessionID, - messageID, - type: "tool", - callID: `call_${id}`, - tool: "question", - state: { - status, - input: { questions: [{ header: "Question", question: "Continue?", options: [] }] }, - title: "", - metadata: { externalResultReady: true }, - time: { start: 1 }, - }, - }) as Part - const permissionRequest = (id: string, sessionID: string, title = id) => ({ id, @@ -144,7 +122,6 @@ const baseState = (input: Partial = {}) => turn_change_aggregate: {}, todo: {}, permission: {}, - external_result_question: {}, mcp: {}, lsp: [], vcs: undefined, @@ -363,18 +340,6 @@ describe("applyDirectoryEvent", () => { turn_change_aggregate: { ses_1: emptyAggregate("ses_1") }, todo: { ses_1: [] }, permission: { ses_1: [] }, - external_result_question: { - ses_1: [ - { - id: `${message.id}:call_1`, - sessionID: "ses_1", - questions: [{ question: "Continue?" }], - messageID: message.id, - callID: "call_1", - partID: "prt_1", - }, - ], - }, session_status: { ses_1: { type: "busy" } }, }), ) @@ -395,7 +360,6 @@ describe("applyDirectoryEvent", () => { expect(store.turn_change_aggregate.ses_1).toBeUndefined() expect(store.todo.ses_1).toBeUndefined() expect(store.permission.ses_1).toBeUndefined() - expect(store.external_result_question.ses_1).toBeUndefined() expect(store.session_status.ses_1).toBeUndefined() }) @@ -420,18 +384,6 @@ describe("applyDirectoryEvent", () => { turn_change_aggregate: { [item.info.id]: emptyAggregate(item.info.id) }, todo: { [item.info.id]: [] }, permission: { [item.info.id]: [] }, - external_result_question: { - [item.info.id]: [ - { - id: `${message.id}:call_1`, - sessionID: item.info.id, - questions: [{ question: "Continue?" }], - messageID: message.id, - callID: "call_1", - partID: "prt_1", - }, - ], - }, session_status: { [item.info.id]: { type: "busy" } }, }), ) @@ -452,7 +404,6 @@ describe("applyDirectoryEvent", () => { expect(store.turn_change_aggregate[item.info.id]).toBeUndefined() expect(store.todo[item.info.id]).toBeUndefined() expect(store.permission[item.info.id]).toBeUndefined() - expect(store.external_result_question[item.info.id]).toBeUndefined() expect(store.session_status[item.info.id]).toBeUndefined() } }) @@ -661,132 +612,6 @@ describe("applyDirectoryEvent", () => { expect(store.part[messageID]).toBeUndefined() }) - test("indexes ready question parts even when the owning message row is missing", () => { - const sessionID = "ses_1" - const messageID = "msg_missing" - const [store, setStore] = createStore(baseState()) - - applyDirectoryEvent({ - event: { - type: "message.part.updated", - properties: { part: questionToolPart("prt_question", sessionID, messageID) }, - }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - - expect(store.external_result_question[sessionID]?.[0]).toMatchObject({ - id: "msg_missing:call_prt_question", - sessionID, - messageID, - callID: "call_prt_question", - partID: "prt_question", - }) - }) - - test("clears indexed question blockers on terminal update and part removal", () => { - const sessionID = "ses_1" - const messageID = "msg_missing" - const [store, setStore] = createStore(baseState()) - const running = questionToolPart("prt_question", sessionID, messageID) - - applyDirectoryEvent({ - event: { type: "message.part.updated", properties: { part: running } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]?.length).toBe(1) - - applyDirectoryEvent({ - event: { - type: "message.part.updated", - properties: { part: questionToolPart("prt_question", sessionID, messageID, "error") }, - }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]).toBeUndefined() - - applyDirectoryEvent({ - event: { type: "message.part.updated", properties: { part: running } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - applyDirectoryEvent({ - event: { type: "message.part.removed", properties: { messageID, partID: "prt_question" } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]).toBeUndefined() - }) - - test("keeps sibling question blockers from the same message when one part settles", () => { - const sessionID = "ses_1" - const messageID = "msg_multi_question" - const [store, setStore] = createStore(baseState()) - const first = questionToolPart("prt_first", sessionID, messageID) - const second = questionToolPart("prt_second", sessionID, messageID) - - applyDirectoryEvent({ - event: { type: "message.part.updated", properties: { part: first } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - applyDirectoryEvent({ - event: { type: "message.part.updated", properties: { part: second } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]?.map((question) => question.partID)).toEqual([ - "prt_first", - "prt_second", - ]) - - applyDirectoryEvent({ - event: { - type: "message.part.updated", - properties: { part: questionToolPart("prt_first", sessionID, messageID, "completed") }, - }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]?.map((question) => question.partID)).toEqual(["prt_second"]) - - applyDirectoryEvent({ - event: { type: "message.part.removed", properties: { messageID, partID: "prt_second" } }, - store, - setStore, - push() {}, - directory: "/tmp", - loadLsp() {}, - }) - expect(store.external_result_question[sessionID]).toBeUndefined() - }) - test("completed live todowrite metadata writes canonical todo before part storage returns", () => { const sessionID = "ses_1" const messageID = "msg_1" diff --git a/packages/app/src/context/global-sync/event-reducer.ts b/packages/app/src/context/global-sync/event-reducer.ts index eef00b862..09f88aa1d 100644 --- a/packages/app/src/context/global-sync/event-reducer.ts +++ b/packages/app/src/context/global-sync/event-reducer.ts @@ -17,11 +17,6 @@ import type { State, VcsCache } from "./types" import { applyAutomationDefinition, applyAutomationRun, applyAutomationTombstone } from "./automation-store" import { trimSessions } from "./session-trim" import { dropSessionCaches } from "./session-cache" -import { - pendingExternalResultQuestionFromPart, - removePendingExternalResultQuestion, - upsertPendingExternalResultQuestion, -} from "./external-result-question" import { message as clean } from "@/utils/diffs" import type { createBlockerTerminalCache } from "./blocker-terminal-cache" import type { TodoHydrateCoordinator } from "./todo-hydrate-coordinator" @@ -124,7 +119,6 @@ export function cleanupDroppedSessionCaches( const stale = [ ...dropped, ...Object.keys(store.message), - ...Object.keys(store.external_result_question), ...Object.keys(store.turn_change_aggregate), ...Object.keys(store.todo), ...Object.keys(store.permission), @@ -320,13 +314,6 @@ export function applyDirectoryEvent(input: { if (result.found) messages.splice(result.index, 1) } delete draft.part[props.messageID] - for (const sessionID of Object.keys(draft.external_result_question)) { - const next = removePendingExternalResultQuestion(draft.external_result_question[sessionID], { - messageID: props.messageID, - }) - if (next) draft.external_result_question[sessionID] = next - else delete draft.external_result_question[sessionID] - } }), ) break @@ -345,27 +332,6 @@ export function applyDirectoryEvent(input: { }) if (accepted) input.setStore("todo", todo.sessionID, reconcile(todo.snapshot.todos, { key: "id" })) } - const pendingQuestion = pendingExternalResultQuestionFromPart(part) - if (pendingQuestion) { - input.setStore("external_result_question", pendingQuestion.sessionID, (list) => - upsertPendingExternalResultQuestion(list, pendingQuestion), - ) - } else if (part.type === "tool" && part.tool === "question") { - input.setStore( - "external_result_question", - produce((draft) => { - const sessionIDs = part.sessionID ? [part.sessionID] : Object.keys(draft) - for (const sessionID of sessionIDs) { - const next = removePendingExternalResultQuestion(draft[sessionID], { - messageID: part.messageID, - partID: part.id, - }) - if (next) draft[sessionID] = next - else delete draft[sessionID] - } - }), - ) - } const parts = input.store.part[part.messageID] if (!parts) { input.setStore("part", part.messageID, [part]) @@ -387,19 +353,6 @@ export function applyDirectoryEvent(input: { } case "message.part.removed": { const props = event.properties as { messageID: string; partID: string } - input.setStore( - "external_result_question", - produce((draft) => { - for (const sessionID of Object.keys(draft)) { - const next = removePendingExternalResultQuestion(draft[sessionID], { - messageID: props.messageID, - partID: props.partID, - }) - if (next) draft[sessionID] = next - else delete draft[sessionID] - } - }), - ) const parts = input.store.part[props.messageID] if (!parts) break const result = Binary.search(parts, props.partID, (p) => p.id) diff --git a/packages/app/src/context/global-sync/external-result-question.ts b/packages/app/src/context/global-sync/external-result-question.ts index 61416995f..fbb0107a7 100644 --- a/packages/app/src/context/global-sync/external-result-question.ts +++ b/packages/app/src/context/global-sync/external-result-question.ts @@ -34,30 +34,3 @@ export function pendingExternalResultQuestionFromPart(part: Part): PendingExtern partID: part.id, } } - -export function upsertPendingExternalResultQuestion( - list: PendingExternalResultQuestion[] | undefined, - next: PendingExternalResultQuestion, -) { - const current = list ?? [] - const index = current.findIndex((item) => item.id === next.id) - if (index === -1) return [...current, next].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) - const out = current.slice() - out[index] = next - return out -} - -export function removePendingExternalResultQuestion( - list: PendingExternalResultQuestion[] | undefined, - match: { id?: string; messageID?: string; partID?: string }, -) { - if (!list) return list - const next = list.filter((item) => { - const matches = - (!match.id || item.id === match.id) && - (!match.partID || item.partID === match.partID) && - (!match.messageID || item.messageID === match.messageID) - return !matches - }) - return next.length > 0 ? next : undefined -} diff --git a/packages/app/src/context/global-sync/pending-question-controller.test.ts b/packages/app/src/context/global-sync/pending-question-controller.test.ts new file mode 100644 index 000000000..d8f6d4b48 --- /dev/null +++ b/packages/app/src/context/global-sync/pending-question-controller.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, test } from "bun:test" +import type { Part } from "@opencode-ai/sdk/v2/client" +import { createPendingQuestionController, type PendingQuestionAlert } from "./pending-question-controller" +import type { PendingQuestion, PendingQuestionIndex } from "./pending-question-index" + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) + +const questionPart = (input: { + id: string + sessionID: string + messageID: string + callID: string + status?: "running" | "completed" | "error" +}): Part => + ({ + id: input.id, + type: "tool", + tool: "question", + sessionID: input.sessionID, + messageID: input.messageID, + callID: input.callID, + state: { + status: input.status ?? "running", + input: { questions: [{ question: "?" }] }, + title: "", + metadata: { externalResultReady: true }, + time: { start: 0 }, + }, + }) as Part + +const question = (input: { sessionID: string; messageID: string; callID: string }): PendingQuestion => ({ + id: `${input.messageID}:${input.callID}`, + sessionID: input.sessionID, + questions: [{ question: "?" }], + messageID: input.messageID, + callID: input.callID, + partID: `prt_${input.callID}`, +}) + +function setup(resolveParentID?: (directory: string, sessionID: string) => string | undefined | Promise) { + let index: PendingQuestionIndex = {} + const alerts: PendingQuestionAlert[] = [] + const parents: Record = {} + const controller = createPendingQuestionController({ + read: () => index, + write: (mutate) => mutate(index), + resolveParentID: resolveParentID ?? ((_directory, sessionID) => parents[sessionID]), + }) + controller.onAlert((event) => alerts.push(event)) + return { controller, getIndex: () => index, alerts, parents } +} + +const updated = (part: Part) => ({ type: "message.part.updated", properties: { part } }) as const + +describe("createPendingQuestionController applyEvent", () => { + test("a live question part adds the entry, resolves its root, and alerts once", async () => { + const { controller, getIndex, alerts, parents } = setup() + parents["child"] = "root" + + const part = questionPart({ id: "p1", sessionID: "child", messageID: "m1", callID: "c1" }) + controller.applyEvent("/dir", updated(part)) + await flush() + + expect(getIndex()["/dir"]["child"][0]).toMatchObject({ id: "m1:c1", rootSessionID: "root" }) + expect(alerts).toHaveLength(1) + expect(alerts[0]).toMatchObject({ directory: "/dir", askSessionID: "child", rootSessionID: "root" }) + + // A second update for the same identity is not a rising edge → no new alert. + controller.applyEvent("/dir", updated(part)) + await flush() + expect(alerts).toHaveLength(1) + }) + + test("attributes a root-level question to its own session", async () => { + const { controller, getIndex, alerts } = setup() + controller.applyEvent("/dir", updated(questionPart({ id: "p1", sessionID: "root", messageID: "m1", callID: "c1" }))) + await flush() + expect(getIndex()["/dir"]["root"][0].rootSessionID).toBe("root") + expect(alerts[0].rootSessionID).toBe("root") + }) + + test("a terminal question part retracts the entry", async () => { + const { controller, getIndex } = setup() + controller.applyEvent("/dir", updated(questionPart({ id: "p1", sessionID: "s1", messageID: "m1", callID: "c1" }))) + await flush() + expect(getIndex()["/dir"]["s1"]).toHaveLength(1) + + controller.applyEvent( + "/dir", + updated(questionPart({ id: "p1", sessionID: "s1", messageID: "m1", callID: "c1", status: "completed" })), + ) + expect(getIndex()["/dir"]).toBeUndefined() + }) + + test("message.part.removed, message.removed, session.deleted, and archive all retract", async () => { + for (const event of [ + { type: "message.part.removed", properties: { messageID: "m1", partID: "p1" } }, + { type: "message.removed", properties: { messageID: "m1" } }, + { type: "session.deleted", properties: { info: { id: "s1" } } }, + { type: "session.updated", properties: { info: { id: "s1", time: { archived: 10 } } } }, + ]) { + const { controller, getIndex } = setup() + controller.applyEvent("/dir", updated(questionPart({ id: "p1", sessionID: "s1", messageID: "m1", callID: "c1" }))) + await flush() + expect(getIndex()["/dir"]["s1"]).toHaveLength(1) + controller.applyEvent("/dir", event) + expect(getIndex()["/dir"]).toBeUndefined() + } + }) + + test("ignores events without properties", () => { + const { controller, getIndex } = setup() + expect(() => controller.applyEvent("/dir", { type: "message.part.updated" })).not.toThrow() + expect(getIndex()).toEqual({}) + }) + + test("a removal landing mid-walk drops the entry and suppresses its alert", async () => { + let release: ((id: string | undefined) => void) | undefined + const gate = new Promise((resolve) => { + release = resolve + }) + const { controller, getIndex, alerts } = setup(() => gate) + + controller.applyEvent("/dir", updated(questionPart({ id: "p1", sessionID: "child", messageID: "m1", callID: "c1" }))) + // Retract before the parent walk resolves. + controller.applyEvent("/dir", { type: "message.part.removed", properties: { messageID: "m1", partID: "p1" } }) + release?.(undefined) + await flush() + + expect(getIndex()["/dir"]).toBeUndefined() + expect(alerts).toEqual([]) + }) +}) + +describe("createPendingQuestionController reconcile", () => { + test("seeds entries and resolves their roots without firing an alert", async () => { + const { controller, getIndex, alerts, parents } = setup() + parents["child"] = "root" + + controller.reconcile("/dir", [question({ sessionID: "child", messageID: "m1", callID: "c1" })]) + await flush() + + expect(getIndex()["/dir"]["child"][0]).toMatchObject({ id: "m1:c1", rootSessionID: "root" }) + expect(alerts).toEqual([]) + }) + + test("an empty snapshot clears the directory", async () => { + const { controller, getIndex } = setup() + controller.applyEvent("/dir", updated(questionPart({ id: "p1", sessionID: "s1", messageID: "m1", callID: "c1" }))) + await flush() + expect(getIndex()["/dir"]).toBeDefined() + + controller.reconcile("/dir", []) + expect(getIndex()["/dir"]).toBeUndefined() + }) +}) diff --git a/packages/app/src/context/global-sync/pending-question-controller.ts b/packages/app/src/context/global-sync/pending-question-controller.ts new file mode 100644 index 000000000..222e3432c --- /dev/null +++ b/packages/app/src/context/global-sync/pending-question-controller.ts @@ -0,0 +1,154 @@ +// Owns the lifecycle of the global pending-question index: it ingests the SSE +// stream for every directory (so background projects with no child store are +// covered), reconciles the authoritative GET /external-result snapshot on +// bootstrap / reconnect, resolves each question's root session once, and emits a +// rising-edge alert for live arrivals only. The dock and sidebar render from +// child-store parts; this controller feeds the cross-project signals (Dock +// badge, session-trim preserve, OS alert) that parts cannot. + +import type { Part, Session } from "@opencode-ai/sdk/v2/client" +import { + type PendingQuestion, + type PendingQuestionIndex, + pendingQuestionFromPart, + reconcileDirectoryPending, + removePendingQuestions, + setPendingQuestionRoot, + upsertPendingQuestion, +} from "./pending-question-index" + +export type PendingQuestionAlert = { + directory: string + askSessionID: string + rootSessionID: string + question: PendingQuestion +} + +export function createPendingQuestionController(deps: { + read: () => PendingQuestionIndex + write: (mutate: (index: PendingQuestionIndex) => void) => void + // Walk one step up the session tree. Returns from the in-memory child store + // when the project is open, falling back to the network for an unbootstrapped + // background project (so async). + resolveParentID: (directory: string, sessionID: string) => string | undefined | Promise +}) { + let alert: ((event: PendingQuestionAlert) => void) | undefined + const resolving = new Set() + + const stillPending = (directory: string, sessionID: string, id: string) => + deps.read()[directory]?.[sessionID]?.some((question) => question.id === id) ?? false + + const resolveRoot = async (directory: string, sessionID: string) => { + const seen = new Set() + let current = sessionID + while (!seen.has(current)) { + seen.add(current) + const parent = await deps.resolveParentID(directory, current) + if (!parent) break + current = parent + } + return current + } + + // Resolve root attribution once per identity, then — if the question is still + // pending after the (possibly networked) walk — record the root and, for a + // live SSE arrival, fire the one-shot alert. A reset / removal that lands + // mid-walk drops the entry, so `stillPending` re-checks before writing. + // Hydrate calls with live=false: a reload must not re-nag for questions that + // were already pending before it. + const attribute = (directory: string, question: PendingQuestion, live: boolean) => { + const key = `${directory} ${question.id}` + if (resolving.has(key)) return + resolving.add(key) + void Promise.resolve(resolveRoot(directory, question.sessionID)) + .then((rootSessionID) => { + if (!stillPending(directory, question.sessionID, question.id)) return + deps.write((index) => setPendingQuestionRoot(index, directory, question.sessionID, question.id, rootSessionID)) + if (live) alert?.({ directory, askSessionID: question.sessionID, rootSessionID, question }) + }) + .catch(() => {}) + .finally(() => resolving.delete(key)) + } + + // Maintain the index from one directory event. Called for every directory + // (attached or detached) with the raw event directory, exactly once. + const applyEvent = (directory: string, event: { type: string; properties?: unknown }) => { + if (!event.properties || typeof event.properties !== "object") return + switch (event.type) { + case "message.part.updated": { + const part = (event.properties as { part: Part }).part + const pending = pendingQuestionFromPart(part) + if (pending) { + let added = false + deps.write((index) => { + added = upsertPendingQuestion(index, directory, pending) + }) + if (added) attribute(directory, pending, true) + return + } + // A `question` part that is no longer running-ready (terminal / reset) + // retracts its entry. + if (part.type === "tool" && part.tool === "question" && part.sessionID) { + deps.write((index) => + removePendingQuestions(index, { + directory, + sessionID: part.sessionID, + messageID: part.messageID, + partID: part.id, + }), + ) + } + return + } + case "message.part.removed": { + const props = event.properties as { messageID: string; partID: string } + deps.write((index) => removePendingQuestions(index, { directory, messageID: props.messageID, partID: props.partID })) + return + } + case "message.removed": { + const props = event.properties as { messageID: string } + deps.write((index) => removePendingQuestions(index, { directory, messageID: props.messageID })) + return + } + case "session.deleted": { + const info = (event.properties as { info?: Session }).info + if (info?.id) deps.write((index) => removePendingQuestions(index, { directory, sessionID: info.id })) + return + } + case "session.updated": { + const info = (event.properties as { info?: Session }).info + if (info?.id && info.time?.archived) { + deps.write((index) => removePendingQuestions(index, { directory, sessionID: info.id })) + } + return + } + } + } + + // Apply the authoritative GET /external-result snapshot for a directory: + // prune resolved questions, keep survivors, and resolve roots for any new + // entry (no alert — these are seeded, not freshly arrived). + const reconcile = (directory: string, entries: PendingQuestion[]) => { + deps.write((index) => { + reconcileDirectoryPending(index, directory, entries) + }) + for (const entry of entries) { + const current = deps.read()[directory]?.[entry.sessionID]?.find((question) => question.id === entry.id) + if (current && !current.rootSessionID) attribute(directory, current, false) + } + } + + return { + applyEvent, + reconcile, + // Register the side-effect that fires when a question first appears live. + // Returns an unsubscribe. The controller owns the index; the caller owns how + // to nag (sound / OS notification / Dock attention). + onAlert(handler: (event: PendingQuestionAlert) => void) { + alert = handler + return () => { + if (alert === handler) alert = undefined + } + }, + } +} diff --git a/packages/app/src/context/global-sync/pending-question-index.test.ts b/packages/app/src/context/global-sync/pending-question-index.test.ts new file mode 100644 index 000000000..2b8322b9e --- /dev/null +++ b/packages/app/src/context/global-sync/pending-question-index.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, test } from "bun:test" +import { + type PendingQuestion, + type PendingQuestionIndex, + pendingRootSessionIDs, + pendingSessionIDsForDirectory, + reconcileDirectoryPending, + removePendingQuestions, + setPendingQuestionRoot, + upsertPendingQuestion, +} from "./pending-question-index" + +function question(input: { + sessionID: string + messageID: string + callID: string + partID?: string + rootSessionID?: string +}): PendingQuestion { + return { + id: `${input.messageID}:${input.callID}`, + sessionID: input.sessionID, + questions: [{ question: "?" }], + messageID: input.messageID, + callID: input.callID, + partID: input.partID ?? `prt_${input.callID}`, + rootSessionID: input.rootSessionID, + } +} + +describe("upsertPendingQuestion", () => { + test("returns true only on the first insert of an identity", () => { + const index: PendingQuestionIndex = {} + const q = question({ sessionID: "s1", messageID: "m1", callID: "c1" }) + expect(upsertPendingQuestion(index, "/dir", q)).toBe(true) + expect(upsertPendingQuestion(index, "/dir", q)).toBe(false) + expect(index["/dir"]["s1"]).toHaveLength(1) + }) + + test("re-upsert keeps an already-resolved root", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1", rootSessionID: "root" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + expect(index["/dir"]["s1"][0].rootSessionID).toBe("root") + }) +}) + +describe("setPendingQuestionRoot", () => { + test("fills the root on an existing entry", () => { + const index: PendingQuestionIndex = {} + const q = question({ sessionID: "s1", messageID: "m1", callID: "c1" }) + upsertPendingQuestion(index, "/dir", q) + setPendingQuestionRoot(index, "/dir", "s1", q.id, "root") + expect(index["/dir"]["s1"][0].rootSessionID).toBe("root") + }) + + test("no-op when the entry retracted mid-walk", () => { + const index: PendingQuestionIndex = {} + expect(() => setPendingQuestionRoot(index, "/dir", "s1", "m1:c1", "root")).not.toThrow() + expect(index["/dir"]).toBeUndefined() + }) +}) + +describe("removePendingQuestions", () => { + test("by partID retracts one part, returns it", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1", partID: "p1" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m2", callID: "c2", partID: "p2" })) + const removed = removePendingQuestions(index, { directory: "/dir", partID: "p1" }) + expect(removed.map((q) => q.partID)).toEqual(["p1"]) + expect(index["/dir"]["s1"]).toHaveLength(1) + }) + + test("by messageID sweeps every question in the message", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c2" })) + removePendingQuestions(index, { directory: "/dir", messageID: "m1" }) + expect(index["/dir"]).toBeUndefined() + }) + + test("by directory + sessionID drops a deleted session", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s2", messageID: "m2", callID: "c2" })) + removePendingQuestions(index, { directory: "/dir", sessionID: "s1" }) + expect(index["/dir"]["s1"]).toBeUndefined() + expect(index["/dir"]["s2"]).toHaveLength(1) + }) + + test("without directory sweeps every project", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/a", question({ sessionID: "s1", messageID: "m1", callID: "c1", partID: "p" })) + upsertPendingQuestion(index, "/b", question({ sessionID: "s2", messageID: "m2", callID: "c2", partID: "p" })) + const removed = removePendingQuestions(index, { partID: "p" }) + expect(removed).toHaveLength(2) + expect(index).toEqual({}) + }) +}) + +describe("reconcileDirectoryPending", () => { + test("prunes resolved questions and keeps survivors", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m2", callID: "c2" })) + const dropped = reconcileDirectoryPending(index, "/dir", [question({ sessionID: "s1", messageID: "m1", callID: "c1" })]) + expect(dropped).toEqual(["m2:c2"]) + expect(index["/dir"]["s1"].map((q) => q.id)).toEqual(["m1:c1"]) + }) + + test("carries forward a resolved root across reconcile", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1", rootSessionID: "root" })) + reconcileDirectoryPending(index, "/dir", [question({ sessionID: "s1", messageID: "m1", callID: "c1" })]) + expect(index["/dir"]["s1"][0].rootSessionID).toBe("root") + }) + + test("empty snapshot clears the directory", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + reconcileDirectoryPending(index, "/dir", []) + expect(index["/dir"]).toBeUndefined() + }) +}) + +describe("derivations", () => { + test("pendingRootSessionIDs dedupes by root and falls back to ask session", () => { + const index: PendingQuestionIndex = {} + // two child agents under the same root → one badge unit + upsertPendingQuestion(index, "/dir", question({ sessionID: "child-a", messageID: "m1", callID: "c1", rootSessionID: "root" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "child-b", messageID: "m2", callID: "c2", rootSessionID: "root" })) + // unresolved → counts under its own ask session + upsertPendingQuestion(index, "/other", question({ sessionID: "lonely", messageID: "m3", callID: "c3" })) + expect(pendingRootSessionIDs(index)).toEqual(new Set(["root", "lonely"])) + }) + + test("pendingSessionIDsForDirectory lists asking sessions for trim preserve", () => { + const index: PendingQuestionIndex = {} + upsertPendingQuestion(index, "/dir", question({ sessionID: "s1", messageID: "m1", callID: "c1" })) + upsertPendingQuestion(index, "/dir", question({ sessionID: "s2", messageID: "m2", callID: "c2" })) + expect(pendingSessionIDsForDirectory(index, "/dir")).toEqual(new Set(["s1", "s2"])) + expect(pendingSessionIDsForDirectory(index, "/missing")).toEqual(new Set()) + }) +}) diff --git a/packages/app/src/context/global-sync/pending-question-index.ts b/packages/app/src/context/global-sync/pending-question-index.ts new file mode 100644 index 000000000..9f83f67d6 --- /dev/null +++ b/packages/app/src/context/global-sync/pending-question-index.ts @@ -0,0 +1,175 @@ +// The single source of truth for "which question tool calls are currently +// waiting on the user", projected across every directory the global event +// stream touches — including background projects that were never bootstrapped +// and so have no child store. It is a small live condition index, not a log: +// entries appear when a `question` part flips `externalResultReady` and retract +// on every removal path. The dock / sidebar "asking" pip render from child-store +// parts (the authoritative renderable truth for an open session); this index +// exists for the cross-project signals that parts cannot serve — the Dock badge +// count, session-trim preservation, and the rising-edge OS alert. +// +// Identity is (directory, askSessionID, messageID, callID): the same identity +// the server registry and POST /session/:id/tool/respond use. `partID` rides +// along only so a `message.part.removed` (which carries no callID) can retract. + +import type { Part } from "@opencode-ai/sdk/v2/client" +import { + pendingExternalResultQuestionFromPart, + type PendingExternalResultQuestion, +} from "./external-result-question" + +// One pending question keyed by its asking identity, plus the resolved root +// session it should be attributed to. `rootSessionID` is filled asynchronously +// at ingestion (a child agent's question is answered from — and badged on — its +// root session); it stays undefined until the walk resolves, and badge/preserve +// derivations fall back to `sessionID` so an unresolved entry still counts. +export type PendingQuestion = PendingExternalResultQuestion & { rootSessionID?: string } + +// directory -> askSessionID -> questions owned by that session +export type PendingQuestionIndex = { + [directory: string]: { [sessionID: string]: PendingQuestion[] } +} + +export function pendingQuestionFromPart(part: Part): PendingExternalResultQuestion | undefined { + return pendingExternalResultQuestionFromPart(part) +} + +// Upsert one question under (directory, sessionID). Returns true only when the +// (messageID:callID) identity is newly added — the rising-edge signal the OS +// alert keys off, so a stream of `message.part.updated` for the same call +// alerts exactly once. Preserves an already-resolved `rootSessionID` when the +// same identity is re-upserted (e.g. a later part update) so a resolved +// attribution is not dropped back to unresolved. +export function upsertPendingQuestion( + index: PendingQuestionIndex, + directory: string, + question: PendingQuestion, +): boolean { + const bySession = index[directory] ?? (index[directory] = {}) + const list = bySession[question.sessionID] ?? [] + const at = list.findIndex((item) => item.id === question.id) + if (at === -1) { + bySession[question.sessionID] = [...list, question].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + return true + } + const next = list.slice() + next[at] = { ...question, rootSessionID: question.rootSessionID ?? list[at].rootSessionID } + bySession[question.sessionID] = next + return false +} + +// Set the resolved root on an existing entry (post async walk). No-op if the +// entry retracted while the walk was in flight. +export function setPendingQuestionRoot( + index: PendingQuestionIndex, + directory: string, + sessionID: string, + id: string, + rootSessionID: string, +): void { + const list = index[directory]?.[sessionID] + if (!list) return + const at = list.findIndex((item) => item.id === id) + if (at === -1) return + const next = list.slice() + next[at] = { ...next[at], rootSessionID } + index[directory][sessionID] = next +} + +type RemoveMatch = { + directory?: string + sessionID?: string + messageID?: string + partID?: string +} + +// Retract every entry matching the (optional) fields. A bare `directory` +// sweeps the whole project; `directory + sessionID` a deleted/archived session; +// `messageID` a removed message; `partID` a removed part. Returns the removed +// entries so the caller can cancel any in-flight root resolution for them. +export function removePendingQuestions(index: PendingQuestionIndex, match: RemoveMatch): PendingQuestion[] { + const removed: PendingQuestion[] = [] + const directories = match.directory ? [match.directory] : Object.keys(index) + for (const directory of directories) { + const bySession = index[directory] + if (!bySession) continue + const sessionIDs = match.sessionID ? [match.sessionID] : Object.keys(bySession) + for (const sessionID of sessionIDs) { + const list = bySession[sessionID] + if (!list) continue + const kept: PendingQuestion[] = [] + for (const question of list) { + const hit = + (match.messageID === undefined || question.messageID === match.messageID) && + (match.partID === undefined || question.partID === match.partID) + if (hit) removed.push(question) + else kept.push(question) + } + if (kept.length === list.length) continue + if (kept.length > 0) bySession[sessionID] = kept + else delete bySession[sessionID] + } + if (Object.keys(bySession).length === 0) delete index[directory] + } + return removed +} + +// Replace a directory's whole pending set with the authoritative snapshot from +// GET /external-result (hydrate / reconnect). Carries forward an already +// resolved `rootSessionID` for identities that survive, so a reconcile does not +// re-trigger a root walk for questions that were already attributed. Returns +// the identities that were dropped (resolved while the app was away) so the +// caller can release their resolution state. +export function reconcileDirectoryPending( + index: PendingQuestionIndex, + directory: string, + next: PendingQuestion[], +): string[] { + const previous = index[directory] ?? {} + const priorRoot = new Map() + for (const list of Object.values(previous)) { + for (const question of list ?? []) { + if (question.rootSessionID) priorRoot.set(question.id, question.rootSessionID) + } + } + const keptIDs = new Set() + const bySession: { [sessionID: string]: PendingQuestion[] } = {} + for (const question of next) { + keptIDs.add(question.id) + const merged = { ...question, rootSessionID: question.rootSessionID ?? priorRoot.get(question.id) } + const list = bySession[question.sessionID] ?? (bySession[question.sessionID] = []) + list.push(merged) + } + for (const list of Object.values(bySession)) { + list.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + } + const dropped: string[] = [] + for (const id of priorRoot.keys()) if (!keptIDs.has(id)) dropped.push(id) + for (const list of Object.values(previous)) { + for (const question of list ?? []) if (!keptIDs.has(question.id) && !priorRoot.has(question.id)) dropped.push(question.id) + } + if (next.length > 0) index[directory] = bySession + else delete index[directory] + return dropped +} + +// Distinct root sessions with a pending question, across all projects. This is +// the Dock badge's question contribution: one root session waiting on the user +// counts once, regardless of how many child agents under it are asking. +// Unresolved entries fall back to their asking session so they still count. +export function pendingRootSessionIDs(index: PendingQuestionIndex): Set { + const roots = new Set() + for (const bySession of Object.values(index)) { + for (const list of Object.values(bySession)) { + for (const question of list ?? []) roots.add(question.rootSessionID ?? question.sessionID) + } + } + return roots +} + +// The asking sessions in a directory that still hold a pending question — fed +// to session-trim so a child agent waiting on the user is never trimmed out of +// the session list (which would drop its parts and collapse the dock). +export function pendingSessionIDsForDirectory(index: PendingQuestionIndex, directory: string): Set { + return new Set(Object.keys(index[directory] ?? {})) +} diff --git a/packages/app/src/context/global-sync/session-cache.test.ts b/packages/app/src/context/global-sync/session-cache.test.ts index fe729b540..2d9e9be83 100644 --- a/packages/app/src/context/global-sync/session-cache.test.ts +++ b/packages/app/src/context/global-sync/session-cache.test.ts @@ -7,7 +7,6 @@ import type { SessionStatus, Todo, } from "@opencode-ai/sdk/v2/client" -import type { PendingExternalResultQuestion } from "./external-result-question" import { dropSessionCaches, pickSessionCacheEvictions } from "./session-cache" const msg = (id: string, sessionID: string) => @@ -36,32 +35,11 @@ type CacheShape = { message: Record part: Record permission: Record - external_result_question: Record } const emptyAggregate = (sessionID: string): SessionDiffResponse => ({ kind: "empty", sessionID }) describe("app session cache", () => { - test("dropSessionCaches tolerates legacy cache shape without external_result_question", () => { - const legacyStore = { - session_status: { ses_1: { type: "busy" } as SessionStatus }, - turn_change_aggregate: { ses_1: emptyAggregate("ses_1") }, - todo: { ses_1: [] as Todo[] }, - message: { ses_1: [msg("msg_1", "ses_1")] }, - part: { msg_1: [part("prt_1", "ses_1", "msg_1")] }, - permission: { ses_1: [] as PermissionRequest[] }, - } as Omit - const store = legacyStore as unknown as CacheShape - - expect(() => dropSessionCaches(store, ["ses_1"])).not.toThrow() - expect(store.message.ses_1).toBeUndefined() - expect(store.part.msg_1).toBeUndefined() - expect(store.todo.ses_1).toBeUndefined() - expect(store.turn_change_aggregate.ses_1).toBeUndefined() - expect(store.session_status.ses_1).toBeUndefined() - expect(store.permission.ses_1).toBeUndefined() - }) - test("dropSessionCaches clears orphaned parts without message rows", () => { const store: CacheShape = { session_status: { ses_1: { type: "busy" } as SessionStatus }, @@ -70,18 +48,6 @@ describe("app session cache", () => { message: {}, part: { msg_1: [part("prt_1", "ses_1", "msg_1")] }, permission: { ses_1: [] as PermissionRequest[] }, - external_result_question: { - ses_1: [ - { - id: "msg_1:call_1", - sessionID: "ses_1", - questions: [{ question: "Continue?" }], - messageID: "msg_1", - callID: "call_1", - partID: "prt_1", - }, - ], - }, } dropSessionCaches(store, ["ses_1"]) @@ -92,7 +58,6 @@ describe("app session cache", () => { expect(store.turn_change_aggregate.ses_1).toBeUndefined() expect(store.session_status.ses_1).toBeUndefined() expect(store.permission.ses_1).toBeUndefined() - expect(store.external_result_question.ses_1).toBeUndefined() }) test("dropSessionCaches clears message-backed parts", () => { @@ -104,7 +69,6 @@ describe("app session cache", () => { message: { ses_1: [m] }, part: { [m.id]: [part("prt_1", "ses_1", m.id)] }, permission: {}, - external_result_question: {}, } dropSessionCaches(store, ["ses_1"]) diff --git a/packages/app/src/context/global-sync/session-cache.ts b/packages/app/src/context/global-sync/session-cache.ts index df20cd461..fe9a1b167 100644 --- a/packages/app/src/context/global-sync/session-cache.ts +++ b/packages/app/src/context/global-sync/session-cache.ts @@ -6,7 +6,6 @@ import type { SessionStatus, Todo, } from "@opencode-ai/sdk/v2/client" -import type { PendingExternalResultQuestion } from "./external-result-question" export const SESSION_CACHE_LIMIT = 40 @@ -17,7 +16,6 @@ type SessionCache = { message: Record part: Record permission: Record - external_result_question?: Record } export function dropSessionCaches(store: SessionCache, sessionIDs: Iterable) { @@ -36,7 +34,6 @@ export function dropSessionCaches(store: SessionCache, sessionIDs: Iterable { permission: { "child-kept-by-permission": [{ id: "perm-1" } as PermissionRequest], }, - externalResultQuestion: { - "child-kept-by-question": [ - { - id: "msg_question:call_question", - sessionID: "child-kept-by-question", - questions: [{ question: "Continue?" }], - messageID: "msg_question", - callID: "call_question", - partID: "prt_question", - }, - ], - }, + preserveSessionIDs: new Set(["child-kept-by-question"]), now, }) diff --git a/packages/app/src/context/global-sync/session-trim.ts b/packages/app/src/context/global-sync/session-trim.ts index a8e2116da..350c292e3 100644 --- a/packages/app/src/context/global-sync/session-trim.ts +++ b/packages/app/src/context/global-sync/session-trim.ts @@ -1,5 +1,4 @@ import type { PermissionRequest, Session } from "@opencode-ai/sdk/v2/client" -import type { PendingExternalResultQuestion } from "./external-result-question" import { cmp, compareSessionsByCreated } from "./utils" import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "./types" @@ -36,7 +35,10 @@ export function trimSessions( options: { limit: number permission: Record - externalResultQuestion?: Record + // Asking sessions to keep regardless of recency: a child agent waiting on a + // pending question must stay in the list so its parts survive and the + // part-derived dock does not collapse. Fed from the global pending index. + preserveSessionIDs?: ReadonlySet now?: number }, ) { @@ -56,8 +58,7 @@ export function trimSessions( if (s.parentID && keepRootIds.has(s.parentID)) return true const perms = options.permission[s.id] ?? [] if (perms.length > 0) return true - const questions = options.externalResultQuestion?.[s.id] ?? [] - if (questions.length > 0) return true + if (options.preserveSessionIDs?.has(s.id)) return true return sessionUpdatedAt(s) > cutoff }) return [...keepRoots, ...keepChildren].sort((a, b) => cmp(a.id, b.id)) diff --git a/packages/app/src/context/global-sync/types.ts b/packages/app/src/context/global-sync/types.ts index 402b2b273..b7a968a0f 100644 --- a/packages/app/src/context/global-sync/types.ts +++ b/packages/app/src/context/global-sync/types.ts @@ -19,7 +19,6 @@ import type { } from "@opencode-ai/sdk/v2/client" import type { Accessor } from "solid-js" import type { SetStoreFunction, Store } from "solid-js/store" -import type { PendingExternalResultQuestion } from "./external-result-question" export type ProjectMeta = { name?: string @@ -62,9 +61,6 @@ export type State = { permission: { [sessionID: string]: PermissionRequest[] } - external_result_question: { - [sessionID: string]: PendingExternalResultQuestion[] - } mcp_ready: boolean mcp: { [name: string]: McpStatus diff --git a/packages/app/src/context/notification-derive.test.ts b/packages/app/src/context/notification-derive.test.ts index 92907fdae..439c18dd7 100644 --- a/packages/app/src/context/notification-derive.test.ts +++ b/packages/app/src/context/notification-derive.test.ts @@ -1,21 +1,59 @@ import { describe, expect, test } from "bun:test" -import { - partitionRetractedQuestions, - questionCallKey, - questionNotificationAction, - resolveAndAlertQuestion, - resolveRootSessionIDAsync, - unreadSessionCount, -} from "./notification-derive" - -describe("unreadSessionCount", () => { +import { badgeSessionCount, buildNotificationIndex, isLiveNotification } from "./notification-derive" +import type { Notification } from "./notification" + +describe("isLiveNotification", () => { + test("keeps turn-complete and error, drops legacy question", () => { + expect(isLiveNotification({ type: "turn-complete" })).toBe(true) + expect(isLiveNotification({ type: "error" })).toBe(true) + expect(isLiveNotification({ type: "question" })).toBe(false) + }) +}) + +describe("buildNotificationIndex", () => { + test("drops legacy persisted question entries so they never strand an unread dot", () => { + // Simulates a notification.v1 store written by an older build: an + // already-answered question persisted as type:"question", viewed:false. + const list = [ + { type: "question", session: "ses_q", directory: "/repo", viewed: false, time: 10 }, + { type: "turn-complete", session: "ses_done", directory: "/repo", viewed: false, time: 20 }, + ] as unknown as Notification[] + + const index = buildNotificationIndex(list) + + // The legacy question contributes nothing to session or project unread. + expect(index.session.unseenCount["ses_q"]).toBeUndefined() + expect(index.session.all["ses_q"]).toBeUndefined() + expect(index.project.unseen["/repo"]?.some((n) => n.type !== "turn-complete" && n.type !== "error")).toBeFalsy() + // The live turn-complete still counts. + expect(index.session.unseenCount["ses_done"]).toBe(1) + expect(index.project.unseenCount["/repo"]).toBe(1) + }) + + test("counts unseen turn-complete and error, flags error, skips viewed", () => { + const list = [ + { type: "turn-complete", session: "ses_a", directory: "/r", viewed: false, time: 1 }, + { type: "error", session: "ses_a", directory: "/r", viewed: false, time: 2 }, + { type: "turn-complete", session: "ses_b", directory: "/r", viewed: true, time: 3 }, + ] as unknown as Notification[] + + const index = buildNotificationIndex(list) + + expect(index.session.unseenCount["ses_a"]).toBe(2) + expect(index.session.unseenHasError["ses_a"]).toBe(true) + expect(index.session.unseenCount["ses_b"]).toBeUndefined() + expect(index.project.unseenCount["/r"]).toBe(2) + }) +}) + +describe("badgeSessionCount", () => { test("counts distinct unseen sessions, not the total notification count", () => { const notifications = [ { session: "ses_a", viewed: false, time: 10 }, { session: "ses_a", viewed: false, time: 11 }, { session: "ses_b", viewed: false, time: 12 }, ] - expect(unreadSessionCount(notifications)).toBe(2) + expect(badgeSessionCount(notifications, [])).toBe(2) }) test("excludes sessions whose notifications have all been viewed", () => { @@ -23,15 +61,15 @@ describe("unreadSessionCount", () => { { session: "ses_a", viewed: false, time: 10 }, { session: "ses_b", viewed: true, time: 11 }, ] - expect(unreadSessionCount(notifications)).toBe(1) + expect(badgeSessionCount(notifications, [])).toBe(1) }) test("ignores notifications with no session", () => { - expect(unreadSessionCount([{ viewed: false, time: 10 }])).toBe(0) + expect(badgeSessionCount([{ viewed: false, time: 10 }], [])).toBe(0) }) - test("is zero when nothing is unseen", () => { - expect(unreadSessionCount([])).toBe(0) + test("is zero when nothing is unseen and nothing is pending", () => { + expect(badgeSessionCount([], [])).toBe(0) }) test("ignores notifications created before the since cutoff", () => { @@ -41,191 +79,26 @@ describe("unreadSessionCount", () => { ] // Persisted backlog from a previous run (older timestamps) must not surface // on the Dock badge at launch; only this run's notifications count. - expect(unreadSessionCount(notifications, 10)).toBe(1) + expect(badgeSessionCount(notifications, [], 10)).toBe(1) }) test("counts notifications at exactly the since cutoff", () => { const notifications = [{ session: "ses_a", viewed: false, time: 10 }] - expect(unreadSessionCount(notifications, 10)).toBe(1) - }) -}) - -describe("resolveRootSessionIDAsync", () => { - // getParentID is injected so the same walk works whether the parent comes - // from the in-memory session list or an async network lookup (the latter is - // what kicks in when a background project's sessions were never bootstrapped). - const parentLookup = (chain: Record) => async (id: string) => chain[id] - - test("walks the parent chain to the root session", async () => { - const getParentID = parentLookup({ ses_leaf: "ses_child", ses_child: "ses_root", ses_root: undefined }) - expect(await resolveRootSessionIDAsync("ses_leaf", getParentID)).toBe("ses_root") - }) - - test("returns the session itself when it has no parent", async () => { - expect(await resolveRootSessionIDAsync("ses_root", async () => undefined)).toBe("ses_root") - }) - - test("returns the id unchanged when the parent lookup yields nothing", async () => { - expect(await resolveRootSessionIDAsync("ses_missing", async () => undefined)).toBe("ses_missing") - }) - - test("breaks parent cycles instead of looping forever", async () => { - const getParentID = parentLookup({ ses_a: "ses_b", ses_b: "ses_a" }) - expect(await resolveRootSessionIDAsync("ses_a", getParentID)).toBe("ses_a") - }) -}) - -describe("resolveAndAlertQuestion", () => { - test("alerts with the resolved root when the question is still pending", async () => { - let alerted: string | undefined - const root = await resolveAndAlertQuestion({ - resolveRoot: async () => "ses_root", - disposed: () => false, - isPending: () => true, - alert: (id) => { - alerted = id - }, - }) - expect(root).toBe("ses_root") - expect(alerted).toBe("ses_root") - }) - - test("skips the alert when the question is removed during root resolution", async () => { - // The dedupe claim is cleared (message.part.removed / terminal reset) while - // resolveRoot is still awaiting the network. The alert must not fire, or it - // would strand a stale unread dot / badge bump / Dock bounce for a question - // that no longer needs the user. - let pending = true - let resolveRoot: (id: string) => void = () => {} - const rootResolved = new Promise((resolve) => { - resolveRoot = resolve - }) - let alerted = false - const done = resolveAndAlertQuestion({ - resolveRoot: () => rootResolved, - disposed: () => false, - isPending: () => pending, - alert: () => { - alerted = true - }, - }) - pending = false // message.part.removed lands mid-await - resolveRoot("ses_root") - expect(await done).toBeUndefined() - expect(alerted).toBe(false) - }) - - test("skips the alert when the provider is disposed during root resolution", async () => { - let alerted = false - const root = await resolveAndAlertQuestion({ - resolveRoot: async () => "ses_root", - disposed: () => true, - isPending: () => true, - alert: () => { - alerted = true - }, - }) - expect(root).toBeUndefined() - expect(alerted).toBe(false) - }) -}) - -describe("partitionRetractedQuestions", () => { - const question = (id: string, ask: { sessionID: string; messageID: string; partID: string }) => ({ - type: "question" as const, - directory: "/repo", - session: "ses_root", - id, - ask, - }) - - test("retracts the question matching the removed part, keeps the rest", () => { - const target = question("a", { sessionID: "ses_child", messageID: "msg_1", partID: "prt_1" }) - const other = question("b", { sessionID: "ses_child", messageID: "msg_1", partID: "prt_2" }) - const event = { type: "turn-complete" as const, directory: "/repo", id: "c" } - const { kept, removed } = partitionRetractedQuestions([target, other, event], { - directory: "/repo", - sessionID: "ses_child", - partID: "prt_1", - }) - expect(removed).toEqual([target]) - expect(kept).toEqual([other, event]) - }) - - test("retracts every question in a message when the whole message is removed", () => { - const a = question("a", { sessionID: "ses_child", messageID: "msg_1", partID: "prt_1" }) - const b = question("b", { sessionID: "ses_child", messageID: "msg_1", partID: "prt_2" }) - const elsewhere = question("c", { sessionID: "ses_child", messageID: "msg_2", partID: "prt_3" }) - const { kept, removed } = partitionRetractedQuestions([a, b, elsewhere], { - directory: "/repo", - sessionID: "ses_child", - messageID: "msg_1", - }) - expect(removed).toEqual([a, b]) - expect(kept).toEqual([elsewhere]) - }) - - test("does not cross directory or session boundaries", () => { - const otherDir = { ...question("a", { sessionID: "ses_child", messageID: "msg_1", partID: "prt_1" }), directory: "/other" } - const otherSession = question("b", { sessionID: "ses_sibling", messageID: "msg_1", partID: "prt_1" }) - const { removed } = partitionRetractedQuestions([otherDir, otherSession], { - directory: "/repo", - sessionID: "ses_child", - partID: "prt_1", - }) - expect(removed).toEqual([]) - }) - - test("keeps legacy question notifications that have no ask identity", () => { - const legacy = { type: "question" as const, directory: "/repo", session: "ses_root", id: "a" } - const { kept, removed } = partitionRetractedQuestions([legacy], { - directory: "/repo", - sessionID: "ses_child", - partID: "prt_1", - }) - expect(removed).toEqual([]) - expect(kept).toEqual([legacy]) - }) -}) - -describe("questionCallKey", () => { - test("builds a stable dedupe key from directory, session, and part", () => { - expect(questionCallKey("/repo", "ses_1", "prt_1")).toBe("/repo:ses_1:prt_1") - }) -}) - -describe("questionNotificationAction", () => { - test("notifies only once the external question input is ready", () => { - expect( - questionNotificationAction({ - type: "tool", - tool: "question", - state: { status: "running", metadata: { externalResultReady: true } }, - }), - ).toBe("notify") + expect(badgeSessionCount(notifications, [], 10)).toBe(1) }) - test("ignores a running question that is not yet ready", () => { - expect( - questionNotificationAction({ - type: "tool", - tool: "question", - state: { status: "running", metadata: { externalResultReady: false } }, - }), - ).toBe("ignore") + test("adds pending question roots, which are never since-scoped", () => { + // ses_pending arrived before the cutoff but is a live condition → still badges. + const notifications = [{ session: "ses_event", viewed: false, time: 20 }] + expect(badgeSessionCount(notifications, ["ses_pending"], 10)).toBe(2) }) - test("resets the dedupe entry when the question part is no longer running", () => { - expect( - questionNotificationAction({ - type: "tool", - tool: "question", - state: { status: "completed", metadata: { externalResultReady: true } }, - }), - ).toBe("reset") + test("unions a session that is both unseen and pending into one unit", () => { + const notifications = [{ session: "ses_a", viewed: false, time: 20 }] + expect(badgeSessionCount(notifications, ["ses_a"], 10)).toBe(1) }) - test("ignores parts that are not the question tool", () => { - expect(questionNotificationAction({ type: "text" })).toBe("ignore") + test("counts a pending root even with no notifications at all", () => { + expect(badgeSessionCount([], ["ses_a", "ses_b"])).toBe(2) }) }) diff --git a/packages/app/src/context/notification-derive.ts b/packages/app/src/context/notification-derive.ts index f0529234d..1a70877d8 100644 --- a/packages/app/src/context/notification-derive.ts +++ b/packages/app/src/context/notification-derive.ts @@ -1,58 +1,104 @@ // Pure derivation helpers for the notification store. Kept separate from the -// reactive context so the badge count and question attribution logic can be -// unit-tested without rendering the provider. +// reactive context so the badge count and unread index can be unit-tested +// without rendering the provider. -import type { Part } from "@opencode-ai/sdk/v2/client" +import type { Notification } from "./notification" -type QuestionNotificationPart = Pick & { - tool?: string - state?: { - status?: string - metadata?: { - externalResultReady?: unknown - } +export type NotificationIndex = { + session: { + all: Record + unseen: Record + unseenCount: Record + unseenHasError: Record + } + project: { + all: Record + unseen: Record + unseenCount: Record + unseenHasError: Record } } -export function questionCallKey(directory: string, sessionID: string, partID: string) { - return `${directory}:${sessionID}:${partID}` +// A persisted entry we still model as an unread signal. Questions used to be +// persisted as `type:"question"` notifications; they are now a live condition +// tracked by the global pending-question index (see #1199). The persistence key +// is unchanged, so a `type:"question"` entry written by an older build can still +// be on disk after upgrade — drop it on load so an already-answered question can +// never strand a sidebar unread dot or Dock badge. New entries are only ever +// `turn-complete` / `error`, so this is purely a one-time migration filter. +export function isLiveNotification(notification: { type: string }): boolean { + return notification.type === "turn-complete" || notification.type === "error" } -/** - * Decide what a `message.part.updated` event means for a question notification. - * - * Question parts stream many updates; the external-result input controls only - * become usable once the engine flips `metadata.externalResultReady`. We notify - * exactly once on that transition, and `reset` clears the per-call dedupe entry - * when the part is no longer running (terminal updates may not be followed by a - * `message.part.removed`). - */ -export function questionNotificationAction(part: QuestionNotificationPart): "ignore" | "reset" | "notify" { - if (part.type !== "tool" || part.tool !== "question") return "ignore" - if (part.state?.status !== "running") return "reset" - if (part.state.metadata?.externalResultReady !== true) return "ignore" - return "notify" +export function createNotificationIndex(): NotificationIndex { + return { + session: { + all: {}, + unseen: {}, + unseenCount: {}, + unseenHasError: {}, + }, + project: { + all: {}, + unseen: {}, + unseenCount: {}, + unseenHasError: {}, + }, + } +} + +export function buildNotificationIndex(list: readonly Notification[]): NotificationIndex { + const index = createNotificationIndex() + + list.forEach((notification) => { + if (!isLiveNotification(notification)) return + + if (notification.session) { + const all = index.session.all[notification.session] ?? [] + index.session.all[notification.session] = [...all, notification] + if (!notification.viewed) { + const unseen = index.session.unseen[notification.session] ?? [] + index.session.unseen[notification.session] = [...unseen, notification] + index.session.unseenCount[notification.session] = unseen.length + 1 + if (notification.type === "error") index.session.unseenHasError[notification.session] = true + } + } + + if (notification.directory) { + const all = index.project.all[notification.directory] ?? [] + index.project.all[notification.directory] = [...all, notification] + if (!notification.viewed) { + const unseen = index.project.unseen[notification.directory] ?? [] + index.project.unseen[notification.directory] = [...unseen, notification] + index.project.unseenCount[notification.directory] = unseen.length + 1 + if (notification.type === "error") index.project.unseenHasError[notification.directory] = true + } + } + }) + + return index } /** - * Number of distinct sessions with unseen notifications created at or after - * `since`. + * Number of distinct sessions to badge on the Dock/taskbar. + * + * Counts *sessions* needing the user, not notifications: one session with three + * unseen notifications is a single unit, matching how the user reasons about + * "how many things need me". Two sources union by session id: * - * This is the Dock/taskbar badge number: it counts *sessions* waiting for the - * user, not the total notification count. One session with three unseen - * notifications still contributes a single unit, matching how the user reasons - * about "how many things need me". The `since` cutoff scopes the badge to the - * current app run — notifications persist across restarts to drive the sidebar, - * but a fresh launch should show zero on the Dock instead of resurfacing a - * stale backlog whose sessions the user may have long since dealt with (or that - * no longer exist). Derived straight from the notification list (the persisted - * source of truth) so a memo over it tracks reactively. + * - persisted turn-complete / error notifications created at or after `since`. + * The cutoff scopes them to the current app run so a fresh launch shows zero + * instead of resurfacing a stale backlog the user may have long dealt with. + * - `pendingRootSessionIDs`: root sessions with a live question awaiting the + * user right now. A question is a live condition (not a log), so these are + * never `since`-scoped — one still outstanding across a restart should badge. */ -export function unreadSessionCount( +export function badgeSessionCount( notifications: readonly { session?: string; viewed: boolean; time: number }[], + pendingRootSessionIDs: Iterable, since = 0, ): number { - const sessions = new Set() + const sessions = new Set(pendingRootSessionIDs) for (const notification of notifications) { if (!notification.viewed && notification.session && notification.time >= since) { sessions.add(notification.session) @@ -60,99 +106,3 @@ export function unreadSessionCount( } return sessions.size } - -/** - * Walk a session's parent chain to its root via an injected parent lookup. - * - * A child agent's question is surfaced on (and answered from) its root - * session's page, and only root sessions appear in the sidebar — so a question - * notification must attribute to the root, not the asking child. `getParentID` - * is async so the walk can fall back to a network lookup: the global event - * stream delivers a question even for a background project whose session list - * was never bootstrapped, where a purely in-memory walk would stop short and - * mis-attribute the notification to the child. Returns the input id when it has - * no parent, is unknown, or the chain cycles. - */ -export async function resolveRootSessionIDAsync( - sessionID: string, - getParentID: (id: string) => Promise, -): Promise { - const seen = new Set() - let current = sessionID - while (!seen.has(current)) { - seen.add(current) - const parent = await getParentID(current) - if (!parent) break - current = parent - } - return current -} - -/** - * Resolve a question's root session, then fire its alert — but only if the - * provider is still mounted and the question is still pending once the async - * resolution returns. - * - * `resolveRoot` may await the network (a background project whose sessions were - * never bootstrapped), which yields the event loop. In that gap a - * `message.part.removed` or a terminal `reset` update for the same question can - * land and clear its dedupe claim — the question is already answered or gone. - * Re-checking `isPending` after the await (alongside `disposed`) stops a stale - * alert: an unread dot, badge bump, or Dock bounce for a question that no longer - * needs the user. `alert` carries the resolved root id and owns the actual - * notification / sound / attention side effects. Returns the root id when it - * alerted, or undefined when it bailed. - */ -export async function resolveAndAlertQuestion(opts: { - resolveRoot: () => Promise - disposed: () => boolean - isPending: () => boolean - alert: (rootID: string) => void -}): Promise { - const rootID = await opts.resolveRoot() - if (opts.disposed()) return undefined - if (!opts.isPending()) return undefined - opts.alert(rootID) - return rootID -} - -type RetractableQuestion = { - type: string - directory?: string - ask?: { sessionID: string; messageID: string; partID: string } -} - -/** - * Split a notification list into the question notifications a removal event - * retracts and everything kept. - * - * A question is a live condition, not a point-in-time event: once its part - * leaves `running` (a terminal `reset`), the part is removed, or its whole - * message is removed, the appended notification must be retracted or the unread - * dot / Dock badge keeps claiming the session needs input. Matching is by the - * *asking* question identity recorded in `ask` (directory + asking sessionID, - * plus `partID` or `messageID`) — the notification's own `session` is the root - * session used for display, not for matching. `partID` and `messageID` are each - * matched only when provided, so a part removal targets one part while a message - * removal sweeps every question in that message. Question notifications without - * an `ask` identity (legacy persisted entries) never match and are kept. - */ -export function partitionRetractedQuestions( - list: readonly T[], - match: { directory: string; sessionID: string; partID?: string; messageID?: string }, -): { kept: T[]; removed: T[] } { - const kept: T[] = [] - const removed: T[] = [] - for (const notification of list) { - const ask = notification.type === "question" ? notification.ask : undefined - const matches = - ask !== undefined && - notification.directory === match.directory && - ask.sessionID === match.sessionID && - (match.partID === undefined || ask.partID === match.partID) && - (match.messageID === undefined || ask.messageID === match.messageID) - if (matches) removed.push(notification) - else kept.push(notification) - } - return { kept, removed } -} diff --git a/packages/app/src/context/notification.tsx b/packages/app/src/context/notification.tsx index b62152cec..7108b6117 100644 --- a/packages/app/src/context/notification.tsx +++ b/packages/app/src/context/notification.tsx @@ -12,18 +12,16 @@ import { Binary } from "@opencode-ai/util/binary" import { base64Encode } from "@opencode-ai/util/encode" import { decode64 } from "@/utils/base64" import { EventSessionError } from "@opencode-ai/sdk/v2" -import type { Part } from "@opencode-ai/sdk/v2/client" import { Persist, persisted } from "@/utils/persist" import { playSoundById } from "@/utils/sound" import { workspaceKey } from "@/pages/layout/helpers" import { - partitionRetractedQuestions, - questionCallKey, - questionNotificationAction, - resolveAndAlertQuestion, - resolveRootSessionIDAsync, - unreadSessionCount, + badgeSessionCount, + buildNotificationIndex, + isLiveNotification, + type NotificationIndex, } from "./notification-derive" +import { pendingRootSessionIDs } from "./global-sync/pending-question-index" type NotificationBase = { directory?: string @@ -42,91 +40,20 @@ type ErrorNotification = NotificationBase & { error: EventSessionError["properties"]["error"] } -type QuestionNotification = NotificationBase & { - type: "question" - // Identity of the originating question call (the *asking* session/message/part, - // not the root `session` recorded above for display). A question is a live - // condition: this lets a terminal reset, a removed part, or a removed message - // retract the notification so the unread dot / badge stops claiming the session - // needs input. Optional so legacy persisted entries (written before this field) - // still load — they simply never match a retraction. - ask?: { sessionID: string; messageID: string; partID: string } -} - -export type Notification = TurnCompleteNotification | ErrorNotification | QuestionNotification - -type NotificationIndex = { - session: { - all: Record - unseen: Record - unseenCount: Record - unseenHasError: Record - } - project: { - all: Record - unseen: Record - unseenCount: Record - unseenHasError: Record - } -} +export type Notification = TurnCompleteNotification | ErrorNotification const MAX_NOTIFICATIONS = 500 const NOTIFICATION_TTL_MS = 1000 * 60 * 60 * 24 * 30 function pruneNotifications(list: Notification[]) { const cutoff = Date.now() - NOTIFICATION_TTL_MS - const pruned = list.filter((n) => n.time >= cutoff) + // isLiveNotification drops legacy persisted `type:"question"` entries on load + // (see #1199) so an already-answered question can never strand an unread dot. + const pruned = list.filter((n) => isLiveNotification(n) && n.time >= cutoff) if (pruned.length <= MAX_NOTIFICATIONS) return pruned return pruned.slice(pruned.length - MAX_NOTIFICATIONS) } -function createNotificationIndex(): NotificationIndex { - return { - session: { - all: {}, - unseen: {}, - unseenCount: {}, - unseenHasError: {}, - }, - project: { - all: {}, - unseen: {}, - unseenCount: {}, - unseenHasError: {}, - }, - } -} - -function buildNotificationIndex(list: Notification[]) { - const index = createNotificationIndex() - - list.forEach((notification) => { - if (notification.session) { - const all = index.session.all[notification.session] ?? [] - index.session.all[notification.session] = [...all, notification] - if (!notification.viewed) { - const unseen = index.session.unseen[notification.session] ?? [] - index.session.unseen[notification.session] = [...unseen, notification] - index.session.unseenCount[notification.session] = unseen.length + 1 - if (notification.type === "error") index.session.unseenHasError[notification.session] = true - } - } - - if (notification.directory) { - const all = index.project.all[notification.directory] ?? [] - index.project.all[notification.directory] = [...all, notification] - if (!notification.viewed) { - const unseen = index.project.unseen[notification.directory] ?? [] - index.project.unseen[notification.directory] = [...unseen, notification] - index.project.unseenCount[notification.directory] = unseen.length + 1 - if (notification.type === "error") index.project.unseenHasError[notification.directory] = true - } - } - }) - - return index -} - export const { use: useNotification, provider: NotificationProvider } = createSimpleContext({ name: "Notification", init: () => { @@ -227,19 +154,6 @@ export const { use: useNotification, provider: NotificationProvider } = createSi }) } - // Retract the persisted question notification(s) a removal event resolves — - // a question is a live condition, so when its part leaves `running` (reset), - // its part is removed, or its whole message is removed, the unread dot / - // badge must stop claiming the session needs input. - const dropQuestions = (match: { directory: string; sessionID: string; partID?: string; messageID?: string }) => { - const { kept, removed } = partitionRetractedQuestions(store.list, match) - if (!removed.length) return - batch(() => { - removed.forEach((n) => removeFromIndex(n)) - setStore("list", kept) - }) - } - const lookup = async (directory: string, sessionID?: string) => { if (!sessionID) return undefined const [syncStore] = globalSync.child(directory, { bootstrap: false }) @@ -323,78 +237,33 @@ export const { use: useNotification, provider: NotificationProvider } = createSi }) } - // Questions stream as repeated `message.part.updated` events; dedupe so a - // single question alerts once. The entry is cleared when the part stops - // running (see questionNotificationAction) or is removed. - const alertedQuestionCalls = new Set() - - // Resolve a session's parentID from the in-memory list, falling back to a - // network lookup when the project's sessions were never bootstrapped — the - // global event stream delivers questions for background projects too, so the - // in-memory list can be empty here. - const fetchParentID = async (directory: string, sessionID: string): Promise => { - const [syncStore] = globalSync.child(directory, { bootstrap: false }) - const match = Binary.search(syncStore.session, sessionID, (s) => s.id) - if (match.found) return syncStore.session[match.index].parentID - const session = await globalSDK.client.session - .get({ directory, sessionID }) - .then((x) => x.data) - .catch(() => undefined) - return session?.parentID - } - - const handleQuestionPart = async (directory: string, sessionID: string, part: Part, time: number) => { - const action = questionNotificationAction(part) - if (action === "ignore") return - - const callKey = questionCallKey(directory, sessionID, part.id) - if (action === "reset") { - alertedQuestionCalls.delete(callKey) - dropQuestions({ directory, sessionID, partID: part.id }) - return - } - if (alertedQuestionCalls.has(callKey)) return - alertedQuestionCalls.add(callKey) - - await resolveAndAlertQuestion({ - // A child agent's question surfaces on (and is answered from) its root - // session's page, and only root sessions show in the sidebar — - // attribute the notification to the root, not the asking child. - // Resolving the root may hit the network for an unbootstrapped - // background project, so async. - resolveRoot: () => resolveRootSessionIDAsync(sessionID, (id) => fetchParentID(directory, id)), - disposed: () => meta.disposed, - // Re-check the dedupe claim after the async root resolution: a - // message.part.removed or terminal reset for this same call may have - // cleared it mid-await, meaning the question is gone — don't alert. - isPending: () => alertedQuestionCalls.has(callKey), - alert: (rootID) => { - const [syncStore] = globalSync.child(directory, { bootstrap: false }) - const rootMatch = Binary.search(syncStore.session, rootID, (s) => s.id) - const rootTitle = rootMatch.found ? syncStore.session[rootMatch.index].title : undefined - - const visible = viewedInCurrentSession(directory, rootID) - append({ - directory, - time, - viewed: visible, - type: "question", - session: rootID, - ask: { sessionID, messageID: part.messageID, partID: part.id }, - }) - - const level = settings.notify.level() - const shouldAlert = level !== "never" && (level === "always" || !visible) - if (shouldAlert) { - void playSoundById("notify") - const href = `/${base64Encode(directory)}/session/${rootID}` - void platform.notify(language.t("notification.question.title"), rootTitle ?? rootID, href) - // A question blocks the agent on the user, so it bounces the Dock / - // flashes the taskbar. turn-complete and error (above) only notify. - void platform.requestAttention?.() - } - }, - }) + // A live question's OS alert (sound / notification / Dock attention) is + // driven by the global pending-question controller, which fires exactly once + // on the rising edge — when a `question` part first becomes ready — and never + // on hydrate/reconnect, so a restart with an outstanding question does not + // re-nag. The controller has already resolved the root session it should be + // attributed to; we only decide whether to surface it and how. + const alertQuestion = (alert: { + directory: string + askSessionID: string + rootSessionID: string + }) => { + if (meta.disposed) return + const level = settings.notify.level() + if (level === "never") return + const visible = viewedInCurrentSession(alert.directory, alert.rootSessionID) + if (level !== "always" && visible) return + + const [syncStore] = globalSync.child(alert.directory, { bootstrap: false }) + const match = Binary.search(syncStore.session, alert.rootSessionID, (s) => s.id) + const rootTitle = match.found ? syncStore.session[match.index].title : undefined + + void playSoundById("notify") + const href = `/${base64Encode(alert.directory)}/session/${alert.rootSessionID}` + void platform.notify(language.t("notification.question.title"), rootTitle ?? alert.rootSessionID, href) + // A question blocks the agent on the user, so it bounces the Dock / + // flashes the taskbar. turn-complete and error only notify. + void platform.requestAttention?.() } const markSessionViewed = (session: string) => { @@ -420,22 +289,6 @@ export const { use: useNotification, provider: NotificationProvider } = createSi const event = e.details const directory = e.name - if (event.type === "message.part.updated") { - void handleQuestionPart(directory, event.properties.sessionID, event.properties.part, Date.now()) - return - } - if (event.type === "message.part.removed") { - const { sessionID, partID } = event.properties - alertedQuestionCalls.delete(questionCallKey(directory, sessionID, partID)) - dropQuestions({ directory, sessionID, partID }) - return - } - if (event.type === "message.removed") { - // removeMessage / revert emit only `message.removed`, not a per-part - // `message.part.removed`, so sweep every question in the message. - dropQuestions({ directory, sessionID: event.properties.sessionID, messageID: event.properties.messageID }) - return - } if (event.type !== "session.idle" && event.type !== "session.error") return const time = Date.now() @@ -445,19 +298,25 @@ export const { use: useNotification, provider: NotificationProvider } = createSi } handleSessionError(directory, event, time) }) + const unsubQuestionAlert = globalSync.onQuestionAlert(alertQuestion) onCleanup(() => { meta.disposed = true unsub() + unsubQuestionAlert() }) - // Dock/taskbar badge: how many sessions from *this* app run are waiting for - // the user. Scoped to launch time so a fresh start shows zero instead of - // resurfacing the persisted backlog on the Dock — notifications survive - // restarts to drive the sidebar, but the badge should only nag about what - // arrived this session. Follows the notify level (suppressed when off). - // macOS/Linux only (platform.setBadgeCount is undefined elsewhere). + // Dock/taskbar badge: how many sessions are waiting for the user. Two + // sources unioned by session (see badgeSessionCount): unseen turn-complete / + // error notifications from *this* app run (launch-scoped so a fresh start + // shows zero instead of resurfacing the persisted backlog), plus the root + // sessions of every live pending question (a current condition, so never + // launch-scoped — a question still outstanding across a restart should + // badge). Follows the notify level (suppressed when off). macOS/Linux only + // (platform.setBadgeCount is undefined elsewhere). const launchTime = Date.now() - const badgeCount = createMemo(() => unreadSessionCount(store.list, launchTime)) + const badgeCount = createMemo(() => + badgeSessionCount(store.list, pendingRootSessionIDs(globalSync.data.pendingQuestions), launchTime), + ) createEffect(() => { const count = settings.notify.level() === "never" ? 0 : badgeCount() void platform.setBadgeCount?.(count) diff --git a/packages/app/src/pages/layout/pawwork-session-commands.test.ts b/packages/app/src/pages/layout/pawwork-session-commands.test.ts index e46cadeee..27e78d246 100644 --- a/packages/app/src/pages/layout/pawwork-session-commands.test.ts +++ b/packages/app/src/pages/layout/pawwork-session-commands.test.ts @@ -50,7 +50,6 @@ function setup(opts: SetupOpts = {}) { message: Record part: Record permission: Record - external_result_question: Record }>({ session: opts.sessions ?? [], session_status: {}, @@ -59,7 +58,6 @@ function setup(opts: SetupOpts = {}) { message: {}, part: {}, permission: {}, - external_result_question: {}, }) const defaultExport = ((id: string, dir: string, name: string, label: string) => { calls.exportArgs.push([id, dir, name, label]) diff --git a/packages/app/src/pages/layout/sidebar-items.tsx b/packages/app/src/pages/layout/sidebar-items.tsx index 82649eb12..4d7339266 100644 --- a/packages/app/src/pages/layout/sidebar-items.tsx +++ b/packages/app/src/pages/layout/sidebar-items.tsx @@ -113,7 +113,6 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => { findDescendantExternalResultQuestion({ sessions: sessionStore.session, rootSessionID: props.session.id, - pendingQuestions: sessionStore.external_result_question, messages: sessionStore.message, partsByMessageID: sessionStore.part, }) !== undefined diff --git a/packages/app/src/pages/session/blockers/running-external-result-question.ts b/packages/app/src/pages/session/blockers/running-external-result-question.ts index 0ac0c5e1f..f81c10015 100644 --- a/packages/app/src/pages/session/blockers/running-external-result-question.ts +++ b/packages/app/src/pages/session/blockers/running-external-result-question.ts @@ -10,22 +10,6 @@ export type { QuestionInfo } */ export type DockQuestionRequest = PendingExternalResultQuestion -function isKnownStalePendingQuestion(input: { - pending: DockQuestionRequest - partsByMessageID: { [messageID: string]: Part[] | undefined } -}) { - const part = input.partsByMessageID[input.pending.messageID]?.find((item) => item.id === input.pending.partID) - // If the part never reached the local cache, keep the index entry; bootstrap - // prune reconciles already-answered questions whose terminal event was missed. - if (!part) return false - if (part.type !== "tool") return true - if (part.tool !== "question") return true - if (part.state.status !== "running") return true - if (part.state.metadata?.externalResultReady !== true) return true - const partInput = part.state.input as { questions?: QuestionInfo[] } | undefined - return !Array.isArray(partInput?.questions) || partInput.questions.length === 0 -} - /** * Selector: find the first running `question` tool part for the active session * whose `state.metadata.externalResultReady === true`. The `=== true` check is @@ -76,15 +60,19 @@ export function findRunningExternalResultQuestion(input: { * stay in lock-step). The returned `sessionID` points at the session that * actually owns the running tool part, so /tool/respond hits the correct * Deferred. + * + * Derived purely from the local `message`/`part` cache: a running, ready + * question part IS the renderable truth. Reload / cold-open recovers it because + * `hydratePendingExternalResults` writes the `/external-result` trio's parts + * back into the cache; there is no separate pending index to consult. */ export function findDescendantExternalResultQuestion(input: { sessions: Session[] rootSessionID: string - pendingQuestions?: { [sessionID: string]: DockQuestionRequest[] | undefined } messages: { [sessionID: string]: Message[] | undefined } partsByMessageID: { [messageID: string]: Part[] | undefined } }): DockQuestionRequest | undefined { - const { sessions, rootSessionID, pendingQuestions, messages, partsByMessageID } = input + const { sessions, rootSessionID, messages, partsByMessageID } = input const childMap = sessions.reduce((acc, item) => { if (!item.parentID) return acc const list = acc.get(item.parentID) @@ -97,10 +85,6 @@ export function findDescendantExternalResultQuestion(input: { const stack = [rootSessionID] while (stack.length > 0) { const sid = stack.pop()! - const pending = pendingQuestions?.[sid]?.find( - (item) => !isKnownStalePendingQuestion({ pending: item, partsByMessageID }), - ) - if (pending) return pending const found = findRunningExternalResultQuestion({ sessionID: sid, messages: messages[sid], diff --git a/packages/app/src/pages/session/blockers/use-session-blockers.test.ts b/packages/app/src/pages/session/blockers/use-session-blockers.test.ts index d2fc24fe5..04395bd34 100644 --- a/packages/app/src/pages/session/blockers/use-session-blockers.test.ts +++ b/packages/app/src/pages/session/blockers/use-session-blockers.test.ts @@ -144,102 +144,41 @@ describe("findRunningExternalResultQuestion", () => { }) }) +// The dock walks the session tree and renders purely from the local +// message/part cache — a running, ready question part IS the request. There is +// no pending index to consult: reload recovers via hydrate writing the part +// back, and a terminal part simply stops matching `findRunningExternalResultQuestion`. describe("findDescendantExternalResultQuestion", () => { - test("returns an active session question from the pending blocker index without an owning message row", () => { + test("ignores a running question outside the active session tree", () => { const result = findDescendantExternalResultQuestion({ - sessions: [session("parent")], + sessions: [session("parent"), session("other")], rootSessionID: "parent", - pendingQuestions: { - parent: [ - { - id: "m-orphan:c-parent", - sessionID: "parent", - questions, - messageID: "m-orphan", - callID: "c-parent", - partID: "p-orphan", - }, + messages: { other: [message("m-other")] }, + partsByMessageID: { + "m-other": [ + toolPart("p-other", "question", toolState("running", { externalResultReady: true }, { questions }), { + messageID: "m-other", + callID: "c-other", + }), ], }, - messages: {}, - partsByMessageID: {}, }) - expect(result?.sessionID).toBe("parent") - expect(result?.callID).toBe("c-parent") + expect(result).toBeUndefined() }) - test("ignores a pending blocker index entry when the local part is already terminal", () => { + test("ignores a terminal question part in the tree", () => { const result = findDescendantExternalResultQuestion({ sessions: [session("parent")], rootSessionID: "parent", - pendingQuestions: { - parent: [ - { - id: "m1:c-parent", - sessionID: "parent", - questions, - messageID: "m1", - callID: "c-parent", - partID: "p1", - }, - ], - }, messages: { parent: [message("m1")] }, partsByMessageID: { m1: [ - toolPart( - "p1", - "question", - toolState("completed", { externalResultReady: true }, { questions }), - { messageID: "m1", callID: "c-parent" }, - ), - ], - }, - }) - expect(result).toBeUndefined() - }) - - test("returns a child session question from the pending blocker index without an owning message row", () => { - const result = findDescendantExternalResultQuestion({ - sessions: [session("parent"), session("child", "parent")], - rootSessionID: "parent", - pendingQuestions: { - child: [ - { - id: "m-child-orphan:c-child", - sessionID: "child", - questions, - messageID: "m-child-orphan", - callID: "c-child", - partID: "p-child-orphan", - }, - ], - }, - messages: {}, - partsByMessageID: {}, - }) - expect(result?.sessionID).toBe("child") - expect(result?.callID).toBe("c-child") - }) - - test("ignores pending blocker index entries outside the active session tree", () => { - const result = findDescendantExternalResultQuestion({ - sessions: [session("parent"), session("other")], - rootSessionID: "parent", - pendingQuestions: { - other: [ - { - id: "m-other:c-other", - sessionID: "other", - questions, - messageID: "m-other", - callID: "c-other", - partID: "p-other", - }, + toolPart("p1", "question", toolState("completed", { externalResultReady: true }, { questions }), { + messageID: "m1", + callID: "c-parent", + }), ], }, - messages: {}, - partsByMessageID: {}, }) expect(result).toBeUndefined() }) diff --git a/packages/app/src/pages/session/blockers/use-session-blockers.ts b/packages/app/src/pages/session/blockers/use-session-blockers.ts index fcfe8c419..0cbc17828 100644 --- a/packages/app/src/pages/session/blockers/use-session-blockers.ts +++ b/packages/app/src/pages/session/blockers/use-session-blockers.ts @@ -35,7 +35,6 @@ export function createSessionBlockers(input: { return findDescendantExternalResultQuestion({ sessions: sync.data.session, rootSessionID: sid, - pendingQuestions: sync.data.external_result_question, messages: sync.data.message, partsByMessageID: sync.data.part, })