Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/app/src/context/global-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const globalStoreFixture = (): GlobalStore => ({
path: { state: "", config: "", worktree: "", directory: "", home: "" },
project: [],
session_todo: {},
pendingQuestions: {},
provider: { all: [], connected: [], default: {} },
provider_auth: {},
config: {},
Expand Down
38 changes: 36 additions & 2 deletions packages/app/src/context/global-sync.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import type {
AutomationCreateInput,
Config,
Expand Down Expand Up @@ -32,6 +32,8 @@
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,
Expand Down Expand Up @@ -77,6 +79,11 @@
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
Expand Down Expand Up @@ -111,6 +118,7 @@
path: { state: "", config: "", worktree: "", directory: "", home: "" },
project: projectCache.value,
session_todo: {},
pendingQuestions: {},
provider: { all: [], connected: [], default: {} },
provider_auth: {},
config: {},
Expand Down Expand Up @@ -239,6 +247,24 @@
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)
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
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
Expand All @@ -261,7 +287,7 @@
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, {
Expand Down Expand Up @@ -293,7 +319,7 @@
const sessions = trimSessions([...nonArchived, ...childSessions], {
limit,
permission: store.permission,
externalResultQuestion: store.external_result_question,
preserveSessionIDs: pendingSessionIDsForDirectory(globalStore.pendingQuestions, directory),
})
setStore(
"sessionTotal",
Expand Down Expand Up @@ -432,6 +458,7 @@
loadSessions,
translate: language.t,
queryClient,
pendingQuestions: { reconcile: questions.reconcile },
})
})

Expand Down Expand Up @@ -474,6 +501,10 @@
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,
Expand Down Expand Up @@ -655,6 +686,9 @@
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,
Expand Down
105 changes: 32 additions & 73 deletions packages/app/src/context/global-sync/bootstrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ function createState(): State {
turn_change_aggregate: {},
todo: {},
permission: {},
external_result_question: {},
mcp_ready: false,
mcp: {},
lsp_ready: false,
Expand Down Expand Up @@ -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[]) => {
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -240,6 +231,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand All @@ -266,6 +258,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -320,6 +313,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -412,6 +406,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -464,6 +459,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -520,6 +516,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -574,6 +571,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -633,6 +631,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -707,6 +706,7 @@ describe("bootstrapDirectory", () => {
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
pendingQuestions: { reconcile() {} },
translate: (key: string) => key,
global: {
config: {} as Config,
Expand Down Expand Up @@ -769,28 +769,17 @@ 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 }],
})
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",
Expand All @@ -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", () => {
Expand Down Expand Up @@ -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")
})
Expand Down
Loading
Loading