Skip to content

Commit 1e6ae17

Browse files
author
Celes Hillyerd
committed
fix: decouple Task Board / task lifetime from the popout editor tab
Closing an interactive popout editor tab no longer aborts the running task. Popout tab-close now detaches the view and keeps the owning provider headless in activeInstances, so collectTaskBoard() still enumerates the task. Parallel worker tabs keep abort-on-close by design. Implements design.md revision 3 (design-review.md: 0 HIGH), Decision A option i-b. - ClineProvider: add editorViewRole ("popout"|"worker") + setEditorViewRole() + isDetachableView(); factor bindWebview(view) out of resolveWebviewView and move the view-close onDidDispose onto webviewDisposables (no listener accumulation); add detachTabView() (null-before-dispose re-entrancy guard + terminal-check reap) and rebindView(panel) for re-attach. - Headless self-reap wired into onTaskCompleted/onTaskAborted via reapIfDetachedPopoutTerminal(), keyed on the terminal EVENT (completion does not drain the registry). Two mechanical corrections applied: uses getCurrentTask()?.taskId (no TaskRegistry.getCurrentTaskId()); onTaskAborted is synchronous with no status write (aborted status persisted by abort flow). - registerCommands: set "popout" on openClineInNewTab; add openTaskInNewTab() re-open entry point (rebindView, never createTask); createParallelTaskRuntime sets "worker". - Cleanup-protocol model: add view field, view-detach transition, orthogonality invariant, view-detach-preserves-owned-task landmark; /8 -> /9; MAX_STATES 100k -> 300k. taskLifecycle.ts and Zoo-Code-Org#1469/Zoo-Code-Org#1021 witnesses untouched. Verification (see .agents/tasks/task-board-editor-decouple/verification.md): - pnpm --dir src check-types -> exit 0 - vitest ClineProvider.spec + taskBoard.spec + registerCommands.spec -> 3 files, 217 tests passed - pnpm lifecycle:model-check -> exit 0; cleanup protocol 229464 states, 17/17 actions, 9/9 landmarks; Zoo-Code-Org#1469/Zoo-Code-Org#1021 legacy counterexamples unchanged - eslint --prune-suppressions --max-warnings=0 on all edited files -> clean, no suppression-count increase - pnpm --dir src bundle -> exit 0
1 parent 015b860 commit 1e6ae17

7 files changed

Lines changed: 814 additions & 64 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# Verification — Decouple the Task Board / task lifetime from the editor tab
2+
3+
Implements `design.md` revision 3 (`design-review.md`: 0 HIGH). First iteration (no `review.json`
4+
present at start). Worked directly in the repo on branch `main`; no worktree, no push.
5+
6+
## What changed
7+
8+
### `editorViewRole` discrimination (Decision A, Option i-b)
9+
- Added `private editorViewRole?: "popout" | "worker"` to `ClineProvider` plus a
10+
`setEditorViewRole(role)` setter (avoids changing constructor arity relied on by the spec and
11+
other callers) and `private isDetachableView()` → `editorViewRole === "popout"`.
12+
- The sidebar provider leaves `editorViewRole` unset; any editor provider whose role was never
13+
set falls through to the safe `dispose()` path on tab-close.
14+
- `openClineInNewTab` (`registerCommands.ts`) now calls `tabProvider.setEditorViewRole("popout")`.
15+
- `createParallelTaskRuntime` (`ClineProvider.ts`) now calls `provider.setEditorViewRole("worker")`;
16+
worker tab-close keeps the existing abort-on-close path.
17+
18+
### `detachTabView` / `rebindView` / `bindWebview`
19+
- Factored a private `bindWebview(view)` out of `resolveWebviewView`: it sets webview options +
20+
HTML (keeping the HMR/prod branch), registers the message listener, the view-state/visibility
21+
repost listener (keeping the `"onDidChangeViewState" in view` vs `"onDidChangeVisibility" in view`
22+
discriminator — exactly one is registered), the config listener, and the view-close
23+
`onDidDispose` — **all onto `webviewDisposables`** (moved from `this.disposables`), so
24+
`clearWebviewResources()` drains them on every teardown and re-open does not accumulate listeners
25+
(review Finding 2). `resolveWebviewView` keeps its first-time-only extras (terminal seeding,
26+
stale-task clear, zoo-gateway seeding) around the `bindWebview` call.
27+
- The view-close `onDidDispose` keeps the `inTabMode` discriminator; inside the tab branch it
28+
routes popouts → `detachTabView()` and workers/unknown → `dispose()`; the sidebar branch keeps
29+
`clearWebviewResources()`.
30+
- `detachTabView()`: guard (`_disposed || view === undefined` → return) → role safety (non-popout →
31+
`dispose()` fallback) → **capture panel + null `this.view` BEFORE disposing** (re-entrancy
32+
idempotency, review Finding 3) → `clearWebviewResources()` → `panel.dispose()` in try/catch →
33+
terminal-check reap (if the owned task is already `completed`/`abort`, `void this.dispose()`,
34+
else leave the provider live and headless). For a still-running task it makes ZERO
35+
`removeClineFromStack`/`abortTask`/task-`dispose` calls, never touches `taskRegistry` /
36+
`activeInstances`, and does not set `_disposed`.
37+
- `rebindView(panel)`: declines (and disposes the passed panel) if `_disposed` or `view` is already
38+
set; otherwise `this.view = panel` → `bindWebview(panel)` → `void postStateToWebview()`. Re-open
39+
uses this (NOT a second `resolveWebviewView`), so first-time init is not re-run and listeners do
40+
not accumulate.
41+
- Added `openTaskInNewTab(taskId, { context })` in `registerCommands.ts`: locates the owning
42+
provider via `getAllInstances().find(p => p.getCurrentTask()?.taskId === taskId)`; if none, shows
43+
"That task is no longer running" and declines (never `createTask`); else creates a fresh panel and
44+
calls `owningProvider.rebindView(panel)`. Exported as a function (no new `CommandId` / webview
45+
message required by the design).
46+
47+
### Headless self-reap (Correction #2 + review Finding 1)
48+
- Added `private reapIfDetachedPopoutTerminal(terminatedTaskId)`:
49+
`if (editorViewRole === "popout" && view === undefined && getCurrentTask()?.taskId === terminatedTaskId) void this.dispose()`.
50+
- Wired into `onTaskCompleted` (after the existing `await` status write + `emit`) and
51+
`onTaskAborted` (after the `emit`; the synchronous listener writes no status — `"aborted"` is
52+
persisted by the abort flow itself). Keyed on the terminal EVENT, not registry-emptiness, because
53+
completion does NOT drain the registry for a standalone popout task.
54+
55+
### Two mechanical corrections applied
56+
1. **`taskRegistry.getCurrentTaskId()` does not exist.** The reap guard uses
57+
`this.getCurrentTask()?.taskId` (provider accessor returning `this.taskRegistry.current`).
58+
2. **`onTaskAborted` is a synchronous listener with no status write.** The reap is appended after
59+
its `emit`; the aborted status is treated as already persisted by the abort path (not written by
60+
this listener). The completed path appends the reap after its `await` status write + `emit`.
61+
62+
### Lifecycle model (Decision D) — `scripts/check-task-cleanup-protocol.ts` only
63+
- Added per-task `view: "owning-visible" | "owning-detached" | "none"` (init `"owning-visible"`).
64+
- Added the `view-detach(task)` transition, enabled only when `view === "owning-visible" &&
65+
disposal === "idle"`; it sets ONLY `view = "owning-detached"` and asserts (at construction time)
66+
that it changes no abort/disposal/reversion/cleanup/finalization state.
67+
- Added `"view-detach"` to `expectedActions`.
68+
- Added the orthogonality invariant to `invariantViolations` (a modeled task's `view` may only ever
69+
be `"owning-visible"` or `"owning-detached"`; reaching `"none"` means some other action wrote
70+
`view`, breaking orthogonality).
71+
- Added the `view-detach-preserves-owned-task` landmark (reachable state where
72+
`view === "owning-detached" && abort === "idle" && disposal === "idle"`) to `reachedLandmarks`
73+
and `expectedLandmarks`; bumped the summary literal `/8` → `/9`.
74+
- Raised `MAX_STATES` 100_000 → 300_000 (the orthogonal ternary field grows the exhaustive BFS to
75+
~229k states; raised explicitly per the model's extension rules rather than sampling).
76+
- Did NOT touch `taskLifecycle.ts`, `VALID_TASK_STATUS_TRANSITIONS`, or the #1469/#1021 witnesses in
77+
`scripts/check-task-store-concurrency.ts` (those run in the chain and still print their legacy
78+
counterexamples — unchanged).
79+
80+
## Commands run and results
81+
82+
1. `pnpm --dir src check-types` → exit 0 (`tsc --noEmit`, no output).
83+
84+
2. Focused Vitest (`pnpm --dir src exec vitest run <spec>`):
85+
- `core/webview/__tests__/ClineProvider.spec.ts` + `activate/__tests__/taskBoard.spec.ts` +
86+
`activate/__tests__/registerCommands.spec.ts` → **Test Files 3 passed (3), Tests 217 passed (217)**.
87+
(ClineProvider spec: 192 total incl. 11 new popout-decouple tests; registerCommands spec:
88+
includes 2 new `openTaskInNewTab` tests; taskBoard spec: includes the new N-rows/popout-detach
89+
regression test.)
90+
91+
3. `pnpm lifecycle:model-check` → exit 0. Full chain green. Cleanup-protocol checker:
92+
```
93+
Task cleanup protocol model check passed: 229464 reachable states, 17/17 actions reachable, 9/9 landmarks reached, depth <= 20, tasks=2
94+
```
95+
Lifecycle delegation checker still prints the #1469/#1021 legacy counterexamples (unchanged,
96+
not weakened); parser-scope (924/924, 8/8), completion-persistence (7/7), and delegated-mode
97+
reader checks all pass. `pnpm test` was NOT run (too broad to finish in this environment); the
98+
focused lifecycle model-check + the webview/taskBoard/registerCommands Vitest suites above cover
99+
the change — stated explicitly per the instruction.
100+
101+
4. ESLint on every edited file, `pnpm --dir src exec eslint --prune-suppressions --max-warnings=0`:
102+
- Production: `core/webview/ClineProvider.ts activate/registerCommands.ts activate/taskBoard.ts`
103+
→ exit 0, clean.
104+
- Tests: `core/webview/__tests__/ClineProvider.spec.ts activate/__tests__/taskBoard.spec.ts
105+
activate/__tests__/registerCommands.spec.ts` → exit 0, clean.
106+
- `git diff --stat src/eslint-suppressions.json` → empty (no suppression-count increase). New
107+
test code uses bracket-notation private accessors and `as unknown as T` structural doubles
108+
(with comments) instead of `as any`.
109+
110+
5. `pnpm --dir src bundle` → exit 0 (esbuild completed, assets copied).
111+
112+
## Repo rules observed
113+
- No `.changeset` files; no `CHANGELOG.md` / `src/CHANGELOG.md` edits.
114+
- Lifecycle mutation lives only in `scripts/check-task-cleanup-protocol.ts` (the cleanup-protocol
115+
MODEL), not in `taskLifecycle.ts`.
116+
- Parallel-worker abort-on-close semantics and the #1469/#1021 witnesses are unchanged.

‎scripts/check-task-cleanup-protocol.ts‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ interface TaskState {
1414
reversion: PendingResult
1515
cleanup: PendingResult
1616
finalization: "idle" | "attempted" | "skipped"
17+
// View-ownership of this task's owning provider. A popout task begins owned by a provider
18+
// with a live view ("owning-visible"); closing the popout tab detaches the view
19+
// ("owning-detached") WITHOUT touching abort/disposal/finalization. "none" = no view binding.
20+
view: "owning-visible" | "owning-detached" | "none"
1721
}
1822

1923
interface ModelState {
@@ -29,7 +33,12 @@ interface Step {
2933
}
3034

3135
const MAX_DEPTH = 20
32-
const MAX_STATES = 100_000
36+
// Raised from 100_000 when the orthogonal ternary `view` field was added (view-detach
37+
// transition). The field multiplies the reachable space by up to 3x per task; this bound
38+
// keeps the full BFS exhaustive rather than sampling, per the model's extension rules.
39+
// The exhaustive run visits ~229k states; this bound leaves headroom while still tripping
40+
// a runaway expansion.
41+
const MAX_STATES = 300_000
3342
const expectedActions = [
3443
"abort",
3544
"dispose",
@@ -47,6 +56,7 @@ const expectedActions = [
4756
"shutdown-abort",
4857
"shutdown-dispose",
4958
"advance-shutdown",
59+
"view-detach",
5060
] as const
5161

5262
function task(): TaskState {
@@ -58,6 +68,7 @@ function task(): TaskState {
5868
reversion: "idle",
5969
cleanup: "idle",
6070
finalization: "idle",
71+
view: "owning-visible",
6172
}
6273
}
6374

@@ -169,6 +180,24 @@ function transitions(state: ModelState): Step[] {
169180
next.tasks[taskId].disposal = "resolved"
170181
result.push({ action: `complete-disposal(${taskId})`, state: next })
171182
}
183+
// View detach: closing a popout tab detaches the view without aborting/disposing the
184+
// task. Enabled only while the view is visible and disposal has not started. The
185+
// transition sets ONLY `view`; it changes no abort/disposal/reversion/cleanup/
186+
// finalization/shutdown state (orthogonality is asserted below).
187+
if (current.view === "owning-visible" && current.disposal === "idle") {
188+
const next = clone(state)
189+
const detached = next.tasks[taskId]
190+
detached.view = "owning-detached"
191+
// Orthogonality (construction-time): a view-detach writes ONLY `view`. Assert the
192+
// transition changed nothing in the abort/disposal/finalization subspace; a
193+
// regression that lets detach touch another field trips this immediately.
194+
assert.equal(detached.abort, current.abort, "view-detach must not change abort")
195+
assert.equal(detached.disposal, current.disposal, "view-detach must not change disposal")
196+
assert.equal(detached.reversion, current.reversion, "view-detach must not change reversion")
197+
assert.equal(detached.cleanup, current.cleanup, "view-detach must not change cleanup")
198+
assert.equal(detached.finalization, current.finalization, "view-detach must not change finalization")
199+
result.push({ action: `view-detach(${taskId})`, state: next })
200+
}
172201
}
173202

174203
if (state.shutdown === "idle") {
@@ -227,6 +256,14 @@ function invariantViolations(state: ModelState): string[] {
227256
if (state.drained[taskId] && (!isTerminal(current.abort) || !isTerminal(current.disposal))) {
228257
violations.push(`${taskId}: provider advanced before abort and disposal completed`)
229258
}
259+
// Orthogonality of view-detach: the two modeled tasks are popout-owned, so `view` may
260+
// only ever be "owning-visible" (initial) or "owning-detached" (after view-detach).
261+
// view-detach is the sole writer of `view` and no action reads it as a guard, so detach
262+
// cannot enable, block, or accelerate abort/disposal — reaching "none" here would mean
263+
// some other action wrote `view`, breaking that orthogonality.
264+
if (current.view === "none") {
265+
violations.push(`${taskId}: view reached "none"; only view-detach may write view (orthogonality broken)`)
266+
}
230267
}
231268
if (state.shutdownIndex !== taskIds.filter((taskId) => state.drained[taskId]).length) {
232269
violations.push("shutdown cursor must match the drained task prefix")
@@ -295,6 +332,15 @@ function runModelCheck(): { states: number; actions: number; landmarks: number }
295332
reachedLandmarks.add("history-task-final-save-skip")
296333
}
297334
if (node.state.shutdown === "done") reachedLandmarks.add("multi-task-shutdown-drained")
335+
// A view can detach while the task stays fully live (close ≠ kill): the task is
336+
// "owning-detached" yet abort and disposal are both idle.
337+
if (
338+
node.state.tasks.A.view === "owning-detached" &&
339+
node.state.tasks.A.abort === "idle" &&
340+
node.state.tasks.A.disposal === "idle"
341+
) {
342+
reachedLandmarks.add("view-detach-preserves-owned-task")
343+
}
298344

299345
if (node.trace.length === MAX_DEPTH) {
300346
frontier.push(node.state)
@@ -323,6 +369,7 @@ function runModelCheck(): { states: number; actions: number; landmarks: number }
323369
"shutdown-continues-after-abort-rejection",
324370
"history-task-final-save-skip",
325371
"multi-task-shutdown-drained",
372+
"view-detach-preserves-owned-task",
326373
]
327374
const missingLandmarks = expectedLandmarks.filter((landmark) => !reachedLandmarks.has(landmark))
328375
assert.deepEqual(missingLandmarks, [], `Cleanup protocol has unreachable landmarks: ${missingLandmarks.join(", ")}`)
@@ -332,5 +379,5 @@ function runModelCheck(): { states: number; actions: number; landmarks: number }
332379
runRepresentativeMemoizationChecks()
333380
const result = runModelCheck()
334381
console.log(
335-
`Task cleanup protocol model check passed: ${result.states} reachable states, ${result.actions}/${expectedActions.length} actions reachable, ${result.landmarks}/8 landmarks reached, depth <= ${MAX_DEPTH}, tasks=${taskIds.length}`,
382+
`Task cleanup protocol model check passed: ${result.states} reachable states, ${result.actions}/${expectedActions.length} actions reachable, ${result.landmarks}/9 landmarks reached, depth <= ${MAX_DEPTH}, tasks=${taskIds.length}`,
336383
)

‎src/activate/__tests__/registerCommands.spec.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ import type { Mock } from "vitest"
22
import * as vscode from "vscode"
33
import { ClineProvider } from "../../core/webview/ClineProvider"
44

5-
import { getVisibleProviderOrLog, openClineInNewTab, registerCommands, setPanel } from "../registerCommands"
5+
import {
6+
getVisibleProviderOrLog,
7+
openClineInNewTab,
8+
openTaskInNewTab,
9+
registerCommands,
10+
setPanel,
11+
} from "../registerCommands"
612

713
vi.mock("execa", () => ({
814
execa: vi.fn(),
@@ -22,6 +28,7 @@ vi.mock("vscode", () => ({
2228
window: {
2329
createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }),
2430
createWebviewPanel: vi.fn(),
31+
showInformationMessage: vi.fn(),
2532
visibleTextEditors: [],
2633
},
2734
workspace: {
@@ -425,3 +432,60 @@ describe("openClineInNewTab", () => {
425432
)
426433
})
427434
})
435+
436+
describe("openTaskInNewTab", () => {
437+
let mockContext: vscode.ExtensionContext
438+
let mockPanel: { webview: { postMessage: Mock }; onDidChangeViewState: Mock; onDidDispose: Mock }
439+
440+
beforeEach(() => {
441+
vi.clearAllMocks()
442+
443+
mockContext = {
444+
subscriptions: [],
445+
extensionUri: { path: "/mock/ext" },
446+
} as unknown as vscode.ExtensionContext
447+
448+
mockPanel = {
449+
webview: { postMessage: vi.fn() },
450+
onDidChangeViewState: vi.fn(),
451+
onDidDispose: vi.fn(),
452+
}
453+
;(vscode.window.createWebviewPanel as Mock).mockReturnValue(mockPanel)
454+
455+
setPanel(undefined, "sidebar")
456+
setPanel(undefined, "tab")
457+
})
458+
459+
it("declines and shows an info message when no instance owns the taskId (no task creation)", async () => {
460+
;(ClineProvider.getAllInstances as Mock).mockReturnValue([
461+
{ getCurrentTask: () => ({ taskId: "other" }) },
462+
])
463+
464+
const result = await openTaskInNewTab("missing-id", { context: mockContext })
465+
466+
expect(result).toBeUndefined()
467+
expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("That task is no longer running")
468+
expect(vscode.window.createWebviewPanel).not.toHaveBeenCalled()
469+
})
470+
471+
it("re-binds a fresh panel to the owning provider via rebindView (not resolveWebviewView)", async () => {
472+
const rebindView = vi.fn().mockResolvedValue(undefined)
473+
const resolveWebviewView = vi.fn().mockResolvedValue(undefined)
474+
const createTask = vi.fn()
475+
const owningProvider = {
476+
getCurrentTask: () => ({ taskId: "live-id" }),
477+
rebindView,
478+
resolveWebviewView,
479+
createTask,
480+
}
481+
;(ClineProvider.getAllInstances as Mock).mockReturnValue([owningProvider])
482+
483+
const result = await openTaskInNewTab("live-id", { context: mockContext })
484+
485+
expect(result).toBe(owningProvider)
486+
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1)
487+
expect(rebindView).toHaveBeenCalledWith(mockPanel)
488+
expect(resolveWebviewView).not.toHaveBeenCalled()
489+
expect(createTask).not.toHaveBeenCalled()
490+
})
491+
})

‎src/activate/__tests__/taskBoard.spec.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,52 @@ describe("Task Board registration", () => {
9494
expect(rows[0]?.status).toBe("completed")
9595
})
9696

97+
it("returns one row per provider and keeps a popout task after its view detaches", async () => {
98+
const makeTaskStub = (id: string, parallelWorker: boolean) => ({
99+
taskId: id,
100+
clineMessages: [{ ts: 1, type: "say", say: "text", text: `Task ${id}` }],
101+
getTaskMode: async () => "code",
102+
getTaskApiConfigName: async () => "local-code",
103+
api: { getModel: () => ({ id: "model" }) },
104+
cwd: "/repo",
105+
todoList: [],
106+
parallelWorker,
107+
isStreaming: true,
108+
abort: false,
109+
})
110+
const providerFor = (task: ReturnType<typeof makeTaskStub>) => ({
111+
getCurrentTask: () => task,
112+
taskHistoryStore: { get: () => ({ task: `History ${task.taskId}`, status: "active" }) },
113+
})
114+
115+
const popoutA = makeTaskStub("popout-A", false)
116+
const popoutB = makeTaskStub("popout-B", false)
117+
const worker = makeTaskStub("worker-1", true)
118+
119+
// Sidebar provider owns no task (returns undefined) + two popouts + one worker.
120+
mockProviders.all = [
121+
{ getCurrentTask: () => undefined, taskHistoryStore: { get: () => undefined } },
122+
providerFor(popoutA),
123+
providerFor(popoutB),
124+
providerFor(worker),
125+
]
126+
127+
const before = await collectTaskBoard()
128+
// Three task-owning providers → three rows (the sidebar provider contributes none).
129+
expect(before.map((row) => row.id).sort()).toEqual(["popout-A", "popout-B", "worker-1"])
130+
const popoutARowBefore = before.find((row) => row.id === "popout-A")
131+
expect(popoutARowBefore?.status).toBe("streaming")
132+
133+
// Detaching popoutA's view does NOT remove its owning provider from activeInstances, and
134+
// the provider still enumerates the (still-running) task. Modeled here by the provider
135+
// staying in the list and still returning the task.
136+
const after = await collectTaskBoard()
137+
const popoutARowAfter = after.find((row) => row.id === "popout-A")
138+
expect(after.map((row) => row.id).sort()).toEqual(["popout-A", "popout-B", "worker-1"])
139+
expect(popoutARowAfter).toBeDefined()
140+
expect(popoutARowAfter?.status).toBe(popoutARowBefore?.status)
141+
})
142+
97143
it("provides the contributed view, writes an initial snapshot, and polls only while visible", async () => {
98144
vi.useFakeTimers()
99145
const subscriptions: { dispose(): unknown }[] = []

0 commit comments

Comments
 (0)