Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
15 changes: 14 additions & 1 deletion packages/app/e2e/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,20 @@ export async function seedSessionQuestion(
},
})

if (!result) throw new Error("Timed out seeding question request")
if (!result) {
const [questions, status] = await Promise.all([
sdk.question.list().then((x) => x.data ?? []).catch((error) => ({ error: String(error) })),
sdk.session.status().then((x) => x.data ?? {}).catch((error) => ({ error: String(error) })),
])
throw new Error(
`Timed out seeding question request: ${JSON.stringify({
sessionID: input.sessionID,
wantedHeader: first.header,
questions,
status,
})}`,
)
}
return { id: result.id }
}

Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/context/global-sdk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createSdkForServer } from "@/utils/server"
import { useLanguage } from "./language"
import { usePlatform } from "./platform"
import { useServer } from "./server"
import { createSseCursor } from "./global-sdk/sse-cursor"

const abortError = z.object({
name: z.literal("AbortError"),
Expand Down Expand Up @@ -111,6 +112,7 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
const HEARTBEAT_TIMEOUT_MS = 15_000
let lastEventAt = Date.now()
let heartbeat: ReturnType<typeof setTimeout> | undefined
const replayCursor = createSseCursor()
const resetHeartbeat = () => {
lastEventAt = Date.now()
if (heartbeat) clearTimeout(heartbeat)
Expand Down Expand Up @@ -139,6 +141,10 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
try {
const events = await eventSdk.global.event({
signal: attempt.signal,
headers: replayCursor.headers(),
onSseEvent: (event) => {
replayCursor.update(event.id)
},
onSseError: (error) => {
if (aborted(error)) return
if (streamErrorLogged) return
Expand Down
30 changes: 30 additions & 0 deletions packages/app/src/context/global-sdk/sse-cursor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test"
import { createSseCursor } from "./sse-cursor"

describe("createSseCursor", () => {
test("starts without a cursor", () => {
const cursor = createSseCursor()
expect(cursor.current()).toBeUndefined()
expect(cursor.headers()).toBeUndefined()
})

test("stores the latest non-empty event id", () => {
const cursor = createSseCursor()
cursor.update(undefined)
cursor.update("")
cursor.update("boot:1")
cursor.update("boot:2")

expect(cursor.current()).toBe("boot:2")
})

test("builds Last-Event-ID headers when a cursor exists", () => {
const cursor = createSseCursor()
cursor.update("boot:7")

const headers = cursor.headers()

expect(headers).toBeInstanceOf(Headers)
expect(headers?.get("Last-Event-ID")).toBe("boot:7")
})
})
20 changes: 20 additions & 0 deletions packages/app/src/context/global-sdk/sse-cursor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function createSseCursor() {
let value: string | undefined

return {
current() {
return value
},
update(id: string | undefined) {
if (!id) return
// SSE ids come from the server replay layer; keep this helper transport-only.
value = id
},
headers() {
if (!value) return undefined
const headers = new Headers()
headers.set("Last-Event-ID", value)
return headers
},
}
}
4 changes: 4 additions & 0 deletions packages/app/src/context/global-sync.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Persist, persisted } from "@/utils/persist"
import type { InitError } from "../pages/error"
import { useGlobalSDK } from "./global-sdk"
import { bootstrapDirectory, bootstrapGlobal, clearProviderRev } from "./global-sync/bootstrap"
import { createBlockerTerminalCache } from "./global-sync/blocker-terminal-cache"
import { createChildStoreManager } from "./global-sync/child-store"
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./global-sync/event-reducer"
import { createRefreshQueue } from "./global-sync/queue"
Expand Down Expand Up @@ -57,6 +58,7 @@ function createGlobalSync() {
const booting = new Map<string, Promise<void>>()
const sessionLoads = new Map<string, Promise<void>>()
const sessionMeta = new Map<string, { limit: number }>()
const blockerTerminals = createBlockerTerminalCache()

const [projectCache, setProjectCache, projectInit] = persisted(
Persist.global("globalSync.project", ["globalSync.project.v1"]),
Expand Down Expand Up @@ -166,6 +168,7 @@ function createGlobalSync() {
onDispose: (directory) => {
queue.clear(directory)
sessionMeta.delete(directory)
blockerTerminals.clearDirectory(directory)
sdkCache.delete(directory)
clearProviderRev(directory)
clearSessionPrefetchDirectory(directory)
Expand Down Expand Up @@ -330,6 +333,7 @@ function createGlobalSync() {
setStore,
push: queue.push,
setSessionTodo,
blockerTerminals,
vcsCache: children.vcsCache.get(directory),
loadLsp: () => {
void sdkFor(directory)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, expect, test } from "bun:test"
import { createBlockerTerminalCache } from "./blocker-terminal-cache"

describe("createBlockerTerminalCache", () => {
test("marks and finds terminal blocker ids by kind, directory, session, and request", () => {
const cache = createBlockerTerminalCache({ now: () => 1000 })

cache.mark("question", "/repo", "ses_1", "q1")

expect(cache.has("question", "/repo", "ses_1", "q1")).toBe(true)
expect(cache.has("permission", "/repo", "ses_1", "q1")).toBe(false)
expect(cache.has("question", "/other", "ses_1", "q1")).toBe(false)
expect(cache.has("question", "/repo", "ses_2", "q1")).toBe(false)
})

test("expires old entries by ttl", () => {
let now = 1000
const cache = createBlockerTerminalCache({ ttlMs: 100, now: () => now })

cache.mark("question", "/repo", "ses_1", "q1")
now = 1200

expect(cache.has("question", "/repo", "ses_1", "q1")).toBe(false)
})

test("prunes oldest entries by max size", () => {
let now = 1000
const cache = createBlockerTerminalCache({ max: 2, now: () => now })

cache.mark("question", "/repo", "ses_1", "q1")
now += 1
cache.mark("question", "/repo", "ses_1", "q2")
now += 1
cache.mark("question", "/repo", "ses_1", "q3")

expect(cache.has("question", "/repo", "ses_1", "q1")).toBe(false)
expect(cache.has("question", "/repo", "ses_1", "q2")).toBe(true)
expect(cache.has("question", "/repo", "ses_1", "q3")).toBe(true)
})

test("clears all entries for a directory", () => {
const cache = createBlockerTerminalCache({ now: () => 1000 })

cache.mark("question", "/repo", "ses_1", "q1")
cache.mark("question", "/other", "ses_1", "q1")
cache.clearDirectory("/repo")

expect(cache.has("question", "/repo", "ses_1", "q1")).toBe(false)
expect(cache.has("question", "/other", "ses_1", "q1")).toBe(true)
})
})
50 changes: 50 additions & 0 deletions packages/app/src/context/global-sync/blocker-terminal-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export type BlockerKind = "question" | "permission"

type Entry = {
directory: string
createdAt: number
}

const DEFAULT_MAX = 2048
const DEFAULT_TTL_MS = 5 * 60 * 1000

export function createBlockerTerminalCache(input?: { max?: number; ttlMs?: number; now?: () => number }) {
const max = input?.max ?? DEFAULT_MAX
const ttlMs = input?.ttlMs ?? DEFAULT_TTL_MS
const now = input?.now ?? Date.now
const entries = new Map<string, Entry>()

const keyFor = (kind: BlockerKind, directory: string, sessionID: string, requestID: string) =>
JSON.stringify([kind, directory, sessionID, requestID])

const prune = () => {
const cutoff = now() - ttlMs
for (const [key, entry] of entries) {
if (entry.createdAt >= cutoff) continue
entries.delete(key)
}
while (entries.size > max) {
const oldest = entries.keys().next().value
if (!oldest) break
entries.delete(oldest)
}
}

return {
mark(kind: BlockerKind, directory: string, sessionID: string, requestID: string) {
const key = keyFor(kind, directory, sessionID, requestID)
entries.delete(key)
entries.set(key, { directory, createdAt: now() })
prune()
},
has(kind: BlockerKind, directory: string, sessionID: string, requestID: string) {
prune()
return entries.has(keyFor(kind, directory, sessionID, requestID))
},
clearDirectory(directory: string) {
for (const [key, entry] of entries) {
if (entry.directory === directory) entries.delete(key)
}
},
}
}
61 changes: 61 additions & 0 deletions packages/app/src/context/global-sync/event-reducer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
import type { Message, Part, PermissionRequest, Project, QuestionRequest, Session } from "@opencode-ai/sdk/v2/client"
import { createStore } from "solid-js/store"
import type { State } from "./types"
import { createBlockerTerminalCache } from "./blocker-terminal-cache"
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./event-reducer"

const rootSession = (input: { id: string; parentID?: string; archived?: number; created?: number; updated?: number }) =>
Expand Down Expand Up @@ -493,6 +494,66 @@ describe("applyDirectoryEvent", () => {
expect(store.question[sessionID]?.map((x) => x.id)).toEqual(["q_1", "q_3"])
})

test("question.replied before question.asked prevents stale ask from reopening", () => {
const blockerTerminals = createBlockerTerminalCache({ now: () => 1000 })
const [store, setStore] = createStore(baseState())

applyDirectoryEvent({
event: { type: "question.replied", properties: { sessionID: "ses_1", requestID: "q1" } },
directory: "/repo",
store,
setStore,
push() {},
loadLsp() {},
blockerTerminals,
})

applyDirectoryEvent({
event: {
type: "question.asked",
properties: questionRequest("q1", "ses_1"),
},
directory: "/repo",
store,
setStore,
push() {},
loadLsp() {},
blockerTerminals,
})

expect(store.question.ses_1).toBeUndefined()
})

test("permission.replied before permission.asked prevents stale ask from reopening", () => {
const blockerTerminals = createBlockerTerminalCache({ now: () => 1000 })
const [store, setStore] = createStore(baseState())

applyDirectoryEvent({
event: { type: "permission.replied", properties: { sessionID: "ses_1", requestID: "perm_1" } },
directory: "/repo",
store,
setStore,
push() {},
loadLsp() {},
blockerTerminals,
})

applyDirectoryEvent({
event: {
type: "permission.asked",
properties: permissionRequest("perm_1", "ses_1"),
},
directory: "/repo",
store,
setStore,
push() {},
loadLsp() {},
blockerTerminals,
})

expect(store.permission.ses_1).toBeUndefined()
})

test("updates vcs branch in store and cache", () => {
const [store, setStore] = createStore(baseState({ vcs: { branch: "main", default_branch: "main" } }))
const [cacheStore, setCacheStore] = createStore({
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/context/global-sync/event-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { State, VcsCache } from "./types"
import { trimSessions } from "./session-trim"
import { dropSessionCaches } from "./session-cache"
import { diffs as list, message as clean } from "@/utils/diffs"
import type { createBlockerTerminalCache } from "./blocker-terminal-cache"

const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])

Expand Down Expand Up @@ -95,6 +96,7 @@ export function applyDirectoryEvent(input: {
loadLsp: () => void
vcsCache?: VcsCache
setSessionTodo?: (sessionID: string, todos: Todo[] | undefined) => void
blockerTerminals?: ReturnType<typeof createBlockerTerminalCache>
}) {
const event = input.event
switch (event.type) {
Expand Down Expand Up @@ -277,6 +279,7 @@ export function applyDirectoryEvent(input: {
}
case "permission.asked": {
const permission = event.properties as PermissionRequest
if (input.blockerTerminals?.has("permission", input.directory, permission.sessionID, permission.id)) break
const permissions = input.store.permission[permission.sessionID]
if (!permissions) {
input.setStore("permission", permission.sessionID, [permission])
Expand All @@ -298,6 +301,7 @@ export function applyDirectoryEvent(input: {
}
case "permission.replied": {
const props = event.properties as { sessionID: string; requestID: string }
input.blockerTerminals?.mark("permission", input.directory, props.sessionID, props.requestID)
const permissions = input.store.permission[props.sessionID]
if (!permissions) break
const result = Binary.search(permissions, props.requestID, (p) => p.id)
Expand All @@ -313,6 +317,7 @@ export function applyDirectoryEvent(input: {
}
case "question.asked": {
const question = event.properties as QuestionRequest
if (input.blockerTerminals?.has("question", input.directory, question.sessionID, question.id)) break
const questions = input.store.question[question.sessionID]
if (!questions) {
input.setStore("question", question.sessionID, [question])
Expand All @@ -335,6 +340,7 @@ export function applyDirectoryEvent(input: {
case "question.replied":
case "question.rejected": {
const props = event.properties as { sessionID: string; requestID: string }
input.blockerTerminals?.mark("question", input.directory, props.sessionID, props.requestID)
const questions = input.store.question[props.sessionID]
if (!questions) break
const result = Binary.search(questions, props.requestID, (q) => q.id)
Expand Down
Loading
Loading