refactor(tasks): 后台任务改读宿主客户端 jobs 服务,删除自建三条路由

- 新增 src/client/jobs-client.ts:结构探测 ctx.jobs(watchRows / observe /
  state / kill),引用计数的按会话 roster 订阅、只观测展开的那一行、
  跨树去重(无主任务归到承载它的被观测会话,树外 owner 丢弃)。
- 抽屉与输出浮窗改读该服务:行来自推送 roster(状态 / 时长 / owner / 进度),
  输出面换 TerminalBlock 显示宿主为观察者流的保留输出(gapBefore → 截断提示、
  error → 失败提示),kill 走 jobs.kill(owner, jobId),两击确认不变。
- 自动激活(use-host-feeds)改骑同一条推送 roster;detectNewJob 增加
  「观测起点时钟」参数,避免「页面打开时已在跑的任务」被当成新工作。
- 删除 src/jobs-routes.ts(+ tests/jobs-routes.spec.ts)、index.ts 的三条路由、
  api.jobsList/jobOutput/jobKill 与 JobOutputResult、context-types 的
  SidebarJobsService(换成 SidebarClientJobsService/SidebarJobsSnapshot/
  SidebarObservedJob 镜像,SidebarJobView 补 owner/progress)、
  页面里的 jobs.list 轮询与 collectTreeJobs。
- 三个 spec 改用假 ctx.jobs 服务(jobs-view 14 例 / 自动激活 12 例 /
  页面 20 例):观测只在展开行、切换与关闭释放观测、watch 隐藏时不建立、
  卸载时全部释放、无服务时不渲染任务面。

验证:typecheck / lint 通过;pnpm test 1240 passed / 9 skipped;pnpm build + pack 通过。

(cherry picked from commit 7d9b82e73190218f05910433ed520cb90e4d4ab2)
This commit is contained in:
Menghuan1918 committed 2026-09-27 22:18:35 +08:00
1 parent f584b67813
commit 48294d336e
16 files changed
+763 -1050

No files matched your search

+86 -41
View File
@@ -17,8 +17,8 @@
* (`ctx.sidebarRight.mounted`): the session-list snapshot never carried a
* current-session field, so the park gate used to read a phantom one and was
* permanently false. Background jobs are likewise no longer mirrored into that
* snapshot — the trigger polls the plugin's `jobs.list` route, so a job is
* delivered by mutating the stubbed registry and advancing the poll.
* snapshot — they arrive as whole-set rosters PUSHED by the host's client jobs
* service, so a job is delivered by publishing a frame.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -37,7 +37,13 @@ import {
type SidebarSurface,
type TabComponentProps,
} from '../src/client/service.ts'
import type { Context, SidebarJobView, SidebarSessionList } from '../src/context-types.ts'
import type {
Context,
SidebarClientJobsService,
SidebarJobsSnapshot,
SidebarJobView,
SidebarSessionList,
} from '../src/context-types.ts'
class FakeWebSocket {
onmessage: ((event: { data: unknown }) => void) | null = null
@@ -162,15 +168,58 @@ interface MountedSidebar {
surface: NativeSurfaceSpy
column: NativeColumnSpy
sessionId: string
/** The stubbed `jobs.list` registry, keyed by OWNER session (mutable). */
jobs: Record<string, SidebarJobView[]>
/** The client jobs feed the auto-open trigger watches (push rosters). */
jobs: JobsFeed
unmount: () => void
}
/**
* The host client jobs service double: `watchRows` opens a reference-counted
* roster stream and `publish` pushes a whole-set frame through the same
* subscribe/getSnapshot pair the trigger reads.
*/
interface JobsFeed {
service: SidebarClientJobsService
watched: string[]
released: string[]
publish(sessionId: string, jobs: readonly SidebarJobView[]): void
}
function makeJobsFeed(): JobsFeed {
let snapshot: SidebarJobsSnapshot = { rows: {}, observed: {} }
const listeners = new Set<() => void>()
const feed: JobsFeed = {
watched: [],
released: [],
service: {
state: {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
},
watchRows(sessionId: string) {
feed.watched.push(sessionId)
return () => { feed.released.push(sessionId) }
},
observe: () => () => {},
kill: async () => {},
},
publish(sessionId, jobs) {
snapshot = { rows: { ...snapshot.rows, ...(jobs.length === 0 ? {} : { [sessionId]: [...jobs] }) }, observed: {} }
if (jobs.length === 0) {
const { [sessionId]: _dropped, ...rest } = snapshot.rows
snapshot = { rows: rest, observed: {} }
}
for (const listener of [...listeners]) listener()
},
}
return feed
}
let sessionSeq = 0
const mounted: MountedSidebar[] = []
/** Owner sessions the stubbed `jobs.list` route was read for. */
const jobListReads: string[] = []
function setViewport(width: number): void {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: width })
@@ -190,21 +239,9 @@ function mountSidebar(
},
}
const feed = makeSessionFeed(initial)
const jobs: Record<string, SidebarJobView[]> = {}
// The jobs feed is polled through the plugin's own route (0.1.7 removed the
// snapshot's jobs mirror): the registry below is what a test mutates.
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
const method = String(url).split('/').pop()
if (method !== 'jobs.list') throw new Error(`unexpected fetch ${String(url)}`)
const body = JSON.parse(String(init?.body)) as { sessionId?: string }
const owner = body.sessionId ?? ''
jobListReads.push(owner)
return {
ok: true,
status: 200,
json: async () => ({ ok: true, value: { jobs: jobs[owner] ?? [] } }),
} as unknown as Response
})
// Background jobs arrive through the host's own client jobs service
// (`ctx.jobs`): the feed below is what a test pushes rosters into.
const jobs = makeJobsFeed()
const store = createSidebarStore()
store.setPrefs({ ...store.getPrefs(), autoOpenSubagent: true, autoOpenJobs: true })
store.setSession(sessionId)
@@ -221,7 +258,7 @@ function mountSidebar(
betterSidebar: service,
get: (name: string) => name === 'betterSidebar'
? service
: name === 'sidebarRight' ? column.face : undefined,
: name === 'sidebarRight' ? column.face : name === 'jobs' ? jobs.service : undefined,
} as unknown as Context
const container = document.createElement('div')
document.body.append(container)
@@ -280,19 +317,20 @@ function flushSubagentDebounce(): void {
}
/**
* Deliver one new job through the polled jobs route: let the mount-time
* baseline read land, register the job, then advance one poll interval.
* Deliver one new job: the roster frame the host's client service pushes. The
* job's start stamp is AFTER the watch began, which is what makes it "new
* work" rather than a job that was already running when the page mounted.
*/
async function publishJob(sidebar: MountedSidebar): Promise<void> {
await flushFeeds()
sidebar.jobs[sessionIdOf(sidebar)] = [{
sidebar.jobs.publish(sessionIdOf(sidebar), [{
id: 'bash-1',
kind: 'bash',
label: 'sleep 30',
status: 'running',
startedAt: 1_000,
}]
await act(async () => { await vi.advanceTimersByTimeAsync(2_000) })
startedAt: Date.now() + 1,
}])
await flushFeeds()
}
/** The conversation the sidebar is bound to (its own store's session). */
@@ -394,32 +432,39 @@ describe('Sidebar background-activity auto-activation (#162)', () => {
it('a page that loads with jobs already running never triggers; the next NEW job does', async () => {
const sidebar = mountSidebar(1024)
// The conversation is already running work when the sidebar mounts: the
// first successful read only ARMS the baseline, it is never "new work".
sidebar.jobs[sidebar.sessionId] = [{
// first frame only ARMS the baseline (and the watch clock filters a job
// whose start stamp predates it), so it is never "new work".
sidebar.jobs.publish(sidebar.sessionId, [{
id: 'bash-0',
kind: 'bash',
label: 'already running',
status: 'running',
startedAt: 500,
}]
startedAt: Date.now() - 5_000,
}])
await flushFeeds()
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
expect(sidebar.surface.opens).toEqual([])
// A second, genuinely new job id is what surfaces the Tasks page.
sidebar.jobs[sidebar.sessionId] = [
...sidebar.jobs[sidebar.sessionId] ?? [],
{ id: 'bash-1', kind: 'bash', label: 'sleep 30', status: 'running', startedAt: 1_000 },
]
await act(async () => { await vi.advanceTimersByTimeAsync(2_000) })
sidebar.jobs.publish(sidebar.sessionId, [
{
id: 'bash-0',
kind: 'bash',
label: 'already running',
status: 'running',
startedAt: Date.now() - 5_000,
},
{ id: 'bash-1', kind: 'bash', label: 'sleep 30', status: 'running', startedAt: Date.now() + 1 },
])
await flushFeeds()
expectNativeTasksOpen(sidebar, sidebar.sessionId)
})
it('a session switch re-arms the job baseline instead of firing on the new session\'s jobs', async () => {
const sidebar = mountSidebar(1024)
sidebar.jobs['child'] = [{ id: 'bash-9', kind: 'bash', label: 'child work', status: 'running', startedAt: 10 }]
sidebar.jobs.publish('child', [
{ id: 'bash-9', kind: 'bash', label: 'child work', status: 'running', startedAt: Date.now() + 1 },
])
switchToChild(sidebar)
await flushFeeds()
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
// The child's pre-existing job belongs to the NEW baseline, not to "new
// work in the session I am looking at" (the baseline resets on session).
expect(sidebar.surface.opens).toEqual([])