@daguava/pi-narration 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 daguava
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # Pi Narration
2
+
3
+ Live activity narration for **PI WEB**. A Pi extension summarizes each agent's
4
+ current work with a dedicated small model, and a PI WEB browser plugin renders
5
+ those summaries in a docked overlay above the chat composer.
6
+
7
+ ![Narration rows docked above the PI WEB composer, with a main-session row and named subagent rows](docs/narration.png)
8
+
9
+ Narration renders in PI WEB's chat view for local or configured remote machines.
10
+ Terminal sessions load the extension but have no narration surface.
11
+
12
+ ## Subagent interaction
13
+
14
+ When a session spawns tracked Pi subsessions, the overlay reads each child's own
15
+ public session metadata and renders a named row beneath the parent. Children are
16
+ matched through `parentSessionPath` and `agentSubsession`, so forks do not appear
17
+ as subagents.
18
+
19
+ Each child keeps its own status, timer, summary, and completion mark. Children
20
+ are ordered by start time. A child's retrospective stays in the child's own view;
21
+ the parent keeps the child's frozen live line until the parent finishes. Children
22
+ are listed from the selected session's machine, so cross-machine child sessions
23
+ don't appear in the parent's overlay.
24
+
25
+ ![The same overlay with a main-session row and two tracked subagent rows beneath it](docs/narration-subagents.png)
26
+
27
+ ## What it shows
28
+
29
+ - One row per agent: name, one narration line, elapsed timer, and completion mark
30
+ (green check for success, muted cross for failure or cancellation).
31
+ - The main-session row sits above the composer; the overlay reserves that space
32
+ and never covers the composer or the green activity indicator.
33
+ - Active rows shimmer; completed rows show their last summary. Reduced-motion
34
+ preferences disable animation.
35
+ - Rows remain visible in and out of quiet mode.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pi install npm:@daguava/pi-narration
41
+ ```
42
+
43
+ Enable **Narration** in **Settings → PI WEB plugins**, then reload the PI WEB tab
44
+ once. For a local checkout: `pi install /path/to/pi-narration`.
45
+
46
+ ## Configure
47
+
48
+ Run `/narrator` in a PI WEB session. On PI WEB builds that include the narration
49
+ settings bridge, **Settings → Narration** edits the same plugin config file:
50
+
51
+ - `/narrator on` / `/narrator off` — enable or disable globally.
52
+ - `/narrator model` — choose the dedicated summarization model.
53
+ - `/narrator style` — `minimal`, `descriptive`, `insightful`,
54
+ `conversational`, `custom`; `custom` opens the instruction prompt.
55
+ - `/narrator custom` — edit custom style instructions.
56
+ - `/narrator interval` — seconds between summaries (minimum 1).
57
+ - `/narrator status` — counters, latency, and last error.
58
+
59
+ Settings live in `<pi-agent-dir>/narration/config.json` and apply without
60
+ restarting a session; the settings bridge and `/narrator` write that same file.
61
+ Narration stays off until a model is selected. The narration model is separate
62
+ from the session's primary model.
63
+
64
+ ## How it works
65
+
66
+ The Pi extension runs inside each session and builds a bounded digest of recent
67
+ reasoning, assistant text, tool activity, and user requests. It sends that digest
68
+ to the configured narration model, then publishes the result as public session
69
+ metadata (`pi-web.session-ui-metadata`, never LLM context). One request is in
70
+ flight per session, with a minimum interval, duplicate suppression, backoff, and
71
+ abort-raced timeouts.
72
+
73
+ The PI WEB plugin polls the host's same-origin session list, reads the selected
74
+ session and its tracked children, and renders the rows. Polling backs off when
75
+ rows are idle or the tab is hidden, keeps one request in flight with a timeout,
76
+ and stops on session switches or plugin disposal. If PI WEB removes that API,
77
+ the overlay stops updating until the plugin is adapted.
78
+
79
+ ## Privacy and limits
80
+
81
+ - The narration model receives a bounded digest that includes reasoning, tool
82
+ arguments, tool results, and user requests. With a cloud provider that content
83
+ leaves the machine; prefer a local model and avoid sessions whose tool output
84
+ contains secrets.
85
+ - Repeated metadata snapshots are deduplicated, oversized records are trimmed
86
+ under PI WEB's 16 KiB cap, and error text contains provider body text with
87
+ header lines removed.
88
+ - Retrospectives run asynchronously after a turn settles and never delay the
89
+ final answer.
90
+ - There is no separate diagnostics panel; `/narrator status` exposes counters,
91
+ latency, and the last error.
92
+
93
+ ## Requirements
94
+
95
+ - PI WEB with browser plugin API v5 and public session metadata support.
96
+ - Pi with extension event APIs (current 1.x).
97
+ - A configured narration model with working provider credentials.
98
+
99
+ ## Development
100
+
101
+ ```bash
102
+ npm ci
103
+ npm run build # TypeScript source -> dist/ (committed; CI verifies freshness)
104
+ npm run typecheck
105
+ npm run smoke # fake-host extension test + happy-dom overlay test
106
+ ```
107
+
108
+ `npm publish` runs the same build, typecheck, and smoke gate through
109
+ `prepublishOnly`.
@@ -0,0 +1,485 @@
1
+ import { NARRATION_NAMESPACE, NARRATION_METADATA_VERSION, } from "../shared/narration.js";
2
+ const POLL_ACTIVE_MS = 1_000;
3
+ const POLL_IDLE_MS = 4_000;
4
+ const FETCH_TIMEOUT_MS = 5_000;
5
+ const TICK_MS = 1_000;
6
+ const DOCK_GAP = 6;
7
+ // Reserve a fixed band: measuring the dock makes the composer jump when it appears.
8
+ const DOCK_BAND = 18;
9
+ const INDICATOR_PROBE_MS = 5_000;
10
+ const FALLBACK_COMPOSER = 120;
11
+ const STYLE = `
12
+ :host { all: initial; position: fixed; left: 0; right: 0; z-index: 40; display: flex; justify-content: center; pointer-events: none; }
13
+ .wrap { width: 100%; display: flex; justify-content: center; pointer-events: none; }
14
+ .panel { width: 100%; box-sizing: border-box; padding: 4px 12px; border-radius: 9px;
15
+ background: color-mix(in srgb, var(--pi-bg, #101418) 90%, transparent); color: var(--pi-text-secondary, #b9c0c7);
16
+ font: 12px/18px var(--pi-font, system-ui, sans-serif); box-shadow: 0 1px 0 color-mix(in srgb, var(--pi-border, #333) 60%, transparent); }
17
+ .list { display: grid; gap: 2px; }
18
+ .row { display: flex; align-items: center; gap: 8px; min-width: 0; border-radius: 6px; }
19
+ /* Zebra: the main row stays clean, subagent rows alternate a subtle surface tint. */
20
+ .row:nth-child(even) { background: color-mix(in srgb, var(--pi-surface-hover, var(--pi-border, #2a2f36)) 52%, transparent); }
21
+ /* Fixed gutters keep every row's text centered on the same axis. */
22
+ .name { flex: 0 0 auto; max-width: 22%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-muted, #6b7280); font-size: 11px; }
23
+ /* Align text across rows only while subagent rows participate. */
24
+ .list.has-subagents .row > .name { flex: 0 0 22%; }
25
+ .slot { flex: 1 1 auto; min-width: 0; height: 36px; display: flex; align-items: center; justify-content: center; }
26
+ .text { max-height: 36px; min-width: 0; display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-box-orient: vertical;
27
+ -webkit-line-clamp: 2; text-align: center; unicode-bidi: plaintext; color: var(--pi-text-secondary, #b9c0c7); }
28
+ .text.retro { white-space: pre-wrap; -webkit-line-clamp: 6; max-height: 108px; }
29
+ .text.shimmer { animation: breathe 2.4s ease-in-out infinite; }
30
+ .elapsed { flex: 0 0 auto; min-width: 34px; text-align: right; color: var(--pi-dim, #6b7280); font-size: 11px; font-variant-numeric: tabular-nums; }
31
+ .mark { flex: 0 0 14px; display: flex; justify-content: center; line-height: 1; }
32
+ .check { color: var(--pi-success, #008c82); }
33
+ .end { color: var(--pi-muted, #6b7280); }
34
+ @supports ((-webkit-background-clip: text) or (background-clip: text)) {
35
+ .text.shimmer { color: transparent; background-image: linear-gradient(100deg, var(--pi-text-secondary, #b9c0c7) 20%, var(--pi-text, #e6edf3) 45%, var(--pi-text-secondary, #b9c0c7) 70%);
36
+ background-position: 130% 0; background-size: 220% 100%; -webkit-background-clip: text; background-clip: text; animation: shine 2.4s linear infinite; }
37
+ }
38
+ @keyframes shine { 0% { background-position: 130% 0; } 100% { background-position: -30% 0; } }
39
+ @keyframes breathe { 0%, 100% { opacity: 0.55; } 50% { opacity: 1; } }
40
+ @media (prefers-reduced-motion: reduce) { .text.shimmer { animation: none; background-image: none; color: var(--pi-text-secondary, #b9c0c7); } }
41
+ `;
42
+ function deepFind(selector) {
43
+ const walk = (root) => {
44
+ const direct = root.querySelector(selector);
45
+ if (direct instanceof HTMLElement)
46
+ return direct;
47
+ for (const element of root.querySelectorAll("*")) {
48
+ if (element.shadowRoot) {
49
+ const found = walk(element.shadowRoot);
50
+ if (found)
51
+ return found;
52
+ }
53
+ }
54
+ return null;
55
+ };
56
+ return walk(document);
57
+ }
58
+ function isRecord(value) {
59
+ return typeof value === "object" && value !== null && !Array.isArray(value);
60
+ }
61
+ function parseRow(value) {
62
+ if (!isRecord(value))
63
+ return undefined;
64
+ const status = value["status"];
65
+ if (status !== "active" && status !== "complete" && status !== "failed" && status !== "cancelled")
66
+ return undefined;
67
+ if (typeof value["sessionId"] !== "string" || typeof value["startedAt"] !== "number")
68
+ return undefined;
69
+ return {
70
+ sessionId: value["sessionId"],
71
+ name: typeof value["name"] === "string" ? value["name"] : "Agent",
72
+ subagent: value["subagent"] === true,
73
+ status,
74
+ ...(typeof value["summary"] === "string" ? { summary: value["summary"] } : {}),
75
+ ...(typeof value["summaryAt"] === "number" ? { summaryAt: value["summaryAt"] } : {}),
76
+ startedAt: value["startedAt"],
77
+ ...(typeof value["completedAt"] === "number" ? { completedAt: value["completedAt"] } : {}),
78
+ ...(typeof value["retrospective"] === "string" ? { retrospective: value["retrospective"] } : {}),
79
+ retrospectiveState: value["retrospectiveState"] === "ready" || value["retrospectiveState"] === "pending" || value["retrospectiveState"] === "failed"
80
+ ? value["retrospectiveState"]
81
+ : "none",
82
+ };
83
+ }
84
+ function parseRecord(metadata) {
85
+ if (!isRecord(metadata))
86
+ return undefined;
87
+ const namespaced = metadata[NARRATION_NAMESPACE];
88
+ if (!isRecord(namespaced) || namespaced["v"] !== NARRATION_METADATA_VERSION)
89
+ return undefined;
90
+ if (typeof namespaced["sessionId"] !== "string" || typeof namespaced["executionId"] !== "string")
91
+ return undefined;
92
+ const agent = parseRow(namespaced["agent"]);
93
+ if (agent === undefined)
94
+ return undefined;
95
+ return {
96
+ v: NARRATION_METADATA_VERSION,
97
+ sessionId: namespaced["sessionId"],
98
+ executionId: namespaced["executionId"],
99
+ updatedAt: typeof namespaced["updatedAt"] === "number" ? namespaced["updatedAt"] : Date.now(),
100
+ agent,
101
+ metrics: { succeeded: 0, failed: 0, suppressedDuplicates: 0, skippedUnchanged: 0 },
102
+ };
103
+ }
104
+ /** The host normalizes trailing separators before comparing child paths. */
105
+ function normalizeSessionPath(value) {
106
+ return value.replace(/\\/gu, "/").replace(/\/+$/u, "");
107
+ }
108
+ function parseSessionRows(value) {
109
+ if (!Array.isArray(value))
110
+ return [];
111
+ return value.flatMap((item) => {
112
+ if (!isRecord(item) || typeof item["id"] !== "string")
113
+ return [];
114
+ return [{
115
+ id: item["id"],
116
+ ...(typeof item["path"] === "string" ? { path: item["path"] } : {}),
117
+ ...(typeof item["parentSessionPath"] === "string" ? { parentSessionPath: item["parentSessionPath"] } : {}),
118
+ ...(item["agentSubsession"] === true ? { agentSubsession: true } : {}),
119
+ ...(item["metadata"] === undefined ? {} : { metadata: item["metadata"] }),
120
+ }];
121
+ });
122
+ }
123
+ function elapsedLabel(ms) {
124
+ const total = Math.max(0, Math.floor(ms / 1_000));
125
+ const minutes = Math.floor(total / 60);
126
+ return minutes === 0 ? `${String(total)}s` : `${String(minutes)}:${String(total % 60).padStart(2, "0")}`;
127
+ }
128
+ class NarrationOverlay {
129
+ host;
130
+ panel;
131
+ list;
132
+ views = new Map();
133
+ rows = [];
134
+ hasSubagents = false;
135
+ selectedSessionId;
136
+ selection;
137
+ pollTimer;
138
+ pollAbort;
139
+ polling = false;
140
+ epoch = 0;
141
+ tickTimer;
142
+ resizeObserver;
143
+ composer;
144
+ reservedComposer;
145
+ indicator;
146
+ indicatorProbeAt = 0;
147
+ originalMargin = "";
148
+ marginReserved = false;
149
+ disposed = false;
150
+ constructor() {
151
+ this.host = document.createElement("div");
152
+ this.host.dataset.plugin = "pi-narration";
153
+ this.host.style.display = "none";
154
+ const shadow = this.host.attachShadow({ mode: "open" });
155
+ const style = document.createElement("style");
156
+ style.textContent = STYLE;
157
+ this.panel = document.createElement("div");
158
+ this.panel.className = "wrap";
159
+ const card = document.createElement("div");
160
+ card.className = "panel";
161
+ card.setAttribute("role", "list");
162
+ card.setAttribute("aria-label", "Live activity narration");
163
+ this.list = document.createElement("div");
164
+ this.list.className = "list";
165
+ card.appendChild(this.list);
166
+ this.panel.appendChild(card);
167
+ shadow.append(style, this.panel);
168
+ document.body.appendChild(this.host);
169
+ }
170
+ start(selection) {
171
+ if (this.disposed)
172
+ return;
173
+ this.selection = selection;
174
+ this.selectedSessionId = selection?.getSnapshot()?.selectedSession?.id;
175
+ this.tickTimer = setInterval(() => { this.tick(); }, TICK_MS);
176
+ this.schedulePoll(0);
177
+ }
178
+ updateSelection(selection) {
179
+ if (this.selectedSessionId === selection.selectedSession?.id)
180
+ return;
181
+ this.selectedSessionId = selection.selectedSession?.id;
182
+ this.epoch += 1;
183
+ this.clearRows();
184
+ if (this.pollTimer !== undefined) {
185
+ clearTimeout(this.pollTimer);
186
+ this.pollTimer = undefined;
187
+ }
188
+ this.pollAbort?.abort();
189
+ if (!this.polling)
190
+ void this.poll();
191
+ }
192
+ dispose() {
193
+ this.disposed = true;
194
+ this.pollAbort?.abort();
195
+ if (this.pollTimer !== undefined)
196
+ clearTimeout(this.pollTimer);
197
+ if (this.tickTimer !== undefined)
198
+ clearInterval(this.tickTimer);
199
+ this.resizeObserver?.disconnect();
200
+ this.restoreComposer();
201
+ this.host.remove();
202
+ }
203
+ schedulePoll(delay) {
204
+ if (this.disposed)
205
+ return;
206
+ if (this.pollTimer !== undefined)
207
+ clearTimeout(this.pollTimer);
208
+ this.pollTimer = setTimeout(() => { this.pollTimer = undefined; void this.poll(); }, delay);
209
+ this.pollTimer.unref?.();
210
+ }
211
+ async poll() {
212
+ if (this.disposed || this.polling)
213
+ return;
214
+ if (typeof document !== "undefined" && document.hidden) {
215
+ this.schedulePoll(POLL_IDLE_MS);
216
+ return;
217
+ }
218
+ const snapshot = this.selection?.getSnapshot();
219
+ const session = snapshot?.selectedSession;
220
+ if (session === undefined || session.id !== this.selectedSessionId) {
221
+ this.schedulePoll(POLL_IDLE_MS);
222
+ return;
223
+ }
224
+ const epoch = this.epoch;
225
+ this.polling = true;
226
+ const controller = new AbortController();
227
+ this.pollAbort = controller;
228
+ const timeout = setTimeout(() => { controller.abort(); }, FETCH_TIMEOUT_MS);
229
+ timeout.unref?.();
230
+ let nextDelay = POLL_IDLE_MS;
231
+ try {
232
+ const machineId = snapshot?.selectedMachine?.id ?? "local";
233
+ const endpoint = `api/machines/${encodeURIComponent(machineId)}/sessions?cwd=${encodeURIComponent(session.cwd)}`;
234
+ const response = await fetch(endpoint, { cache: "no-store", signal: controller.signal });
235
+ if (this.disposed || epoch !== this.epoch)
236
+ return;
237
+ if (!response.ok)
238
+ return;
239
+ const sessions = parseSessionRows(await response.json());
240
+ if (this.disposed || epoch !== this.epoch)
241
+ return;
242
+ const own = sessions.find((row) => row.id === session.id);
243
+ const ownRecord = own === undefined ? undefined : parseRecord(own.metadata);
244
+ if (ownRecord === undefined) {
245
+ this.applyRows([]);
246
+ return;
247
+ }
248
+ const parentStarted = ownRecord.agent.startedAt;
249
+ const ownPath = own?.path === undefined ? undefined : normalizeSessionPath(own.path);
250
+ const children = sessions
251
+ .filter((row) => row.id !== session.id && row.agentSubsession === true && ownPath !== undefined && row.parentSessionPath !== undefined && normalizeSessionPath(row.parentSessionPath) === ownPath)
252
+ .flatMap((row) => {
253
+ const record = parseRecord(row.metadata);
254
+ return record === undefined ? [] : [record];
255
+ })
256
+ .filter((record) => record.agent.status === "active" || record.agent.startedAt >= parentStarted)
257
+ .map((record) => record.agent)
258
+ .sort((left, right) => left.startedAt - right.startedAt || left.sessionId.localeCompare(right.sessionId));
259
+ this.applyRows([ownRecord.agent, ...children]);
260
+ nextDelay = this.rows.some((row) => row.status === "active") ? POLL_ACTIVE_MS : POLL_IDLE_MS;
261
+ }
262
+ catch {
263
+ // Keep the last snapshot: a transient fetch failure must not invent progress.
264
+ }
265
+ finally {
266
+ clearTimeout(timeout);
267
+ this.polling = false;
268
+ this.pollAbort = undefined;
269
+ // A selection switch aborted an old poll: repoll immediately for the new session.
270
+ if (!this.disposed)
271
+ this.schedulePoll(this.epoch === epoch ? nextDelay : 0);
272
+ }
273
+ }
274
+ applyRows(rows) {
275
+ if (this.disposed)
276
+ return;
277
+ const visible = rows.filter((row) => {
278
+ if ((row.summary ?? "") !== "")
279
+ return true;
280
+ // Child retrospectives are intentionally shown only in the child's own view.
281
+ return row.sessionId === this.selectedSessionId && row.retrospective !== undefined && row.retrospectiveState === "ready";
282
+ });
283
+ this.rows = visible;
284
+ if (visible.length === 0) {
285
+ this.hide();
286
+ return;
287
+ }
288
+ this.show();
289
+ this.hasSubagents = visible.some((row) => row.subagent);
290
+ this.list.classList.toggle("has-subagents", this.hasSubagents);
291
+ const keep = new Set(visible.map((row) => row.sessionId));
292
+ for (const [sessionId, view] of this.views) {
293
+ if (keep.has(sessionId))
294
+ continue;
295
+ view.root.remove();
296
+ this.views.delete(sessionId);
297
+ }
298
+ const ordered = [];
299
+ for (const row of visible) {
300
+ let view = this.views.get(row.sessionId);
301
+ if (view === undefined) {
302
+ view = this.createRow();
303
+ this.views.set(row.sessionId, view);
304
+ }
305
+ ordered.push(view);
306
+ this.renderRow(row, view);
307
+ }
308
+ // Only touch DOM order when it changed: replaceChildren restarts CSS animations.
309
+ const current = [...this.list.children];
310
+ if (current.length !== ordered.length || ordered.some((view, index) => current[index] !== view.root)) {
311
+ this.list.replaceChildren(...ordered.map((view) => view.root));
312
+ }
313
+ this.dock();
314
+ }
315
+ createRow() {
316
+ const root = document.createElement("div");
317
+ root.className = "row";
318
+ root.setAttribute("role", "listitem");
319
+ const name = document.createElement("span");
320
+ name.className = "name";
321
+ const slot = document.createElement("span");
322
+ slot.className = "slot";
323
+ const text = document.createElement("span");
324
+ text.className = "text";
325
+ text.setAttribute("dir", "auto");
326
+ slot.appendChild(text);
327
+ const elapsed = document.createElement("span");
328
+ elapsed.className = "elapsed";
329
+ const mark = document.createElement("span");
330
+ mark.className = "mark";
331
+ root.append(name, slot, elapsed, mark);
332
+ return { root, name, slot, text, elapsed, mark };
333
+ }
334
+ renderRow(row, view) {
335
+ const active = row.status === "active";
336
+ const ownThread = row.sessionId === this.selectedSessionId;
337
+ const retro = ownThread && !active && row.retrospectiveState === "ready" ? row.retrospective : undefined;
338
+ const text = retro ?? row.summary ?? "";
339
+ // The main row labels its gutter only when a subagent gutter exists to match.
340
+ const name = row.subagent ? row.name : this.hasSubagents ? "Main session" : "";
341
+ const stamp = `${row.status}|${text}|${name}|${retro === undefined ? "0" : "1"}`;
342
+ if (view.stamp !== stamp) {
343
+ view.stamp = stamp;
344
+ if (view.name.textContent !== name)
345
+ view.name.textContent = name;
346
+ view.name.title = name === "" ? row.name : name;
347
+ if (view.text.textContent !== text)
348
+ view.text.textContent = text;
349
+ view.text.title = text;
350
+ view.text.classList.toggle("shimmer", active);
351
+ view.text.classList.toggle("retro", retro !== undefined);
352
+ view.slot.style.height = retro === undefined ? "36px" : "auto";
353
+ this.renderStatus(row, view);
354
+ }
355
+ this.renderTimer(row, view);
356
+ }
357
+ renderStatus(row, view) {
358
+ if (row.status === "complete") {
359
+ const check = document.createElement("span");
360
+ check.className = "check";
361
+ check.textContent = "✓";
362
+ check.setAttribute("role", "img");
363
+ check.setAttribute("aria-label", "Completed");
364
+ view.mark.replaceChildren(check);
365
+ }
366
+ else if (row.status === "failed" || row.status === "cancelled") {
367
+ const end = document.createElement("span");
368
+ end.className = "end";
369
+ end.textContent = "✕";
370
+ end.setAttribute("role", "img");
371
+ end.setAttribute("aria-label", row.status === "failed" ? "Failed" : "Cancelled");
372
+ view.mark.replaceChildren(end);
373
+ }
374
+ else {
375
+ view.mark.replaceChildren();
376
+ }
377
+ }
378
+ renderTimer(row, view) {
379
+ const elapsed = Math.max(0, (row.completedAt ?? Date.now()) - row.startedAt);
380
+ view.elapsed.textContent = elapsedLabel(elapsed);
381
+ }
382
+ tick() {
383
+ if (this.disposed)
384
+ return;
385
+ for (const row of this.rows) {
386
+ const view = this.views.get(row.sessionId);
387
+ if (view !== undefined)
388
+ this.renderTimer(row, view);
389
+ }
390
+ if (this.rows.some((row) => row.status === "active"))
391
+ this.dock();
392
+ }
393
+ hide() {
394
+ this.rows = [];
395
+ this.host.style.display = "none";
396
+ this.restoreComposer();
397
+ }
398
+ show() {
399
+ this.host.style.display = "flex";
400
+ }
401
+ clearRows() {
402
+ this.rows = [];
403
+ this.views.clear();
404
+ this.list.replaceChildren();
405
+ this.hide();
406
+ }
407
+ dock() {
408
+ if (this.disposed)
409
+ return;
410
+ if (this.composer === undefined || !this.composer.isConnected) {
411
+ const found = deepFind("prompt-editor");
412
+ this.composer = found ?? undefined;
413
+ if (this.composer !== undefined) {
414
+ this.resizeObserver?.disconnect();
415
+ this.resizeObserver = new ResizeObserver(() => { this.dock(); });
416
+ this.resizeObserver.observe(this.composer);
417
+ }
418
+ }
419
+ const composerRect = this.composer?.getBoundingClientRect();
420
+ const composerTop = composerRect?.top;
421
+ // The compact activity indicator floats across the composer border; dock above
422
+ // its top edge so narration never covers the "message started/receiving" line.
423
+ // Probe sparingly: the full-document walk is expensive on the active-work hot path.
424
+ if (this.indicator === undefined || !this.indicator.isConnected) {
425
+ const now = Date.now();
426
+ if (now - this.indicatorProbeAt >= INDICATOR_PROBE_MS) {
427
+ this.indicatorProbeAt = now;
428
+ this.indicator = deepFind(".activity-dock") ?? undefined;
429
+ }
430
+ }
431
+ const indicatorRect = this.indicator?.getBoundingClientRect();
432
+ const overlayHeight = this.panel.getBoundingClientRect().height || 46;
433
+ const dockVisible = indicatorRect !== undefined && indicatorRect.height > 0;
434
+ // Prefer the reserved band between the dock and the composer; fall back above
435
+ // the dock when the band is too short for the rows.
436
+ const fitsBelowDock = dockVisible && typeof composerTop === "number"
437
+ && composerTop - DOCK_GAP - overlayHeight >= indicatorRect.bottom;
438
+ const ceiling = typeof composerTop !== "number"
439
+ ? undefined
440
+ : dockVisible && !fitsBelowDock
441
+ ? Math.min(composerTop, indicatorRect.top)
442
+ : composerTop;
443
+ const bottom = ceiling === undefined ? FALLBACK_COMPOSER : innerHeight - ceiling + DOCK_GAP;
444
+ this.host.style.bottom = `${String(Math.max(0, bottom))}px`;
445
+ // Match the composer column exactly instead of spanning the whole viewport.
446
+ this.host.style.left = composerRect === undefined ? "0px" : `${String(Math.round(composerRect.left))}px`;
447
+ this.host.style.right = composerRect === undefined ? "0px" : `${String(Math.max(0, Math.round(innerWidth - composerRect.right)))}px`;
448
+ const height = this.panel.getBoundingClientRect().height || 46;
449
+ // Reserve a fixed dock band so the composer never jumps when the indicator appears.
450
+ const reserve = `${String(Math.round(height + DOCK_GAP + DOCK_BAND))}px`;
451
+ if (this.composer !== undefined && this.composer.style.marginTop !== reserve) {
452
+ if (!this.marginReserved)
453
+ this.originalMargin = this.composer.style.marginTop;
454
+ this.marginReserved = true;
455
+ this.reservedComposer = this.composer;
456
+ this.composer.style.marginTop = reserve;
457
+ }
458
+ }
459
+ restoreComposer() {
460
+ const target = this.reservedComposer?.isConnected === true ? this.reservedComposer : this.composer;
461
+ if (target !== undefined && this.marginReserved) {
462
+ target.style.marginTop = this.originalMargin;
463
+ this.originalMargin = "";
464
+ this.marginReserved = false;
465
+ }
466
+ this.reservedComposer = undefined;
467
+ }
468
+ }
469
+ const plugin = {
470
+ apiVersion: 5,
471
+ name: "Narration",
472
+ activate(context) {
473
+ const overlay = new NarrationOverlay();
474
+ const unsubscribe = context.selection?.subscribe((snapshot) => { overlay.updateSelection(snapshot); });
475
+ overlay.start(context.selection);
476
+ return {
477
+ contributions: {},
478
+ dispose: () => {
479
+ unsubscribe?.();
480
+ overlay.dispose();
481
+ },
482
+ };
483
+ },
484
+ };
485
+ export default plugin;