mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
fix(app): list running jobs once per server for the sidebar spinner
User decisions: - The sidebar spinner also spins while the session's family has running background work
This commit is contained in:
parent
c997134922
commit
ae2b68da3a
5 changed files with 218 additions and 14 deletions
|
|
@ -231,6 +231,9 @@ function createServerController(
|
|||
},
|
||||
})
|
||||
|
||||
// One server-wide list of running jobs lets every sidebar root show its family's background work.
|
||||
void source.job.syncRunning().catch(() => undefined)
|
||||
|
||||
const data = createDesktopData({
|
||||
data: source,
|
||||
remove: (sessionID) => sdk.api.session.remove({ sessionID }),
|
||||
|
|
|
|||
128
packages/app/src/shell/layout/project-avatar-jobs.test.ts
Normal file
128
packages/app/src/shell/layout/project-avatar-jobs.test.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createData, type CreateDataInput } from "@opencode/client/solid"
|
||||
import { OpenCode, type JobInfo, type OpenCodeEvent } from "@opencode/client/promise"
|
||||
import { running } from "./project-avatar-state"
|
||||
import { createDesktopData } from "@/runtime/server/data"
|
||||
|
||||
const job = (id: string, sessionID: string, status: JobInfo["status"] = "running"): JobInfo => ({
|
||||
kind: "codemode",
|
||||
id,
|
||||
sessionID,
|
||||
status,
|
||||
time: { started: 1 },
|
||||
})
|
||||
|
||||
const parents = new Map([
|
||||
["ses_root", undefined],
|
||||
["ses_child", "ses_root"],
|
||||
])
|
||||
|
||||
function setup(jobs: JobInfo[]) {
|
||||
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
|
||||
const lists: URLSearchParams[] = []
|
||||
const gets: string[] = []
|
||||
|
||||
const api = OpenCode.make({
|
||||
baseUrl: "http://opencode.local",
|
||||
fetch: Object.assign(
|
||||
async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = new URL((input instanceof Request ? input : new Request(input, init)).url)
|
||||
|
||||
if (url.pathname.includes("/job")) {
|
||||
lists.push(url.searchParams)
|
||||
|
||||
return Response.json({ data: jobs })
|
||||
}
|
||||
|
||||
const id = url.pathname.split("/").find((part) => parents.has(part))
|
||||
|
||||
if (!id) return Response.json({ data: [] })
|
||||
|
||||
gets.push(id)
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
id,
|
||||
parentID: parents.get(id),
|
||||
projectID: "project",
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 1, updated: 1 },
|
||||
location: { directory: "/project" },
|
||||
},
|
||||
})
|
||||
},
|
||||
{ preconnect: () => {} },
|
||||
),
|
||||
})
|
||||
|
||||
const emit = (event: OpenCodeEvent) => listeners.forEach((listener) => listener({ name: event.type, details: event }))
|
||||
|
||||
const root = createRoot((dispose) => {
|
||||
const source = createData({
|
||||
api: () => api,
|
||||
directory: "/project",
|
||||
event: { on: () => () => {}, listen: (handler) => (listeners.add(handler), () => listeners.delete(handler)) },
|
||||
connection: { status: () => "connected" },
|
||||
onError: () => {},
|
||||
})
|
||||
|
||||
// As the server runtime does, once per server.
|
||||
void source.job.syncRunning().catch(() => undefined)
|
||||
|
||||
const data = createDesktopData({ data: source, remove: async () => {} })
|
||||
|
||||
return { data, dispose }
|
||||
})
|
||||
|
||||
return { ...root, emit, lists, gets }
|
||||
}
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 20))
|
||||
|
||||
test("one server-wide request serves every row", async () => {
|
||||
const { data, dispose, lists } = setup([])
|
||||
|
||||
try {
|
||||
const roots = ["ses_a", "ses_b", "ses_c", "ses_d", "ses_e"]
|
||||
roots.forEach((id) => running(data, id, true))
|
||||
await settle()
|
||||
roots.forEach((id) => expect(running(data, id, true)).toBe(false))
|
||||
expect(lists).toHaveLength(1)
|
||||
expect(lists[0].get("sessionID")).toBeNull()
|
||||
expect(lists[0].get("status")).toBe("running")
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a job owned by an unloaded child spins its root once the child loads, and stops when it settles", async () => {
|
||||
const { data, dispose, emit, lists, gets } = setup([job("job_shell", "ses_child")])
|
||||
|
||||
try {
|
||||
expect(running(data, "ses_root", true)).toBe(false)
|
||||
await settle()
|
||||
expect(gets).toContain("ses_child")
|
||||
expect(data.session.status("ses_child")).not.toBe("running")
|
||||
expect(running(data, "ses_root", true)).toBe(true)
|
||||
|
||||
// SAFETY: the test emits the event shapes the client's handler reads.
|
||||
|
||||
emit({
|
||||
id: "evt_settled",
|
||||
created: 2,
|
||||
type: "experimental.job.updated",
|
||||
data: { info: job("job_shell", "ses_child", "completed") },
|
||||
} as OpenCodeEvent)
|
||||
expect(running(data, "ses_root", true)).toBe(false)
|
||||
|
||||
// SAFETY: the test emits the event shapes the client's handler reads.
|
||||
|
||||
emit({ id: "evt_connected", created: 3, type: "server.connected", data: {} } as OpenCodeEvent)
|
||||
await settle()
|
||||
expect(lists).toHaveLength(2)
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { createEffect, createMemo, type Accessor } from "solid-js"
|
||||
import { createMemo, type Accessor } from "solid-js"
|
||||
import type { SessionInfo } from "@opencode/client/promise"
|
||||
import { useGlobal, useServerCtx, type ServerCtx } from "@/runtime/server/runtime"
|
||||
import { sessionPermissionRequest, sessionFormRequest } from "@/session/requests/session-request-tree"
|
||||
|
|
@ -30,15 +30,6 @@ export function useSessionTabAvatarState(
|
|||
return attention(ctx, sessionId(), !!root?.(), settings.permissions.autoApproves(project))
|
||||
})
|
||||
|
||||
// Roots load their family's running jobs once; job events keep them current and a reconnect re-reads them.
|
||||
createEffect(() => {
|
||||
const ctx = serverCtx()
|
||||
|
||||
if (!ctx || !root?.()) return
|
||||
|
||||
void ctx.data.job.sync(sessionId()).catch(() => undefined)
|
||||
})
|
||||
|
||||
const unread = createMemo(
|
||||
() => needsAttention() || (serverCtx()?.notification.session.unread(sessionId(), snapshot?.()) ?? false),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -145,7 +145,8 @@ type Store = {
|
|||
permission: Record<string, PermissionSavedInfo[]>
|
||||
}
|
||||
location: Record<string, LocationData>
|
||||
// Running background jobs keyed by job id, for the session trees that synced them. Settled jobs are removed.
|
||||
// Running background jobs keyed by job id, for the session trees that synced them (or every one, once the server-wide
|
||||
// list synced). Settled jobs are removed.
|
||||
job: Record<string, JobInfo>
|
||||
// Job ids the server listed for each synced tree root (it filters descendants itself), plus ids that events added
|
||||
// for owners known to be in the tree. Loaded session info only reaches direct children, so walking parents alone
|
||||
|
|
@ -282,6 +283,7 @@ function createSync() {
|
|||
}
|
||||
|
||||
const CHILD_PAGE = 200
|
||||
const JOB_RUNNING = "job:*"
|
||||
// TODO: `sequence` and SEQUENCE_HANDOFF_MS patch a rare ordering race: a
|
||||
// `!shell` or `/command` sent behind a prompt that waits on a gate (the
|
||||
// desktop browser's attachment) must not reach the server before it. That is
|
||||
|
|
@ -391,6 +393,7 @@ export function createData(config: CreateDataInput) {
|
|||
// Job events that arrive while a tree's list is in flight, applied over its response: the latest info, or undefined
|
||||
// once settled.
|
||||
const jobUpdates = new Map<string, Map<string, JobInfo | undefined>>()
|
||||
let jobRunningSynced = false
|
||||
const pendingUpdates = new Map<string, Map<string, SessionInboxInfo | SessionInbox.Delivery | undefined>>()
|
||||
|
||||
function setSessionActive(sessionID: string, status: DataSessionStatus) {
|
||||
|
|
@ -820,6 +823,10 @@ export function createData(config: CreateDataInput) {
|
|||
result.job.invalidate(sessionID)
|
||||
refresh(() => result.job.sync(sessionID))
|
||||
})
|
||||
if (jobRunningSynced) {
|
||||
sync.invalidate(JOB_RUNNING)
|
||||
refresh(() => result.job.syncRunning())
|
||||
}
|
||||
return
|
||||
}
|
||||
case "experimental.job.updated": {
|
||||
|
|
@ -844,6 +851,7 @@ export function createData(config: CreateDataInput) {
|
|||
})
|
||||
}),
|
||||
)
|
||||
if (jobRunningSynced) loadJobOwner(info.sessionID)
|
||||
return
|
||||
}
|
||||
case "project.updated":
|
||||
|
|
@ -1223,8 +1231,7 @@ export function createData(config: CreateDataInput) {
|
|||
error: event.data.error,
|
||||
input: typeof tool.state.input === "string" ? {} : tool.state.input,
|
||||
metadata: event.data.metadata,
|
||||
content:
|
||||
omitFiles() && event.data.content ? omitFileData(event.data.content) : event.data.content,
|
||||
content: omitFiles() && event.data.content ? omitFileData(event.data.content) : event.data.content,
|
||||
}
|
||||
tool.executed = event.data.executed || tool.executed === true
|
||||
if (event.data.native) tool.native = { ...tool.native, ...event.data.native }
|
||||
|
|
@ -1623,6 +1630,55 @@ export function createData(config: CreateDataInput) {
|
|||
)
|
||||
}
|
||||
|
||||
// Every running job on the server, so any session's root can tell whether its family has background work.
|
||||
function syncRunningJobs() {
|
||||
jobRunningSynced = true
|
||||
return sync.run(JOB_RUNNING, async () => {
|
||||
const updates = new Map<string, JobInfo | undefined>()
|
||||
jobUpdates.set(JOB_RUNNING, updates)
|
||||
const list = await api()
|
||||
.experimental.job.list({ status: "running" })
|
||||
.catch((error: unknown) => {
|
||||
if (jobUpdates.get(JOB_RUNNING) === updates) jobUpdates.delete(JOB_RUNNING)
|
||||
throw error
|
||||
})
|
||||
if (jobUpdates.get(JOB_RUNNING) !== updates) return
|
||||
jobUpdates.delete(JOB_RUNNING)
|
||||
const next = new Map(list.map((job) => [job.id, job]))
|
||||
updates.forEach((info, id) => (info ? next.set(id, info) : next.delete(id)))
|
||||
// The server listed every running job, so anything else settled; trees keep their members that still run.
|
||||
setStore(
|
||||
produce((draft) => {
|
||||
Object.keys(draft.job).forEach((id) => {
|
||||
if (next.has(id)) return
|
||||
delete draft.job[id]
|
||||
Object.values(draft.jobTree).forEach((members) => delete members[id])
|
||||
})
|
||||
next.forEach((job, id) => (draft.job[id] = job))
|
||||
}),
|
||||
)
|
||||
next.forEach((job) => loadJobOwner(job.sessionID))
|
||||
})
|
||||
}
|
||||
|
||||
// A job only names its owner, so load the owner's info (and any missing ancestor) to place it under its root.
|
||||
function loadJobOwner(sessionID: string) {
|
||||
const seen = new Set<string>()
|
||||
let current: string | undefined = sessionID
|
||||
while (current && !seen.has(current) && store.session.info[current]) {
|
||||
seen.add(current)
|
||||
current = store.session.info[current]?.parentID
|
||||
}
|
||||
if (!current || seen.has(current) || store.session.missing[current]) return
|
||||
const id = current
|
||||
void result.session
|
||||
.sync(id)
|
||||
.then(() => {
|
||||
if (store.session.info[id]) loadJobOwner(id)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
function removeJobTree(rootID: string) {
|
||||
jobUpdates.delete(rootID)
|
||||
sync.invalidate(`job:${rootID}`)
|
||||
|
|
@ -2287,6 +2343,10 @@ export function createData(config: CreateDataInput) {
|
|||
invalidate(sessionID: string) {
|
||||
sync.invalidate(`job:${sessionID}`)
|
||||
},
|
||||
running() {
|
||||
return Object.values(store.job)
|
||||
},
|
||||
syncRunning: syncRunningJobs,
|
||||
},
|
||||
location: {
|
||||
info(ref?: LocationRef) {
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ function setup() {
|
|||
fetch: async (input, init) => {
|
||||
const url = new URL((input instanceof Request ? input : new Request(input, init)).url)
|
||||
if (!url.pathname.includes("/job")) return Response.json({ data: [] })
|
||||
expect(url.searchParams.get("sessionID")).toBe("ses_root")
|
||||
expect([null, "ses_root"]).toContain(url.searchParams.get("sessionID"))
|
||||
expect(url.searchParams.get("status")).toBe("running")
|
||||
requests++
|
||||
const list = Promise.withResolvers<JobInfo[]>()
|
||||
|
|
@ -117,3 +117,25 @@ test("re-lists on reconnect, pruning jobs that settled while away, and forgets a
|
|||
dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("the server-wide list and a tree's list share the store without wiping each other", async () => {
|
||||
const { data, dispose, ids, respond } = setup()
|
||||
try {
|
||||
const synced = data.job.sync("ses_root")
|
||||
await respond([job("job_a"), job("job_b")])
|
||||
await synced
|
||||
const running = data.job.syncRunning()
|
||||
await respond([job("job_b"), job("job_other", "running", "ses_other")])
|
||||
await running
|
||||
expect(ids()).toEqual(["job_b"])
|
||||
expect(data.job.running().map((item) => item.id)).toEqual(["job_b", "job_other"])
|
||||
|
||||
data.job.invalidate("ses_root")
|
||||
const resynced = data.job.sync("ses_root")
|
||||
await respond([job("job_b")])
|
||||
await resynced
|
||||
expect(data.job.running().map((item) => item.id)).toEqual(["job_b", "job_other"])
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue