@ai-setting/roy-plugin-task-show 2.5.22 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-setting/roy-plugin-task-show",
3
- "version": "2.5.22",
3
+ "version": "2.6.1",
4
4
  "description": "roy-agent plugin: visualize task solving process via tool call flow on a local web service",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/plugin.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@ai-setting/roy-plugin-task-show",
3
- "version": "2.5.22",
3
+ "version": "2.6.1",
4
4
  "type": "tool-plugin",
5
- "description": "v2.4.1: Mermaid zoom now supports click-and-drag pan (Task #2785). After zooming in, users can drag the diagram to view the surrounding canvas area. Implementation: per-container panState/dragState WeakMap (no global state leak); applyTransform(translate+scale) single-source-of-truth for the CSS transform; attachPanHandlers on pointerdown/move/up/cancel with setPointerCapture for off-element drags; pointer cursor switches to grab/grabbing with touch-action: none to prevent native scrolling; reset/zoomReset now also resets pan to (0,0). 14/14 new mermaid-pan tests pass, full suite 558/564 with 6 pre-existing failures unrelated to this commit. v2.4.0: Combines v2.3.0 Combines v2.3.0 (worktree-aware file-tree + unbounded Mermaid zoom, Task #2773) with the v2.3.0 mermaid placeholder expansion (Task #2771). Sidebar + endpoint scope git ls-files to session.context.worktree (fallback process.cwd()); Mermaid zoom-in is no longer capped at 3.0\u00d7; .mermaid placeholder is now min-height: 2400px and .mermaid-zoom-stage is min-width: 6400px / min-height: 2400px (5\u00d7 base, via --mermaid-placeholder-multiplier CSS custom property) so dense diagrams get enough canvas to pan/zoom comfortably. v2.3.0: Worktree-aware file tree sidebar + unbounded Mermaid zoom-in. The file-tree sidebar (and /api/task/:id/file-tree endpoint) now scope git ls-files to session.context.worktree when the host (task:before.create / task:after.create payload) supplies a worktree path, so the sidebar shows the files the agent is actually editing instead of the plugin process cwd. New resolveWorktreePath helper in src/file-tree.ts returns session.context.worktree (trimmed, with empty/non-string guard) or falls back to process.cwd() for backward compatibility with pre-v2.3.0 hosts. TypeScript: TaskSession gains an optional context?: { worktree?: string } field. TaskShowServer exposes getCollector() so tests can seed sessions with context.worktree set. The Mermaid zoom toolbar (introduced in v2.0.8) no longer caps zoom-in at 3.0\u00d7 \u2014 the ZOOM_MAX constant is REMOVED and clampZoom only enforces ZOOM_MIN=0.25, so dense diagrams remain readable on high-DPI monitors when the user wants to zoom way in. ZOOM_MIN stays in place so zoom-out still bottoms out before rendering a black screen. New tests: test/file-tree-worktree.test.ts (10 cases \u2014 resolveWorktreePath edges, SSR scope, endpoint scope, fallback), test/mermaid-zoom-unlimited.test.ts (8 cases \u2014 source guard, behaviour at 6\u00d7/10\u00d7/50\u00d7, lower-bound preserved), test/mermaid-placeholder-size.test.ts (7 cases \u2014 min-height/min-width 5\u00d7 checks, transform-origin preserved, --mermaid-placeholder-multiplier hint). v2.3.0: Major visual overhaul of the per-task detail page \u2014 VS Code-style tool-call browser powered by Monaco Editor + LCS-based diff + project file tree with mermaid-driven navigation. The detail page now renders a 2-column layout: a sticky left sidebar with the project's git-tracked file tree (chevron-toggle directories, `is-affected` highlight for files touched by the current task), and a main column with the existing Mermaid + stats + toolcalls table + a new dedicated `<section id=\"tool-call-detail-panel\">` that hosts the LCS diff body + Monaco container for the currently-selected tool call. The legacy inline `<details class=\"diff-panel\">` (naive split-and-filter, prone to mis-tagging context lines) is replaced by `<ol class=\"diff-body\">` with proper added/removed/context markers driven by a real LCS dynamic-programming table (`computeDiff()` in `src/tool-call-detail.ts`). Tool calls with a file path get a Monaco Editor placeholder (`<div class=\"monaco-editor\" data-file-path=\"...\" data-language=\"...\">`) which the client-side `public/tool-call-detail.js` lazy-loads from `cdn.jsdelivr.net/npm/monaco-editor@0.45.0` the first time the user clicks a tool row. The Mermaid `__toolClick(toolId)` callback now drives THREE things: (a) the existing row scroll + highlight (preserved from v1.x), (b) the dedicated detail panel re-renders with the matching call, (c) the file-tree sidebar highlights the corresponding file (when `data-file-path` is present). New `GET /api/task/:id/file-tree` endpoint serves the git-tracked file list (`{ files: string[] }`) with a 30-second in-memory TTL + 8-entry FIFO bound. New modules: `src/file-tree.ts` (pure data layer: `buildFileTree / extractAffectedPaths / findNodeByPath / collectAllPaths / gitLsFiles / parseLsFiles`), `src/tool-call-detail.ts` (SSR + LCS diff + HTML escaping), `public/file-tree.js` (vanilla JS hydrator with chevron toggle + keyboard navigation + scrollIntoView), `public/tool-call-detail.js` (Monaco AMD loader + `__toolClick` wrapper + file-content fetch). New tests: `test/file-tree.test.ts` (21 cases \u2014 empty/single/nested/dedup/sort/depth/parseLsFiles/gitLsFiles), `test/tool-call-detail.test.ts` (22 cases \u2014 LCS diff edges, HTML escape, path aliases, summary stats), `test/tool-call-detail-server-integration.test.ts` (7 cases \u2014 SSR HTML contracts + endpoint), `test/tool-call-detail-jsdom.test.ts` (7 cases \u2014 client-side hydrators). v1.2.0: CSS context & packaged release hotfix. The plugin's public assets (notably `public/style.css`) and runtime adapters now correctly resolve relative to the installed package directory even when consumed via the published npm tarball. The session-scoped `TaskSessionStore` now preserves the full host session context (parent-child task links, plugin-handle id, env scope) across render cycles \u2014 previously the session was collapsed to its `sessionId` on first load and never refreshed, so the home page lost the \u300csession ancestors\u300d chain and external tasks from outside the current session silently disappeared from the tree. Adds `src/task-metadata.ts` as the single source of truth for the public `Task` shape exposed by `/api/tasks` + `/api/tasks/:id`, including the v1.0.0+ `processDescription` field, and re-exports it through the CLI adapters (`cli-tasks-adapter.ts` + `cli-tasks-tree-adapter.ts`) so the home page tree + the per-task page render against the same metadata contract. Bundles 244-line regression test (`test/context-and-packed-release.test.ts`) that boots the plugin from the **npm-pack** directory (not the repo working tree), spawns `roy-agent tasks get <id> --json`, and asserts (a) `public/style.css` is present and \u2265 64 lines, (b) the `/api/events` SSE endpoint survives a reload, and (c) `task.session` survives a render cycle. v1.1.0: Full Server-Sent Events realtime subscription across 3 event classes (task.created / operation.updated / tool.called) on both the home page and the per-task /task/<id> page. The per-task pipeline now subscribes to /api/events and patches the DOM in place on operation.updated \u2014 no more 5s-poll delay before the user sees a new milestone. The 'Task lifecycle pipeline' header badge is replaced by a 5-state SSE-aware badge (stale / connecting / live / reconnecting / error) so the user can tell at a glance whether real-time updates are flowing, the connection dropped, or 3+ consecutive errors triggered the polling fallback. Legacy boolean `stale` cache-TTL pill and `tool.recorded` event name are preserved for back-compat with v0.9.x / v1.0.0 clients. v1.0.0: First stable release. Replaces the v0.9.x fixture-based verify scripts (which built fake TaskOperationsEnvelope and never invoked the real `roy-agent` CLI, masking regressions in the public-schema `processDescription` field) with a real-CLI scenario test + verify (`test/process-description-real-scenario.test.ts` + `scripts/verify-v100-real-scenario.ts`) that spawns `roy-agent tasks get <id> --operations --json` via `defaultRunner` and asserts the API response carries `processDescription` end-to-end. The 0.9.9 processDescription fix is preserved verbatim \u2014 this release only swaps the verify surface. Visualize the tool call chain of a task on a local web service with real-time SSE updates. v0.9.9: Task lifecycle pipeline on /task/<id> now exposes BOTH the milestone badge AND the \u300c\u8fc7\u7a0b\u63cf\u8ff0\u300d column at a glance \u2014 the server-side `/api/tasks/:id/operations` endpoint exposes `processDescription` on every operation (no longer stripped from the public schema), the client-side `renderPipelineHtml` mirrors the server's `.op-desc-block` + `.op-proc-block` block layout so SSR \u2194 CSR stay in sync, and a long-standing CSS right-side text-truncation bug in the pipeline timeline (long CJK titles overflowing the panel edge) is fixed via `min-width: 0` on `.op-row1` + `overflow-wrap: anywhere` on `.op-title`. v0.9.0: Session-scoped home page (only show tasks created after plugin load + their external ancestors), with per-row \u300c\u663e\u793a\u5168\u90e8\u680f\u4f4d\u300d toggle and lazy-loaded operations timeline; per-task Mermaid labels now correctly render CJK / mixed-Latin / emoji text (encoded as \\uXXXX before emission, decoded by the browser); detail page layout reordered to lifecycle \u2192 pipeline \u2192 stats \u2192 toolcalls \u2192 rawjson. v0.5.0+: page refreshes stream over GET /api/events (Server-Sent Events). Subscribes to tool:before.execute, tool:after.execute, task:before.create, task:after.create, task:after.complete (preferred, 2026-07-10+), and task:after.update (legacy fallback). v0.6.11: Mermaid re-rendering is delegated to a self-contained controller (public/mermaid-renderer.js) that prevents the SVG\u2192raw-source regression on async updates and surfaces recoverable .mermaid-error states. v0.6.12: Task lifecycle pipeline (operations timeline) server now emits data-task-id on the pipeline section; client preserves it on swap, so the page actually fetches /api/tasks/<id>/operations and renders the 7-op timeline (previously silently bailed). v0.7.0: Home page redesigned as a hierarchical task tree (driven by `roy-agent tasks tree --json`); new /api/tasks/tree endpoint with status / priority / type / root-id filters, expand/collapse UI, search, and live 30s polling. v0.8.0: per-task page Mermaid area now renders the hierarchical 'Task lifecycle + tools' view \u2014 each operation record owns a subgraph that nests its tool calls, with click callbacks (`window.__toolClick`) that scroll-into-view + highlight + auto-expand the matching row in the tool-call table below. Operation record descriptions (`description` + `processDescription`) are now always rendered inline (no `<details>` collapse) so the user sees the lifecycle state at a glance; a fallback `<details>` kicks in only for descriptions longer than 600 chars. v0.8.1: hotfix for two pre-existing bugs in v0.8.0 (browser smoke test surfaced after merge). (a) Mermaid click directives were emitted as `click t1 __toolClick(1)` (missing `call` keyword) \u2014 Mermaid 10's parser rejects this with `got 'PS'`. Fixed to `click t1 call __toolClick(1)` (the v10 grammar requires `call` to invoke a callback with arguments). (b) `buildMermaidSource` lived inside the `attachTaskPageTimeline` IIFE but was also called from a listener in the `attachToolClickBridge` IIFE \u2014 sibling IIFEs cannot see each other's locals, so the listener threw `ReferenceError: buildMermaidSource is not defined` and the Mermaid diagram silently failed to re-render after `task-show:lifecycle-ops-loaded`. Fixed by hoisting the function (and its three helpers) to script top-level so both IIFEs can see it via the script-wide closure; the function is also exposed on `window.buildMermaidSource` for tests + tooling. v0.8.3: tree-display fix (Task #2426). The home page used to look like a flat list of root tasks because `autoExpandFirstLevels(..., 2)` only opened the first 2 levels \u2014 30/47 roots were leaf nodes and the remaining 17 collapsed to one level so grandchildren were never visible. Default expand depth is now 3 (root + child + grandchild + great-grandchild are visible on first paint), the summary line now shows per-depth count pills (root / child / grandchild / great-grandchild / level-N), each `tree-row` carries a `data-depth` attribute so CSS can paint coloured left rails per level, and the duplicated 'Live tool-call sessions (legacy view)' panel that made the page look like both a flat table AND a tree is now hidden behind `#legacy-sessions[hidden]` (kept for future debug-toggle restoration). v0.8.10: bug-fix release (Task #2537 + Task #2534). (a) Heap-bounded plugin caches: OperationsCache and TasksTreeCache now enforce a hard maxEntries cap (default 256 / 64). Oldest stale entries are evicted before inserting a new one, so long-lived roy-agent sessions (BackgroundTaskManager + MemorySessionStore) no longer leak Map entries through the plugin's per-task caches \u2014 see Task #2537 for the heap-unbounded-state RED\u2192GREEN repro. (b) Mermaid CJK font-family: server.ts renderTaskPage now configures mermaid.initialize({ themeVariables: { fontFamily: '\"PingFang SC\", \"Microsoft YaHei\", \"Noto Sans CJK SC\", \"Source Han Sans CN\", \"WenQuanYi Micro Hei\", sans-serif' } }) so Chinese node labels render correctly in browsers that have at least one of those fonts installed (see Task #2534).",
5
+ "description": "v2.6.1: Mermaid render-retry self-heal (Task #3129 follow-up). v2.6.0's 3-attempt retry loop replayed the SAME source string on every retry — if the source was half-built at attempt 1 (SSE applyTaskUpdate interleaving with task-operations.js polling), attempts 2-3 hit the same 'Syntax error in text' fallback. v2.6.1 makes `controller.update()` accept an OPTIONAL `getSourceForRetry` thunk and re-invokes it between attempts so each retry sees the freshest (operations, session) snapshot the caller's source-builder can assemble. `scheduleMermaidRender` (public/app.js) now passes the same thunk through, so the SSE/poll race that v2.6.0 fixed now also self-heals within a single render call. RENDER_RETRY_MAX bumped 3→5 with backoff 60ms→120ms to give the second path more time to settle. mount() keeps the original two-arg signature (SSR-stable source, no race). All 7 new retry-thunk tests pass (T1 self-heal, T2 v2.6.0 fallback, T3 first-try bypass, T4 same-source fidelity, T5 non-retryable bail, T6 thunk-throw, T7 mount signature). v2.6.0: Mermaid rendering race-condition fix (Task #3123 — `Syntax error in text` on Task detail pages). Two paths previously raced on the same `<div class=\"mermaid\">`: the SSE `applyTaskUpdate` handler (writes the latest session.toolCalls) and the `task-show:lifecycle-ops-loaded` listener (writes the latest operations from `/api/tasks/:id/operations`). Each path had its OWN `createMermaidController` instance, so two controllers ran concurrent `mermaid.render()` calls and a half-built source string landed mid-transition → 'Syntax error in text'. Fix has three parts: (1) a SINGLE shared `window.__mermaidController` singleton (both paths now `update()` the same instance, so the existing per-container token guard drops late results); (2) a per-container Promise-chain render queue (`window.scheduleMermaidRender(container, taskId, getSource)` where `getSource` is a thunk) so the (operations, session) snapshot is atomic by the time we hand it to the controller; (3) `mermaid-renderer.js#renderInternal` now retries `mermaid.render` up to 3× with jittered backoff (60-180ms+0-40ms) on `Syntax error in text` before giving up, so transient races self-heal without surfacing the error block. Backwards compatible: old bundles that don't include the lock helper fall through to the v2.5.x per-instance controller. Tested: all 135 mermaid/app-js tests pass, build + typecheck clean. v2.4.1: Mermaid zoom now supports click-and-drag pan (Task #2785). After zooming in, users can drag the diagram to view the surrounding canvas area. Implementation: per-container panState/dragState WeakMap (no global state leak); applyTransform(translate+scale) single-source-of-truth for the CSS transform; attachPanHandlers on pointerdown/move/up/cancel with setPointerCapture for off-element drags; pointer cursor switches to grab/grabbing with touch-action: none to prevent native scrolling; reset/zoomReset now also resets pan to (0,0). 14/14 new mermaid-pan tests pass, full suite 558/564 with 6 pre-existing failures unrelated to this commit. v2.4.0: Combines v2.3.0 Combines v2.3.0 (worktree-aware file-tree + unbounded Mermaid zoom, Task #2773) with the v2.3.0 mermaid placeholder expansion (Task #2771). Sidebar + endpoint scope git ls-files to session.context.worktree (fallback process.cwd()); Mermaid zoom-in is no longer capped at 3.0×; .mermaid placeholder is now min-height: 2400px and .mermaid-zoom-stage is min-width: 6400px / min-height: 2400px (5× base, via --mermaid-placeholder-multiplier CSS custom property) so dense diagrams get enough canvas to pan/zoom comfortably. v2.3.0: Worktree-aware file tree sidebar + unbounded Mermaid zoom-in. The file-tree sidebar (and /api/task/:id/file-tree endpoint) now scope git ls-files to session.context.worktree when the host (task:before.create / task:after.create payload) supplies a worktree path, so the sidebar shows the files the agent is actually editing instead of the plugin process cwd. New resolveWorktreePath helper in src/file-tree.ts returns session.context.worktree (trimmed, with empty/non-string guard) or falls back to process.cwd() for backward compatibility with pre-v2.3.0 hosts. TypeScript: TaskSession gains an optional context?: { worktree?: string } field. TaskShowServer exposes getCollector() so tests can seed sessions with context.worktree set. The Mermaid zoom toolbar (introduced in v2.0.8) no longer caps zoom-in at 3.0× — the ZOOM_MAX constant is REMOVED and clampZoom only enforces ZOOM_MIN=0.25, so dense diagrams remain readable on high-DPI monitors when the user wants to zoom way in. ZOOM_MIN stays in place so zoom-out still bottoms out before rendering a black screen. New tests: test/file-tree-worktree.test.ts (10 cases — resolveWorktreePath edges, SSR scope, endpoint scope, fallback), test/mermaid-zoom-unlimited.test.ts (8 cases — source guard, behaviour at 6×/10×/50×, lower-bound preserved), test/mermaid-placeholder-size.test.ts (7 cases — min-height/min-width 5× checks, transform-origin preserved, --mermaid-placeholder-multiplier hint). v2.3.0: Major visual overhaul of the per-task detail page — VS Code-style tool-call browser powered by Monaco Editor + LCS-based diff + project file tree with mermaid-driven navigation. The detail page now renders a 2-column layout: a sticky left sidebar with the project's git-tracked file tree (chevron-toggle directories, `is-affected` highlight for files touched by the current task), and a main column with the existing Mermaid + stats + toolcalls table + a new dedicated `<section id=\"tool-call-detail-panel\">` that hosts the LCS diff body + Monaco container for the currently-selected tool call. The legacy inline `<details class=\"diff-panel\">` (naive split-and-filter, prone to mis-tagging context lines) is replaced by `<ol class=\"diff-body\">` with proper added/removed/context markers driven by a real LCS dynamic-programming table (`computeDiff()` in `src/tool-call-detail.ts`). Tool calls with a file path get a Monaco Editor placeholder (`<div class=\"monaco-editor\" data-file-path=\"...\" data-language=\"...\">`) which the client-side `public/tool-call-detail.js` lazy-loads from `cdn.jsdelivr.net/npm/monaco-editor@0.45.0` the first time the user clicks a tool row. The Mermaid `__toolClick(toolId)` callback now drives THREE things: (a) the existing row scroll + highlight (preserved from v1.x), (b) the dedicated detail panel re-renders with the matching call, (c) the file-tree sidebar highlights the corresponding file (when `data-file-path` is present). New `GET /api/task/:id/file-tree` endpoint serves the git-tracked file list (`{ files: string[] }`) with a 30-second in-memory TTL + 8-entry FIFO bound. New modules: `src/file-tree.ts` (pure data layer: `buildFileTree / extractAffectedPaths / findNodeByPath / collectAllPaths / gitLsFiles / parseLsFiles`), `src/tool-call-detail.ts` (SSR + LCS diff + HTML escaping), `public/file-tree.js` (vanilla JS hydrator with chevron toggle + keyboard navigation + scrollIntoView), `public/tool-call-detail.js` (Monaco AMD loader + `__toolClick` wrapper + file-content fetch). New tests: `test/file-tree.test.ts` (21 cases — empty/single/nested/dedup/sort/depth/parseLsFiles/gitLsFiles), `test/tool-call-detail.test.ts` (22 cases — LCS diff edges, HTML escape, path aliases, summary stats), `test/tool-call-detail-server-integration.test.ts` (7 cases — SSR HTML contracts + endpoint), `test/tool-call-detail-jsdom.test.ts` (7 cases — client-side hydrators). v1.2.0: CSS context & packaged release hotfix. The plugin's public assets (notably `public/style.css`) and runtime adapters now correctly resolve relative to the installed package directory even when consumed via the published npm tarball. The session-scoped `TaskSessionStore` now preserves the full host session context (parent-child task links, plugin-handle id, env scope) across render cycles — previously the session was collapsed to its `sessionId` on first load and never refreshed, so the home page lost the 「session ancestors」 chain and external tasks from outside the current session silently disappeared from the tree. Adds `src/task-metadata.ts` as the single source of truth for the public `Task` shape exposed by `/api/tasks` + `/api/tasks/:id`, including the v1.0.0+ `processDescription` field, and re-exports it through the CLI adapters (`cli-tasks-adapter.ts` + `cli-tasks-tree-adapter.ts`) so the home page tree + the per-task page render against the same metadata contract. Bundles 244-line regression test (`test/context-and-packed-release.test.ts`) that boots the plugin from the **npm-pack** directory (not the repo working tree), spawns `roy-agent tasks get <id> --json`, and asserts (a) `public/style.css` is present and ≥ 64 lines, (b) the `/api/events` SSE endpoint survives a reload, and (c) `task.session` survives a render cycle. v1.1.0: Full Server-Sent Events realtime subscription across 3 event classes (task.created / operation.updated / tool.called) on both the home page and the per-task /task/<id> page. The per-task pipeline now subscribes to /api/events and patches the DOM in place on operation.updated — no more 5s-poll delay before the user sees a new milestone. The 'Task lifecycle pipeline' header badge is replaced by a 5-state SSE-aware badge (stale / connecting / live / reconnecting / error) so the user can tell at a glance whether real-time updates are flowing, the connection dropped, or 3+ consecutive errors triggered the polling fallback. Legacy boolean `stale` cache-TTL pill and `tool.recorded` event name are preserved for back-compat with v0.9.x / v1.0.0 clients. v1.0.0: First stable release. Replaces the v0.9.x fixture-based verify scripts (which built fake TaskOperationsEnvelope and never invoked the real `roy-agent` CLI, masking regressions in the public-schema `processDescription` field) with a real-CLI scenario test + verify (`test/process-description-real-scenario.test.ts` + `scripts/verify-v100-real-scenario.ts`) that spawns `roy-agent tasks get <id> --operations --json` via `defaultRunner` and asserts the API response carries `processDescription` end-to-end. The 0.9.9 processDescription fix is preserved verbatim — this release only swaps the verify surface. Visualize the tool call chain of a task on a local web service with real-time SSE updates. v0.9.9: Task lifecycle pipeline on /task/<id> now exposes BOTH the milestone badge AND the 「过程描述」 column at a glance — the server-side `/api/tasks/:id/operations` endpoint exposes `processDescription` on every operation (no longer stripped from the public schema), the client-side `renderPipelineHtml` mirrors the server's `.op-desc-block` + `.op-proc-block` block layout so SSR ↔ CSR stay in sync, and a long-standing CSS right-side text-truncation bug in the pipeline timeline (long CJK titles overflowing the panel edge) is fixed via `min-width: 0` on `.op-row1` + `overflow-wrap: anywhere` on `.op-title`. v0.9.0: Session-scoped home page (only show tasks created after plugin load + their external ancestors), with per-row 「显示全部栏位」 toggle and lazy-loaded operations timeline; per-task Mermaid labels now correctly render CJK / mixed-Latin / emoji text (encoded as \\uXXXX before emission, decoded by the browser); detail page layout reordered to lifecycle → pipeline → stats → toolcalls → rawjson. v0.5.0+: page refreshes stream over GET /api/events (Server-Sent Events). Subscribes to tool:before.execute, tool:after.execute, task:before.create, task:after.create, task:after.complete (preferred, 2026-07-10+), and task:after.update (legacy fallback). v0.6.11: Mermaid re-rendering is delegated to a self-contained controller (public/mermaid-renderer.js) that prevents the SVG→raw-source regression on async updates and surfaces recoverable .mermaid-error states. v0.6.12: Task lifecycle pipeline (operations timeline) server now emits data-task-id on the pipeline section; client preserves it on swap, so the page actually fetches /api/tasks/<id>/operations and renders the 7-op timeline (previously silently bailed). v0.7.0: Home page redesigned as a hierarchical task tree (driven by `roy-agent tasks tree --json`); new /api/tasks/tree endpoint with status / priority / type / root-id filters, expand/collapse UI, search, and live 30s polling. v0.8.0: per-task page Mermaid area now renders the hierarchical 'Task lifecycle + tools' view — each operation record owns a subgraph that nests its tool calls, with click callbacks (`window.__toolClick`) that scroll-into-view + highlight + auto-expand the matching row in the tool-call table below. Operation record descriptions (`description` + `processDescription`) are now always rendered inline (no `<details>` collapse) so the user sees the lifecycle state at a glance; a fallback `<details>` kicks in only for descriptions longer than 600 chars. v0.8.1: hotfix for two pre-existing bugs in v0.8.0 (browser smoke test surfaced after merge). (a) Mermaid click directives were emitted as `click t1 __toolClick(1)` (missing `call` keyword) — Mermaid 10's parser rejects this with `got 'PS'`. Fixed to `click t1 call __toolClick(1)` (the v10 grammar requires `call` to invoke a callback with arguments). (b) `buildMermaidSource` lived inside the `attachTaskPageTimeline` IIFE but was also called from a listener in the `attachToolClickBridge` IIFE — sibling IIFEs cannot see each other's locals, so the listener threw `ReferenceError: buildMermaidSource is not defined` and the Mermaid diagram silently failed to re-render after `task-show:lifecycle-ops-loaded`. Fixed by hoisting the function (and its three helpers) to script top-level so both IIFEs can see it via the script-wide closure; the function is also exposed on `window.buildMermaidSource` for tests + tooling. v0.8.3: tree-display fix (Task #2426). The home page used to look like a flat list of root tasks because `autoExpandFirstLevels(..., 2)` only opened the first 2 levels — 30/47 roots were leaf nodes and the remaining 17 collapsed to one level so grandchildren were never visible. Default expand depth is now 3 (root + child + grandchild + great-grandchild are visible on first paint), the summary line now shows per-depth count pills (root / child / grandchild / great-grandchild / level-N), each `tree-row` carries a `data-depth` attribute so CSS can paint coloured left rails per level, and the duplicated 'Live tool-call sessions (legacy view)' panel that made the page look like both a flat table AND a tree is now hidden behind `#legacy-sessions[hidden]` (kept for future debug-toggle restoration). v0.8.10: bug-fix release (Task #2537 + Task #2534). (a) Heap-bounded plugin caches: OperationsCache and TasksTreeCache now enforce a hard maxEntries cap (default 256 / 64). Oldest stale entries are evicted before inserting a new one, so long-lived roy-agent sessions (BackgroundTaskManager + MemorySessionStore) no longer leak Map entries through the plugin's per-task caches — see Task #2537 for the heap-unbounded-state RED→GREEN repro. (b) Mermaid CJK font-family: server.ts renderTaskPage now configures mermaid.initialize({ themeVariables: { fontFamily: '\"PingFang SC\", \"Microsoft YaHei\", \"Noto Sans CJK SC\", \"Source Han Sans CN\", \"WenQuanYi Micro Hei\", sans-serif' } }) so Chinese node labels render correctly in browsers that have at least one of those fonts installed (see Task #2534).",
6
6
  "main": "dist/index.js",
7
7
  "hooks": [
8
8
  {
@@ -23,11 +23,11 @@
23
23
  },
24
24
  {
25
25
  "point": "task:after.complete",
26
- "purpose": "PREFERRED hook point (roy-agent 2026-07-10+). When a task transitions to a terminal status (completed/failed/cancelled), finalize the session and broadcast a `task.completed` SSE event. terminalStatus field is explicit \u2014 no status filtering required. The handler dedupes against any `task:after.update` that may also fire on the same transition."
26
+ "purpose": "PREFERRED hook point (roy-agent 2026-07-10+). When a task transitions to a terminal status (completed/failed/cancelled), finalize the session and broadcast a `task.completed` SSE event. terminalStatus field is explicit no status filtering required. The handler dedupes against any `task:after.update` that may also fire on the same transition."
27
27
  },
28
28
  {
29
29
  "point": "task:after.update",
30
- "purpose": "GENERIC status update hook (v0.5.0+). Used for non-terminal transitions (running \u2192 paused \u2192 running) AND as a legacy fallback for hosts predating the AFTER_COMPLETE hook point. Broadcasts `task.updated` for non-terminal status, `task.completed` for terminal status. The internal dedup set guarantees at most one terminal broadcast per task even if both hooks fire."
30
+ "purpose": "GENERIC status update hook (v0.5.0+). Used for non-terminal transitions (running paused running) AND as a legacy fallback for hosts predating the AFTER_COMPLETE hook point. Broadcasts `task.updated` for non-terminal status, `task.completed` for terminal status. The internal dedup set guarantees at most one terminal broadcast per task even if both hooks fire."
31
31
  }
32
32
  ],
33
33
  "commands": [
@@ -64,20 +64,20 @@
64
64
  }
65
65
  },
66
66
  "endpoints": {
67
- "index": "GET / \u2014 index of recent task sessions",
68
- "taskDetail": "GET /task/:taskId \u2014 detail page (mermaid flow + tables)",
69
- "apiSessions": "GET /api/sessions \u2014 JSON list of sessions",
70
- "apiSessionDetail": "GET /api/sessions/:taskId \u2014 JSON detail of one session",
71
- "apiEvents": "GET /api/events \u2014 Server-Sent Events stream (real-time push)",
72
- "static": "GET /static/* \u2014 static frontend assets (CSS/JS)"
67
+ "index": "GET / index of recent task sessions",
68
+ "taskDetail": "GET /task/:taskId detail page (mermaid flow + tables)",
69
+ "apiSessions": "GET /api/sessions JSON list of sessions",
70
+ "apiSessionDetail": "GET /api/sessions/:taskId JSON detail of one session",
71
+ "apiEvents": "GET /api/events Server-Sent Events stream (real-time push)",
72
+ "static": "GET /static/* static frontend assets (CSS/JS)"
73
73
  },
74
74
  "sse": {
75
75
  "events": [
76
- "snapshot \u2014 initial state dump on connect",
77
- "task.created \u2014 new task session opened",
78
- "task.updated \u2014 non-terminal status change",
79
- "task.completed \u2014 task transitioned to a terminal status",
80
- "tool.recorded \u2014 tool call appended to a session"
76
+ "snapshot initial state dump on connect",
77
+ "task.created new task session opened",
78
+ "task.updated non-terminal status change",
79
+ "task.completed task transitioned to a terminal status",
80
+ "tool.recorded tool call appended to a session"
81
81
  ],
82
82
  "heartbeatMs": 15000,
83
83
  "snapshotFrame": "event: snapshot\ndata: {type:'snapshot', data:{sessions:[...]}}\n\n"
@@ -89,4 +89,4 @@
89
89
  },
90
90
  "repository": "github:ai-setting/roy-plugin-task-visualize",
91
91
  "bugs": "https://github.com/ai-setting/roy-plugin-task-visualize/issues"
92
- }
92
+ }
package/public/app.js CHANGED
@@ -104,6 +104,141 @@
104
104
  }
105
105
  })();
106
106
 
107
+ /* ------------------------------------------------------------------------- */
108
+ /* v2.6.0 (fix/task-show-mermaid-render-lock): shared singleton + queue */
109
+ /* */
110
+ /* Background: two paths call `controller.update(mermaidDiv, source)` for */
111
+ /* the same DOM node — (1) SSE `applyTaskUpdate` (latest session) and */
112
+ /* (2) `task-show:lifecycle-ops-loaded` (latest operations). Each path */
113
+ /* previously created its OWN `createMermaidController` instance, so two */
114
+ /* controllers raced on the same container and produced inconsistent */
115
+ /* source strings during the brief window where one path had new toolCalls */
116
+ /* but the other still served stale operations. */
117
+ /* */
118
+ /* The fix has three parts: */
119
+ /* 1. A single shared controller (`window.__mermaidController`) — both */
120
+ /* paths call `update()` on the same instance, so the existing `token` */
121
+ /* mechanism (in `mermaid-renderer.js`) drops the late result. */
122
+ /* 2. A render queue keyed by container (`window.__mermaidQueue`) — */
123
+ /* before `update()` runs we enqueue a Promise that resolves only */
124
+ /* after the previous `update()` for that container settled. This */
125
+ /* gives a stable (operations, session) snapshot to render: the */
126
+ /* second caller will see the freshly-updated `__lifecycleOps` or */
127
+ /* `__pipelineController.lastSession` by the time its callback */
128
+ /* runs. */
129
+ /* 3. The controllers' own retry path (`mermaid-renderer.js` v2.6.0) */
130
+ /* handles any remaining transient syntax errors. */
131
+ /* ------------------------------------------------------------------------- */
132
+ (function attachSharedMermaidLock() {
133
+ function ensureSharedMermaidController(taskId) {
134
+ if (!window.MermaidRenderer || !window.MermaidRenderer.createMermaidController) {
135
+ return null;
136
+ }
137
+ if (!window.__mermaidController) {
138
+ window.__mermaidController = window.MermaidRenderer.createMermaidController({
139
+ idPrefix: "task-" + (taskId || "lifecycle"),
140
+ });
141
+ }
142
+ return window.__mermaidController;
143
+ }
144
+
145
+ function ensureMermaidQueue() {
146
+ if (!window.__mermaidQueue) {
147
+ // Promise chain key — keyed by container DOM node identity so
148
+ // different diagrams on the same page render independently.
149
+ window.__mermaidQueue = new WeakMap();
150
+ }
151
+ return window.__mermaidQueue;
152
+ }
153
+
154
+ /**
155
+ * Schedule a render via the SHARED controller + per-container queue.
156
+ *
157
+ * `getSource()` is a thunk so it reads the LATEST state right before
158
+ * its turn in the queue runs — this is what makes the snapshot atomic.
159
+ * By the time the queue dispatches our thunk, the previous update()'s
160
+ * `mermaid.render` Promise has either resolved or been superseded, and
161
+ * any sibling path that fired in the meantime has updated the
162
+ * authoritative state (window.__lifecycleOps or
163
+ * window.__pipelineController.lastSession). The thunk reads both and
164
+ * builds the source string in one synchronous block — no interleaving
165
+ * possible between "read ops" and "read session".
166
+ *
167
+ * Returns a Promise that resolves when THIS render is settled. Note
168
+ * that if a newer call has already superseded us, the controller's
169
+ * token guard drops our result and our Promise simply resolves to
170
+ * "we ran, but nothing changed" — matching the v1.x behavior.
171
+ */
172
+ function scheduleMermaidRender(container, taskId, getSource) {
173
+ const controller = ensureSharedMermaidController(taskId);
174
+ if (!controller) {
175
+ // Mermaid not loaded — preserve legacy fallback: write source
176
+ // as pre-formatted text so the user at least sees something.
177
+ try {
178
+ container.textContent = String(getSource());
179
+ } catch (_) { /* swallow — same as v1.x */ }
180
+ return Promise.resolve();
181
+ }
182
+ const queue = ensureMermaidQueue();
183
+ const prev = queue.get(container);
184
+ const next = Promise.resolve(prev).then(() => {
185
+ // Re-check container still in the DOM; lifecycle-ops-loaded
186
+ // can fire after the user navigates away (task page replaced
187
+ // by the index, etc.) — `controller.update` already no-ops on
188
+ // a destroyed controller, but skipping earlier saves work.
189
+ if (!container || !container.isConnected) return;
190
+ let source;
191
+ try {
192
+ source = String(getSource());
193
+ } catch (err) {
194
+ // eslint-disable-next-line no-console
195
+ console.warn("[task-show] scheduleMermaidRender: getSource threw:", err);
196
+ return;
197
+ }
198
+ // v2.6.1 (fix/task-show-mermaid-render-thunk-retry): the
199
+ // v2.6.0 retry path replayed the same `source` string on
200
+ // every attempt, so a half-built source at attempt 1 was
201
+ // doomed to fail at attempts 2-3 as well. We now hand the
202
+ // controller the SAME `getSource` thunk as
203
+ // `getSourceForRetry` so each retry can read the freshest
204
+ // (operations, session) snapshot the thunk can assemble.
205
+ return controller.update(container, source, { getSourceForRetry: getSource });
206
+ }).catch((err) => {
207
+ // Defensive: never let an exception in the queue escape the
208
+ // promise chain. The controller's own onStateChange handler
209
+ // already surfaces render errors as the visible error block.
210
+ // eslint-disable-next-line no-console
211
+ console.warn("[task-show] mermaid queue tick failed:", err && err.message || err);
212
+ }).finally(() => {
213
+ // Drop our chain slot once settled so the WeakMap entry stays
214
+ // accurate — this also prevents a stale chain from blocking
215
+ // future renders on the same container (a common v1.x bug
216
+ // where a caught render error left the chain permanently
217
+ // broken).
218
+ const cur = queue.get(container);
219
+ if (cur === next) queue.delete(container);
220
+ });
221
+ queue.set(container, next);
222
+ // v2.5.12 (Task #2951): install the zoom-stage guardian once per
223
+ // container so Mermaid's late `mermaid.run()` (~T+3s) doesn't
224
+ // strip the `.mermaid-zoom-stage` wrapper. Guarded by the same
225
+ // `__mermaidGuardian` flag the legacy code used so multiple
226
+ // callers don't double-bind.
227
+ if (window.MermaidZoomGuardian && window.MermaidZoomGuardian.MermaidZoomGuardian && !window.__mermaidGuardian) {
228
+ try {
229
+ window.__mermaidGuardian = new window.MermaidZoomGuardian.MermaidZoomGuardian(container);
230
+ window.__mermaidGuardian.start();
231
+ } catch (_) { /* ignore — guardian is best-effort */ }
232
+ }
233
+ return next;
234
+ }
235
+
236
+ // Expose helpers so other IIFEs (attachTaskPageTimeline,
237
+ // attachToolClickBridge) share the same controller + queue.
238
+ window.scheduleMermaidRender = scheduleMermaidRender;
239
+ window.ensureSharedMermaidController = ensureSharedMermaidController;
240
+ })();
241
+
107
242
  /* ------------------------------------------------------------------------- */
108
243
  /* v0.8.1+ Mermaid source builder (top-level — shared by both IIFEs) */
109
244
  /* ------------------------------------------------------------------------- */
@@ -632,14 +767,31 @@ if (typeof window !== "undefined") {
632
767
  .then((r) => (r.ok ? r.json() : null))
633
768
  .then((s) => {
634
769
  if (!s) return;
770
+ // v2.6.0 (fix/task-show-mermaid-render-lock): route through
771
+ // the shared singleton + queue. The thunk reads the LATEST
772
+ // state inside its slot, so by the time the queue dispatches
773
+ // us we may have a richer session than what was captured
774
+ // here — that's fine, it just means we render with the most
775
+ // up-to-date snapshot.
776
+ if (window.scheduleMermaidRender) {
777
+ window.scheduleMermaidRender(mermaidDiv, taskId, () => {
778
+ const liveOps = (window.__lifecycleOps && window.__lifecycleOps.operations) || ops;
779
+ return buildMermaidSource(s, liveOps);
780
+ });
781
+ return;
782
+ }
635
783
  const source = buildMermaidSource(s, ops);
636
784
  if (window.MermaidRenderer && window.MermaidRenderer.createMermaidController) {
637
- if (!window.__mermaidController) {
638
- window.__mermaidController = window.MermaidRenderer.createMermaidController({
639
- idPrefix: "lifecycle-" + taskId,
640
- });
785
+ if (window.ensureSharedMermaidController) {
786
+ window.ensureSharedMermaidController(taskId).update(mermaidDiv, source);
787
+ } else {
788
+ if (!window.__mermaidController) {
789
+ window.__mermaidController = window.MermaidRenderer.createMermaidController({
790
+ idPrefix: "lifecycle-" + taskId,
791
+ });
792
+ }
793
+ window.__mermaidController.update(mermaidDiv, source);
641
794
  }
642
- window.__mermaidController.update(mermaidDiv, source);
643
795
  // v2.5.12 (Task #2951): install the zoom-stage guardian.
644
796
  if (!window.__mermaidGuardian && window.MermaidZoomGuardian) {
645
797
  window.__mermaidGuardian = new window.MermaidZoomGuardian.MermaidZoomGuardian(mermaidDiv);
@@ -654,14 +806,29 @@ if (typeof window !== "undefined") {
654
806
  });
655
807
  return;
656
808
  }
809
+ // v2.6.0: prefer the shared scheduler so this render serializes
810
+ // behind any in-flight `applyTaskUpdate` call.
811
+ if (window.scheduleMermaidRender) {
812
+ window.scheduleMermaidRender(mermaidDiv, taskId, () => {
813
+ const liveOps = (window.__lifecycleOps && window.__lifecycleOps.operations) || ops;
814
+ // Re-read the live session inside the thunk too — SSE may
815
+ // have updated `__pipelineController.lastSession` while we
816
+ // waited in the queue.
817
+ const liveSession = (window.__pipelineController && window.__pipelineController.lastSession) || session;
818
+ return buildMermaidSource(liveSession, liveOps);
819
+ });
820
+ return;
821
+ }
657
822
  const source = buildMermaidSource(session, ops);
658
823
  if (window.MermaidRenderer && window.MermaidRenderer.createMermaidController) {
659
- if (!window.__mermaidController) {
824
+ if (window.ensureSharedMermaidController) {
825
+ window.ensureSharedMermaidController(taskId).update(mermaidDiv, source);
826
+ } else if (!window.__mermaidController) {
660
827
  window.__mermaidController = window.MermaidRenderer.createMermaidController({
661
828
  idPrefix: "lifecycle-" + taskId,
662
829
  });
830
+ window.__mermaidController.update(mermaidDiv, source);
663
831
  }
664
- window.__mermaidController.update(mermaidDiv, source);
665
832
  // v2.5.12 (Task #2951): install the zoom-stage guardian.
666
833
  if (!window.__mermaidGuardian && window.MermaidZoomGuardian) {
667
834
  window.__mermaidGuardian = new window.MermaidZoomGuardian.MermaidZoomGuardian(mermaidDiv);
@@ -781,23 +948,29 @@ if (typeof window !== "undefined") {
781
948
  // Re-render mermaid diagram.
782
949
  const mermaidDiv = document.querySelector(".mermaid");
783
950
  if (mermaidDiv) {
784
- // v0.8.0+: prefer the latest operations fetched by
785
- // task-operations.js (window.__lifecycleOps) so the Mermaid shows
786
- // the hierarchical view. Falls back to the linear chain when no
787
- // operations are loaded yet.
788
- const ops = (window.__lifecycleOps && window.__lifecycleOps.operations) || null;
789
- const source = buildMermaidSource(session, ops);
790
- // The controller handles mermaid availability, async race protection,
791
- // error fallback, and idempotency. If Mermaid hasn't loaded yet
792
- // (window.MermaidRenderer is undefined), we fall back to writing the
793
- // source as a <pre> so the user at least sees the diagram text — same
794
- // UX as the legacy pre-controller code.
795
- if (window.MermaidRenderer && window.MermaidRenderer.createMermaidController) {
951
+ // v2.6.0 (fix/task-show-mermaid-render-lock): route through the
952
+ // shared singleton + per-container queue (`window.scheduleMermaidRender`).
953
+ // Previously `applyTaskUpdate._controller` was a SEPARATE instance from
954
+ // the one `task-show:lifecycle-ops-loaded` created (`window.__mermaidController`),
955
+ // so two controllers raced on the same `<div class="mermaid">` and the
956
+ // SSR or the winning render could land stale. The shared controller +
957
+ // thunk-based source builder makes the (operations, session) snapshot
958
+ // atomic.
959
+ if (window.scheduleMermaidRender) {
960
+ window.scheduleMermaidRender(mermaidDiv, taskId, () => {
961
+ const ops = (window.__lifecycleOps && window.__lifecycleOps.operations) || null;
962
+ return buildMermaidSource(session, ops);
963
+ });
964
+ } else if (window.MermaidRenderer && window.MermaidRenderer.createMermaidController) {
965
+ // Backwards-compatible fallback for older bundles that loaded
966
+ // app.js without the lock helper. Same behavior as v2.5.x.
796
967
  if (!applyTaskUpdate._controller) {
797
968
  applyTaskUpdate._controller = window.MermaidRenderer.createMermaidController({
798
969
  idPrefix: "task-" + taskId,
799
970
  });
800
971
  }
972
+ const ops = (window.__lifecycleOps && window.__lifecycleOps.operations) || null;
973
+ const source = buildMermaidSource(session, ops);
801
974
  applyTaskUpdate._controller.update(mermaidDiv, source);
802
975
  // v2.5.12 (Task #2951): install the zoom-stage guardian so
803
976
  // Mermaid's late `mermaid.run()` (~T+3s) doesn't strip the
@@ -69,6 +69,57 @@
69
69
  const ZOOM_MIN = 0.25;
70
70
  const ZOOM_DEFAULT = 1.0;
71
71
 
72
+ // v2.6.0 (fix/task-show-mermaid-render-retry): robustness
73
+ // against transient syntax errors. The mermaid CLI parser is
74
+ // strict — a half-built source string from a race between
75
+ // the SSE `applyTaskUpdate` path (which writes the latest
76
+ // session.toolCalls) and the `task-operations.js` polling
77
+ // path (which writes the latest operations) can land in the
78
+ // controller mid-transition. The controller already drops
79
+ // *late* results via `getToken`, but it cannot save a *bad*
80
+ // source that was already inconsistent at construction time.
81
+ //
82
+ // v2.6.1 (fix/task-show-mermaid-render-thunk-retry): the
83
+ // v2.6.0 retry loop kept replaying the *same* source string
84
+ // on each attempt. If that string was bad (half-built at the
85
+ // moment we read it), all retries were doomed — every retry
86
+ // hit the same `Parse error on line N` / `Syntax error in
87
+ // text` SVG fallback. The fix is to (a) thread an optional
88
+ // `getSourceForRetry` thunk through `renderInternal()` /
89
+ // `update()`, and (b) re-invoke that thunk between attempts
90
+ // so each retry sees the **freshest** `(operations,
91
+ // session)` snapshot the controller's caller can assemble.
92
+ // `scheduleMermaidRender` (public/app.js) supplies this thunk
93
+ // by default so the race that v2.6.0 fixed now also self-
94
+ // heals within a single render call.
95
+ //
96
+ // We also bumped the retry budget + backoff so a second
97
+ // SSE/poll cycle has time to land before the loop gives up.
98
+ // The (v) prefixed config keeps the v2.6.0 behaviour available
99
+ // for callers that still want the literal replay (legacy
100
+ // direct `controller.update(container, source)` callers).
101
+ const RENDER_RETRY_MAX = 5;
102
+ const RENDER_RETRY_BACKOFF_MS = 120;
103
+ const RENDER_RETRY_BACKOFF_JITTER_MS = 80;
104
+
105
+ function isRetryableMermaidError(err) {
106
+ // Mermaid 10 surfaces parse failures with a thrown Error
107
+ // whose message contains "Syntax error in text" (lower-
108
+ // case `i`, capital `S`). Other failure modes (network,
109
+ // library missing, internal bug) are NOT retryable here —
110
+ // we let the outer try/catch surface them normally.
111
+ const msg = (err && err.message) || String(err || "");
112
+ return msg.indexOf("Syntax error in text") !== -1
113
+ || msg.indexOf("syntax error in text") !== -1;
114
+ }
115
+
116
+ function backoffDelay(attempt) {
117
+ // attempt is 1-based: 1 → base, 2 → base + 0..jitter.
118
+ const base = RENDER_RETRY_BACKOFF_MS * attempt;
119
+ const jitter = Math.floor(Math.random() * RENDER_RETRY_BACKOFF_JITTER_MS);
120
+ return base + jitter;
121
+ }
122
+
72
123
  function escapeHtml(s) {
73
124
  return String(s)
74
125
  .replace(/&/g, "&amp;")
@@ -667,8 +718,29 @@
667
718
  * the container reflects the latest source (either an SVG or an error
668
719
  * block). If a newer call supersedes this one before the mermaid.render
669
720
  * Promise resolves, the result is dropped (no DOM mutation).
721
+ *
722
+ * v2.6.0 (fix/task-show-mermaid-render-retry): on `Syntax error in
723
+ * text` we retry up to `RENDER_RETRY_MAX` times with jittered
724
+ * backoff before giving up. The race window between the SSE
725
+ * `applyTaskUpdate` and the `task-operations.js` poll paths can
726
+ * deliver a half-built source string to this controller; a brief
727
+ * wait usually lets the second path complete and the next
728
+ * `update()` call supersedes us — the dropped retry then costs
729
+ * nothing. See `isRetryableMermaidError` and `backoffDelay`.
730
+ *
731
+ * v2.6.1 (fix/task-show-mermaid-render-thunk-retry): we now
732
+ * accept an OPTIONAL `opts.getSourceForRetry` thunk. When the
733
+ * first render raises a retryable error, the loop awaits
734
+ * `backoffDelay(attempt)` ms (giving the SSE/poll paths time to
735
+ * settle) and re-invokes the thunk to read the LATEST source —
736
+ * rather than replaying the stale one. The caller (typically
737
+ * `scheduleMermaidRender`) bundles the (operations, session)
738
+ * read inside the thunk so each retry sees an atomic snapshot
739
+ * produced after the previous attempt's failure surfaced. This
740
+ * converts a doomed 3-of-3 retry loop into a chance to heal as
741
+ * soon as the racing path lands the missing piece.
670
742
  */
671
- async function renderInternal(container, source) {
743
+ async function renderInternal(container, source, opts) {
672
744
  // Idempotency: if the controller was destroyed or the container has
673
745
  // already successfully rendered this exact source, skip work entirely.
674
746
  if (controllerDestroyed) return;
@@ -687,20 +759,76 @@
687
759
  return;
688
760
  }
689
761
 
762
+ // v2.6.1: parse the optional thunk ONCE so the value can be
763
+ // reused across retries without surprising the caller
764
+ // (the same thunk must return consistent snapshots, i.e. it
765
+ // is a snapshot-fetcher not a side-effect-emitter).
766
+ const getSourceForRetry = (opts && typeof opts.getSourceForRetry === "function")
767
+ ? opts.getSourceForRetry
768
+ : null;
769
+
690
770
  const myToken = beginRender(container);
691
771
  setState(container, "loading");
772
+ // v2.6.0: same `id` is reused across retries inside one logical
773
+ // render — no need to bump `seqNum` per attempt since the token
774
+ // already distinguishes this logical call from any newer one.
692
775
  const seqNum = nextSeq(container);
693
776
  const id = `${idPrefix}-${seqNum}`;
694
777
  let result;
695
- try {
696
- result = await mermaid.render(id, source);
697
- } catch (err) {
698
- // Only surface this error if the user hasn't superseded us.
778
+ let lastErr = null;
779
+ // v2.6.0 + v2.6.1: retry loop. v2.6.0 replayed the same
780
+ // `source` string, which could not self-heal. v2.6.1 re-fetches
781
+ // `source` from the thunk (when provided) between attempts so
782
+ // each try sees the freshest `(operations, session)` snapshot
783
+ // the caller's source-builder can assemble. Non-retryable
784
+ // failures (e.g. library missing, thrown exception) bail
785
+ // immediately to preserve the original error behavior.
786
+ outer: for (let attempt = 1; attempt <= RENDER_RETRY_MAX; attempt++) {
787
+ // Bail out fast if a newer render has superseded us — paying
788
+ // for retries on a doomed source is wasteful.
789
+ if (controllerDestroyed || isDestroyed(container) || getToken(container) !== myToken) return;
790
+ try {
791
+ result = await mermaid.render(id, source);
792
+ lastErr = null;
793
+ break;
794
+ } catch (err) {
795
+ lastErr = err;
796
+ // v2.6.1: re-read the latest source from the thunk
797
+ // BEFORE the next backoff so the next attempt does not
798
+ // replay the same stale string. If the thunk is missing
799
+ // or throws we keep the prior `source` (legacy v2.6.0
800
+ // behaviour) and let the existing backoff handle the
801
+ // best-effort sequence.
802
+ if (getSourceForRetry && isRetryableMermaidError(err) && attempt < RENDER_RETRY_MAX) {
803
+ try {
804
+ const fresh = String(getSourceForRetry() ?? "");
805
+ if (fresh && fresh !== source) {
806
+ source = fresh;
807
+ }
808
+ } catch (_thunkErr) {
809
+ // Thunk threw — keep the previous source and let
810
+ // backoff + supersede do the work. We intentionally
811
+ // do not propagate this to the user; the loop will
812
+ // surface the underlying mermaid error instead.
813
+ }
814
+ }
815
+ if (!isRetryableMermaidError(err) || attempt === RENDER_RETRY_MAX) break;
816
+ // v2.6.0: wait, then check whether a newer call has
817
+ // superseded us. If yes, abort silently — no DOM mutation,
818
+ // no error block.
819
+ await new Promise((r) => setTimeout(r, backoffDelay(attempt)));
820
+ if (controllerDestroyed || isDestroyed(container) || getToken(container) !== myToken) return;
821
+ }
822
+ }
823
+ if (lastErr) {
824
+ // All retries failed (or the error wasn't retryable). Surface
825
+ // it just like before — only if this call is still the live
826
+ // one.
699
827
  if (controllerDestroyed || isDestroyed(container) || getToken(container) !== myToken) return;
700
828
  renderErrorBlock(
701
829
  container,
702
830
  source,
703
- (err && err.message) || String(err),
831
+ (lastErr && lastErr.message) || String(lastErr),
704
832
  );
705
833
  if (onStateChange) onStateChange(container, "error");
706
834
  return;
@@ -777,11 +905,25 @@
777
905
  // Idempotent: calling mount twice on the same container should not
778
906
  // duplicate SVG. We treat mount and update identically from the
779
907
  // rendering pipeline's perspective; the contract difference is only
780
- // intent (mount for first paint, update for re-renders).
908
+ // intent (mount for first paint, update for re-renders). mount keeps
909
+ // the simple two-arg signature — passing a thunk here would be
910
+ // surprising because the SSR page already commits a stable source.
781
911
  return renderInternal(container, source);
782
912
  },
783
- update(container, source) {
784
- return renderInternal(container, source);
913
+ /**
914
+ * v2.6.1: `update()` now accepts an optional third arg, a thunk that
915
+ * re-fetches the LATEST source between retry attempts. When omitted
916
+ * the controller falls back to v2.6.0's behaviour of replaying the
917
+ * supplied `source` (useful for callers that already know the
918
+ * string is final). `scheduleMermaidRender` (public/app.js) supplies
919
+ * this thunk so the race-fixed source-builder path self-heals.
920
+ *
921
+ * @param {HTMLElement} container
922
+ * @param {string} source
923
+ * @param {{ getSourceForRetry?: () => string | null }} [opts]
924
+ */
925
+ update(container, source, opts) {
926
+ return renderInternal(container, source, opts || null);
785
927
  },
786
928
  showError(container, source, error) {
787
929
  renderErrorBlock(container, source, error && error.message ? error.message : String(error));