@erdemtuna/doc-review 0.8.1 → 0.10.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.
Files changed (82) hide show
  1. package/README.md +52 -137
  2. package/{src → lib}/SKILL.md +28 -4
  3. package/lib/anchor-text.js +155 -0
  4. package/lib/atomic-write.js +54 -0
  5. package/lib/chrome-api.js +78 -0
  6. package/lib/chrome-client.js +2255 -0
  7. package/lib/chrome-session.js +76 -0
  8. package/{src → lib}/chrome.css +253 -8
  9. package/lib/chrome.html +196 -0
  10. package/lib/cli.js +255 -0
  11. package/lib/click-target.js +28 -0
  12. package/lib/comment-anchor.js +23 -0
  13. package/lib/comment-target.js +164 -0
  14. package/lib/comparison-view.js +380 -0
  15. package/lib/contracts/feedback.js +1 -0
  16. package/lib/contracts/frame.js +7 -0
  17. package/lib/contracts/history.js +1 -0
  18. package/lib/contracts/index.js +2 -0
  19. package/lib/contracts/page.js +23 -0
  20. package/lib/document-execution.js +115 -0
  21. package/lib/document-trust.js +2 -0
  22. package/lib/edit-limits.js +24 -0
  23. package/lib/editing.js +107 -0
  24. package/lib/execution-client.js +69 -0
  25. package/lib/feedback-controller.js +106 -0
  26. package/lib/frame-channel.js +42 -0
  27. package/lib/frame-controller.js +313 -0
  28. package/lib/frame-host.js +136 -0
  29. package/lib/frame-policy.js +50 -0
  30. package/lib/history-client.js +112 -0
  31. package/lib/history-coordinator.js +210 -0
  32. package/lib/history-policy.js +43 -0
  33. package/lib/history-server.js +464 -0
  34. package/lib/html-transform.js +52 -0
  35. package/lib/icons.js +249 -0
  36. package/{src → lib}/markdown.js +25 -26
  37. package/lib/paths.js +83 -0
  38. package/lib/poll-transport.js +220 -0
  39. package/lib/positioning.js +97 -0
  40. package/lib/review-controller.js +93 -0
  41. package/lib/review-mode.js +66 -0
  42. package/lib/revision-diff.js +482 -0
  43. package/lib/revision-schema.js +235 -0
  44. package/lib/revision-store.js +190 -0
  45. package/lib/save-controller.js +300 -0
  46. package/lib/sdk.js +2629 -0
  47. package/lib/semantic-snapshot.js +268 -0
  48. package/lib/serialize.js +32 -0
  49. package/lib/server-entry.js +26 -0
  50. package/lib/server-lock.js +109 -0
  51. package/lib/server.js +1501 -0
  52. package/lib/setup-guidance.js +119 -0
  53. package/{src → lib}/setup.js +44 -55
  54. package/lib/state.js +733 -0
  55. package/lib/view-identity.js +112 -0
  56. package/package.json +24 -12
  57. package/src/anchor-text.js +0 -160
  58. package/src/atomic-write.js +0 -53
  59. package/src/chrome-client.js +0 -2006
  60. package/src/chrome-session.js +0 -85
  61. package/src/chrome.html +0 -129
  62. package/src/cli.js +0 -267
  63. package/src/click-target.js +0 -26
  64. package/src/comment-anchor.js +0 -22
  65. package/src/comment-target.js +0 -77
  66. package/src/edit-limits.js +0 -23
  67. package/src/editing.js +0 -99
  68. package/src/frame-channel.js +0 -44
  69. package/src/frame-policy.js +0 -16
  70. package/src/html-transform.js +0 -62
  71. package/src/icons.js +0 -251
  72. package/src/paths.js +0 -91
  73. package/src/poll-transport.js +0 -222
  74. package/src/positioning.js +0 -107
  75. package/src/review-mode.js +0 -59
  76. package/src/sdk.js +0 -2243
  77. package/src/serialize.js +0 -32
  78. package/src/server-entry.js +0 -26
  79. package/src/server-lock.js +0 -101
  80. package/src/server.js +0 -1298
  81. package/src/setup-guidance.js +0 -128
  82. package/src/state.js +0 -507
@@ -0,0 +1,2255 @@
1
+ /**
2
+ * doc-review chrome. Owns the toolbar, contextual surfaces, drawer, and every
3
+ * call to the local server.
4
+ * It never touches the artifact DOM directly — the SDK does that, over
5
+ * postMessage, because the artifact iframe lives on the other loopback
6
+ * hostname: a separate origin that can never reach this page or its token.
7
+ */
8
+ import { tidyMiddle } from "./anchor-text.js";
9
+ import { clearOwned, createCommentUi, migrateCommentUi, mutationIsCurrent, ownConfirmation, ownEdit, ownMenu, newestComments, pageUrl, reconcileCommentUi, replacePage, } from "./chrome-session.js";
10
+ import { sanitizeClientRects, sanitizeClipRect, sanitizeRelation } from "./comment-target.js";
11
+ import { externalHref } from "./editing.js";
12
+ import { framePolicy } from "./frame-policy.js";
13
+ import { createIcon } from "./icons.js";
14
+ import { createComparisonView } from "./comparison-view.js";
15
+ import { createExecutionControls } from "./execution-client.js";
16
+ import { alignedCardPosition, placeContextualSurface, visibleViewport } from "./positioning.js";
17
+ import { normalizeReviewMode, reviewConfiguration } from "./review-mode.js";
18
+ import { createCaptureRequests, captureError, sameRender, draftCount, excerpt, changeKind, pendingCaptureTarget, comparisonFreshness } from "./history-client.js";
19
+ import { createCaptureCoordinator, createHistoryController, historyPresentation, requireCaptureSuccess } from "./history-coordinator.js";
20
+ import { createReviewApi, decodePage } from "./chrome-api.js";
21
+ import { createFrameHost } from "./frame-host.js";
22
+ import { createFrameController } from "./frame-controller.js";
23
+ import { createSaveController } from "./save-controller.js";
24
+ import { createFeedbackController } from "./feedback-controller.js";
25
+ import { createReviewController } from "./review-controller.js";
26
+ const $ = (id) => document.getElementById(id);
27
+ const ARTIFACT_HOST = location.hostname === "127.0.0.1" ? "localhost" : "127.0.0.1";
28
+ const ARTIFACT_ORIGIN = `${location.protocol}//${ARTIFACT_HOST}:${location.port}`;
29
+ const frameHost = createFrameHost($("frame"), ARTIFACT_ORIGIN);
30
+ const uiLifetime = new AbortController();
31
+ const uiTimers = new Set();
32
+ const uiFrames = new Set();
33
+ function afterPaint(callback) {
34
+ const id = requestAnimationFrame(() => {
35
+ uiFrames.delete(id);
36
+ if (!uiLifetime.signal.aborted)
37
+ callback();
38
+ });
39
+ uiFrames.add(id);
40
+ }
41
+ function afterDelay(callback, milliseconds) {
42
+ const id = setTimeout(() => {
43
+ uiTimers.delete(id);
44
+ if (!uiLifetime.signal.aborted)
45
+ callback();
46
+ }, milliseconds);
47
+ uiTimers.add(id);
48
+ }
49
+ function listen(target, type, handler, options = {}) {
50
+ target.addEventListener(type, handler, {
51
+ ...(typeof options === "boolean" ? { capture: options } : options),
52
+ signal: uiLifetime.signal,
53
+ });
54
+ }
55
+ const state = {
56
+ sessionId: document.body.dataset.session,
57
+ token: document.body.dataset.token,
58
+ page: null,
59
+ compose: null,
60
+ composeLifecycle: "closed",
61
+ composePlacement: "hidden",
62
+ target: null,
63
+ activeSavedCommentId: null,
64
+ activeGeometry: new Map(),
65
+ commentUi: createCommentUi(),
66
+ pageEpoch: 0,
67
+ reviewMode: "view",
68
+ savePolicy: "writable",
69
+ modeApplying: false,
70
+ modeMenuOpen: false,
71
+ drawerOpen: false,
72
+ agent: "idle",
73
+ orphans: new Set(),
74
+ pollCommand: "",
75
+ editsExpanded: false,
76
+ others: [],
77
+ scroll: { x: 0, y: 0 },
78
+ comparing: false,
79
+ executionPreference: null,
80
+ ended: false,
81
+ };
82
+ const diagnostic = (event, detail = {}) => {
83
+ console.info("[doc-review]", { event, ...detail });
84
+ };
85
+ const patchFlights = new Map();
86
+ const deleteFlights = new Map();
87
+ let requestedFocus = null;
88
+ let editFocusRequested = false;
89
+ let skipEditCaptureOnce = false;
90
+ function advancePageEpoch(reason) {
91
+ state.pageEpoch += 1;
92
+ diagnostic("page-epoch-advanced", { epoch: state.pageEpoch, reason });
93
+ return state.pageEpoch;
94
+ }
95
+ function commentById(id) {
96
+ return state.page?.comments?.find((comment) => comment.id === id) || null;
97
+ }
98
+ function domId(value) {
99
+ return String(value).replace(/[^a-zA-Z0-9_-]/g, (char) => `-${char.codePointAt(0).toString(16)}-`);
100
+ }
101
+ function controlId(commentId, surface, action) {
102
+ return `comment-${surface}-${domId(commentId)}-${action}`;
103
+ }
104
+ function requestControlFocus(id) {
105
+ requestedFocus = id;
106
+ }
107
+ function editTextarea(commentId) {
108
+ const root = state.drawerOpen ? $("cards") : $("alignedCard");
109
+ return root?.querySelector(`textarea[data-comment-edit="${CSS.escape(commentId)}"]`) || null;
110
+ }
111
+ function captureEditState() {
112
+ const edit = state.commentUi.edit;
113
+ if (!edit)
114
+ return false;
115
+ const input = editTextarea(edit.commentId);
116
+ if (!input)
117
+ return false;
118
+ edit.draft = input.value;
119
+ edit.selectionStart = input.selectionStart;
120
+ edit.selectionEnd = input.selectionEnd;
121
+ return document.activeElement === input;
122
+ }
123
+ function restoreTransientFocus(editWasFocused = false) {
124
+ const focusId = requestedFocus;
125
+ requestedFocus = null;
126
+ const shouldFocusEdit = editWasFocused || editFocusRequested;
127
+ afterPaint(() => {
128
+ if (focusId) {
129
+ document.getElementById(focusId)?.focus();
130
+ return;
131
+ }
132
+ const edit = state.commentUi.edit;
133
+ if (!shouldFocusEdit || !edit)
134
+ return;
135
+ const input = editTextarea(edit.commentId);
136
+ if (!input || input.closest("[hidden]")) {
137
+ editFocusRequested = true;
138
+ return;
139
+ }
140
+ editFocusRequested = false;
141
+ input.focus();
142
+ input.setSelectionRange(edit.selectionStart, edit.selectionEnd);
143
+ });
144
+ }
145
+ function moveTransientSurface(surface) {
146
+ const menu = state.commentUi.menu;
147
+ if (menu) {
148
+ menu.surface = surface;
149
+ menu.triggerId = controlId(menu.commentId, surface, "more");
150
+ }
151
+ if (state.commentUi.confirmation)
152
+ state.commentUi.confirmation.surface = surface;
153
+ }
154
+ function announce(message) {
155
+ const region = $("liveRegion");
156
+ region.textContent = "";
157
+ afterPaint(() => {
158
+ region.textContent = message;
159
+ });
160
+ }
161
+ function replaceIcon(container, name, title = "") {
162
+ container.textContent = "";
163
+ container.append(createIcon(name, { title }));
164
+ }
165
+ function installStaticIcons() {
166
+ document.querySelectorAll("[data-icon]").forEach((container) => {
167
+ replaceIcon(container, container.dataset.icon);
168
+ });
169
+ replaceIcon($("modeChevron"), "chevronDown");
170
+ replaceIcon($("composeClose"), "x");
171
+ replaceIcon($("drawerClose"), "x");
172
+ }
173
+ function openModeMenu() {
174
+ if (state.modeMenuOpen)
175
+ return;
176
+ state.modeMenuOpen = true;
177
+ $("modeMenu").hidden = false;
178
+ $("modeButton").setAttribute("aria-expanded", "true");
179
+ toFrame({ type: "eh:modeMenuState", open: true });
180
+ $("modeMenu").querySelector(`[data-mode="${state.reviewMode}"]`)?.focus();
181
+ }
182
+ function closeModeMenu(reason = "dismissed", { restoreFocus = false } = {}) {
183
+ if (!state.modeMenuOpen)
184
+ return false;
185
+ state.modeMenuOpen = false;
186
+ $("modeMenu").hidden = true;
187
+ $("modeButton").setAttribute("aria-expanded", "false");
188
+ toFrame({ type: "eh:modeMenuState", open: false });
189
+ diagnostic("mode-menu-close", { reason });
190
+ if (restoreFocus)
191
+ $("modeButton").focus();
192
+ return true;
193
+ }
194
+ function openDrawer() {
195
+ captureEditState();
196
+ skipEditCaptureOnce = true;
197
+ state.drawerOpen = true;
198
+ moveTransientSurface("drawer");
199
+ editFocusRequested = !!state.commentUi.edit;
200
+ render();
201
+ if (!state.commentUi.edit)
202
+ afterPaint(() => $("commentsSection").focus());
203
+ }
204
+ function closeDrawer() {
205
+ if (!state.drawerOpen)
206
+ return;
207
+ captureEditState();
208
+ skipEditCaptureOnce = true;
209
+ state.drawerOpen = false;
210
+ const transientOwner = state.commentUi.edit?.commentId ||
211
+ state.commentUi.confirmation?.commentId ||
212
+ state.commentUi.menu?.commentId ||
213
+ null;
214
+ if (transientOwner && commentById(transientOwner)) {
215
+ state.activeSavedCommentId = transientOwner;
216
+ moveTransientSurface("aligned");
217
+ toFrame({ type: "eh:activate", id: transientOwner, scroll: false });
218
+ }
219
+ else if (state.activeSavedCommentId) {
220
+ moveTransientSurface("aligned");
221
+ }
222
+ editFocusRequested = !!state.commentUi.edit;
223
+ render();
224
+ if (!state.commentUi.edit)
225
+ $("commentsButton").focus();
226
+ }
227
+ function setComposeLifecycle(next, reason) {
228
+ if (state.composeLifecycle === next)
229
+ return;
230
+ const from = state.composeLifecycle;
231
+ state.composeLifecycle = next;
232
+ const submitting = next === "submitting";
233
+ $("composeCancel").disabled = submitting;
234
+ $("composeClose").disabled = submitting;
235
+ diagnostic("composer-lifecycle-transition", { from, to: next, reason });
236
+ }
237
+ function setComposePlacement(next) {
238
+ if (state.composePlacement === next)
239
+ return;
240
+ const from = state.composePlacement;
241
+ state.composePlacement = next;
242
+ diagnostic("placement-transition", { from, to: next });
243
+ }
244
+ /**
245
+ * Most reviewers drive an agent from a chat (Claude Code, Codex, Cursor), not
246
+ * a bare terminal — so the handoff is a prompt the agent can act on, with the
247
+ * poll command embedded for anyone who does live in a shell.
248
+ */
249
+ function handoffPrompt(pollCommand) {
250
+ const cmd = String(pollCommand || "").trim();
251
+ if (!cmd)
252
+ return "";
253
+ return `Run \`${cmd} --timeout 600\`, apply the feedback it returns, then run its exact \`next_step\` command with \`--ack <batch_id>\` until I end the review.`;
254
+ }
255
+ // ------------------------------------------------------------------- server
256
+ const transport = createReviewApi({ token: state.token });
257
+ const api = transport.request;
258
+ const frameController = createFrameController({
259
+ sessionId: state.sessionId, host: frameHost, request: api,
260
+ suspended() {
261
+ captures.cancel();
262
+ captureCoordinator.reset();
263
+ manualCaptureController?.abort();
264
+ },
265
+ transitioning() {
266
+ reviewController.invalidate();
267
+ if (state.compose) {
268
+ state.compose.unresolved = true;
269
+ state.compose.relation = "unavailable";
270
+ state.compose.rects = [];
271
+ state.compose.generation = -1;
272
+ }
273
+ state.target = null;
274
+ state.activeGeometry.clear();
275
+ saveController.baseline(null);
276
+ },
277
+ failed(message) {
278
+ $("reloadNotice").hidden = false;
279
+ $("reloadMessage").textContent = `${message} Reload keeps your comment drafts.`;
280
+ toast(message);
281
+ },
282
+ });
283
+ const saveController = createSaveController({
284
+ sessionId: state.sessionId, current: () => frameController.identity(),
285
+ policy: () => state.savePolicy, request: api,
286
+ flush: (strict) => frameController.flush(strict), send: (message) => frameController.send(message),
287
+ sourceHash: (hash) => frameController.setSourceHash(hash),
288
+ pageChanged(page) { state.page = page; feedbackController.clearSent(); render(); },
289
+ conflict() { holdReload(); announce("Save conflict. Edit mode remains active so you can reload safely."); },
290
+ failed(message) { toast(message); announce("An edit could not be saved. Retry before leaving the page or sending feedback."); },
291
+ diagnostic, sending: () => feedbackController.sending,
292
+ });
293
+ const feedbackController = createFeedbackController({
294
+ sessionId: state.sessionId, current: () => frameController.identity(),
295
+ sourceHash: () => frameController.state.sourceHash, save: saveController,
296
+ policy: () => state.savePolicy, request: api,
297
+ capture: () => captureStablePage({ timeout: 500 }), refresh: () => refreshHistory(),
298
+ note: () => $("note").value,
299
+ clearNote(sent) { if ($("note").value === sent)
300
+ $("note").value = ""; },
301
+ pauseCapture() {
302
+ if ($("captureWarning"))
303
+ $("captureWarning").hidden = true;
304
+ captureCoordinator.reset();
305
+ manualCaptureController?.abort();
306
+ },
307
+ resumeCapture: () => scheduleResultCapture(),
308
+ failed(message) { toast(message); announce(message); },
309
+ warning: toast, announce,
310
+ });
311
+ const reviewController = createReviewController({
312
+ sessionId: state.sessionId, key: () => frameController.state.key,
313
+ generation: () => frameController.state.generation, request: api,
314
+ beforeRefresh: () => advancePageEpoch("acknowledgement"),
315
+ refreshPage(page) {
316
+ reconcilePage(page, { syncAnchors: true, reason: "acknowledgement", advance: false });
317
+ feedbackController.clearSent();
318
+ render();
319
+ },
320
+ load: async (key) => { state.scroll = { x: 0, y: 0 }; await loadPage(key); },
321
+ reload: () => reloadLatest(), history: () => refreshHistory(),
322
+ save: () => saveController.barrier(), suspend: () => frameController.suspend(),
323
+ hasDrafts: () => !!draftCount(state),
324
+ agent(value) { state.agent = value; render(); },
325
+ ended: showEnded, failed: (error) => { toast(error.message || String(error)); },
326
+ });
327
+ reviewController.own(frameController.subscribe(renderExecution));
328
+ reviewController.own(saveController.subscribe(renderSave));
329
+ reviewController.own(feedbackController.subscribe(render));
330
+ reviewController.own(() => uiLifetime.abort());
331
+ reviewController.own(() => {
332
+ for (const id of uiTimers)
333
+ clearTimeout(id);
334
+ for (const id of uiFrames)
335
+ cancelAnimationFrame(id);
336
+ uiTimers.clear();
337
+ uiFrames.clear();
338
+ });
339
+ reviewController.own(() => frameController.dispose());
340
+ reviewController.own(() => saveController.dispose());
341
+ reviewController.own(() => feedbackController.dispose());
342
+ reviewController.own(() => transport.dispose());
343
+ const executionControls = createExecutionControls({
344
+ api,
345
+ sessionId: state.sessionId,
346
+ elements: {
347
+ static: $("executionStatic"), auto: $("executionAuto"), status: $("executionStatus"),
348
+ details: $("executionDetails"), menu: $("reviewDetails"),
349
+ editDescription: $("modeMenu").querySelector('[data-mode="edit"] small'),
350
+ },
351
+ changed(page) {
352
+ if (!page || page.key !== frameController.state.key)
353
+ return;
354
+ state.executionPreference = page.executionPreference || null;
355
+ state.page = {
356
+ ...state.page,
357
+ executionPreference: page.executionPreference,
358
+ ...frameController.state.execution,
359
+ };
360
+ state.savePolicy = reviewConfiguration(state.page, state.reviewMode).savePolicy;
361
+ render();
362
+ },
363
+ failed(error) { toast(error.message || String(error)); },
364
+ });
365
+ const toolbar = document.querySelector(".toolbar");
366
+ const toolbarObserver = new ResizeObserver(() => {
367
+ document.documentElement.style.setProperty("--toolbar-h", `${toolbar.getBoundingClientRect().height}px`);
368
+ });
369
+ toolbarObserver.observe(toolbar);
370
+ reviewController.own(() => toolbarObserver.disconnect());
371
+ function renderExecution() {
372
+ executionControls.render(state.page, frameHost.visibleExecution, {
373
+ pendingReload: frameController.state.pendingReload || !!frameHost.previous,
374
+ loading: frameController.loading,
375
+ error: frameController.state.phase.kind === "failed" ? frameController.state.phase.message : null,
376
+ });
377
+ }
378
+ const persistEdit = (key, payload) => saveController.persistEdit(key, payload);
379
+ const settleEditPersistence = (key) => saveController.settleEdits(key);
380
+ function reconcilePage(page, { syncAnchors = false, reason = "mutation", advance = reason !== "mutation" } = {}) {
381
+ const previousIds = new Set((state.page?.comments || []).map((comment) => comment.id));
382
+ if (advance)
383
+ advancePageEpoch(reason);
384
+ replacePage(state, page);
385
+ const commentIds = new Set((page.comments || []).map((comment) => comment.id));
386
+ for (const id of state.activeGeometry.keys()) {
387
+ if (!commentIds.has(id))
388
+ state.activeGeometry.delete(id);
389
+ }
390
+ if (state.activeSavedCommentId && !commentIds.has(state.activeSavedCommentId)) {
391
+ state.activeSavedCommentId = null;
392
+ }
393
+ const removedTransient = reconcileCommentUi(state.commentUi, page.comments || []);
394
+ state.orphans = new Set([...state.orphans].filter((id) => commentIds.has(id)));
395
+ if (syncAnchors && !frameController.loading) {
396
+ toFrame({ type: "eh:anchors", comments: page.comments || [] });
397
+ }
398
+ if (reason === "acknowledgement") {
399
+ const removed = [...previousIds].filter((id) => !commentIds.has(id));
400
+ if (removed.length) {
401
+ announce(`${removed.length === 1 ? "Comment" : "Comments"} delivered and removed`);
402
+ if (removedTransient.size)
403
+ afterPaint(() => (state.drawerOpen ? $("commentsSection") : frameHost.current).focus());
404
+ }
405
+ }
406
+ diagnostic("page-reconciled", { reason, epoch: state.pageEpoch });
407
+ }
408
+ const toFrame = (message) => frameController.send(message);
409
+ function beginFrameTransition(key = frameController.state.key) {
410
+ return frameController.begin(key);
411
+ }
412
+ const registerFrame = (key, generation) => frameController.register(key, generation);
413
+ const failFrame = (message) => frameController.fail(message);
414
+ const flushFrame = ({ strict = false } = {}) => saveController.flush(strict);
415
+ function configureFrame() {
416
+ if (!frameController.state.execution)
417
+ return Promise.resolve(false);
418
+ Object.assign(state.page, frameController.state.execution);
419
+ const configuration = reviewConfiguration(state.page, state.reviewMode);
420
+ state.savePolicy = configuration.savePolicy;
421
+ return frameController.configure(configuration.mode, configuration.savePolicy);
422
+ }
423
+ async function setReviewMode(nextMode) {
424
+ const next = normalizeReviewMode(nextMode);
425
+ closeModeMenu("selection");
426
+ if (next === state.reviewMode || state.modeApplying)
427
+ return;
428
+ state.modeApplying = true;
429
+ render();
430
+ try {
431
+ if (state.reviewMode === "edit" && next === "view") {
432
+ await fullSaveBarrier();
433
+ if (saveController.state.conflict) {
434
+ toast("Resolve the save conflict before leaving Edit");
435
+ announce("Save conflict. Edit mode remains active.");
436
+ return;
437
+ }
438
+ }
439
+ state.reviewMode = next;
440
+ const applied = await configureFrame();
441
+ if (!applied)
442
+ throw new Error("The reviewed page did not confirm the mode change");
443
+ diagnostic("mode-change", { mode: next, savePolicy: state.savePolicy });
444
+ announce(`${next === "edit" ? "Edit" : "View"} mode active`);
445
+ }
446
+ catch (err) {
447
+ state.reviewMode = next === "edit" ? "view" : "edit";
448
+ toast(`${err.message}. Stay in ${state.reviewMode === "edit" ? "Edit" : "View"} and retry.`);
449
+ }
450
+ finally {
451
+ state.modeApplying = false;
452
+ render();
453
+ }
454
+ }
455
+ async function loadPage(key, { reload = true } = {}) {
456
+ const returning = state.page;
457
+ advancePageEpoch(returning ? "navigation" : "reload");
458
+ const generation = beginFrameTransition(key);
459
+ frameController.resetRetries();
460
+ const page = await api(pageUrl(key, state.sessionId), undefined, decodePage);
461
+ if (frameController.state.key !== key || frameController.state.generation !== generation)
462
+ return;
463
+ state.executionPreference = page.executionPreference || null;
464
+ reconcilePage(page, { reason: "reload", advance: false });
465
+ state.savePolicy = reviewConfiguration(state.page, state.reviewMode).savePolicy;
466
+ frameController.setPolicy(framePolicy(state.page, ARTIFACT_ORIGIN));
467
+ state.orphans = new Set();
468
+ state.compose = null;
469
+ setComposeLifecycle("closed", "page-change");
470
+ setComposePlacement("hidden");
471
+ state.target = null;
472
+ state.activeSavedCommentId = null;
473
+ state.activeGeometry.clear();
474
+ state.commentUi = createCommentUi();
475
+ feedbackController.clearSent();
476
+ saveController.reset();
477
+ if (reload) {
478
+ frameController.startReload();
479
+ await registerFrame(key, generation);
480
+ }
481
+ render();
482
+ // Coming back to a dev-server page shows the app's own copy again, without
483
+ // the direct edits — which reads as data loss unless we say what happened.
484
+ const edits = state.page.edits ? state.page.edits.length : 0;
485
+ if (returning && state.page.feedbackOnly && edits > 0) {
486
+ toast(`${edits} ${edits === 1 ? "edit is" : "edits are"} queued for the agent to apply to the source`);
487
+ }
488
+ }
489
+ // -------------------------------------------------------------------- clock
490
+ function ago(ts) {
491
+ const secs = Math.max(0, Math.round((Date.now() - ts) / 1000));
492
+ if (secs < 45)
493
+ return "just now";
494
+ const mins = Math.round(secs / 60);
495
+ if (mins < 60)
496
+ return `${mins}m`;
497
+ const hours = Math.round(mins / 60);
498
+ if (hours < 24)
499
+ return `${hours}h`;
500
+ return `${Math.round(hours / 24)}d`;
501
+ }
502
+ // -------------------------------------------------------------------- render
503
+ function render() {
504
+ if (state.ended)
505
+ return;
506
+ const page = state.page;
507
+ if (!page)
508
+ return;
509
+ // Source updates cannot change the policy of a frame awaiting draft-safe reload.
510
+ if (frameController.state.execution)
511
+ Object.assign(page, frameController.state.execution);
512
+ if (state.executionPreference)
513
+ page.executionPreference = state.executionPreference;
514
+ renderExecution();
515
+ syncFrameInteraction();
516
+ const editWasFocused = skipEditCaptureOnce ? false : captureEditState();
517
+ skipEditCaptureOnce = false;
518
+ document.title = page.filename || 'doc-review';
519
+ const comments = newestComments(page.comments);
520
+ const edits = page.edits || [];
521
+ $("count").textContent = String(comments.length);
522
+ $("toolbarCount").textContent = String(comments.length);
523
+ $("empty").hidden = comments.length > 0 || !!state.compose;
524
+ $("modeLabel").textContent = state.reviewMode === "edit" ? "Edit" : "View";
525
+ replaceIcon($("modeIcon"), state.reviewMode === "edit" ? "pencil" : "eye");
526
+ $("modeButton").disabled = state.modeApplying || state.comparing || feedbackController.sending || !frameController.state.execution;
527
+ for (const item of $("modeMenu").querySelectorAll("[data-mode]")) {
528
+ const checked = item.dataset.mode === state.reviewMode;
529
+ item.setAttribute("aria-checked", String(checked));
530
+ const check = item.querySelector(".menu-check");
531
+ check.textContent = "";
532
+ if (checked)
533
+ check.append(createIcon("check"));
534
+ }
535
+ $("drawer").classList.toggle("open", state.drawerOpen);
536
+ $("drawer").setAttribute("aria-hidden", String(!state.drawerOpen));
537
+ $("commentsButton").setAttribute("aria-expanded", String(state.drawerOpen));
538
+ $("drawerBackdrop").hidden = !state.drawerOpen;
539
+ // --- compose
540
+ const composeWrap = $("compose");
541
+ if (state.compose) {
542
+ composeWrap.hidden = false;
543
+ $("composeKind").textContent = state.compose.kind === "element" ? "Element" : "Selection";
544
+ $("composeQuote").textContent = tidyMiddle(state.compose.quote, 260);
545
+ afterPaint(positionCompose);
546
+ }
547
+ else {
548
+ composeWrap.hidden = true;
549
+ $("composeText").value = "";
550
+ $("composeError").hidden = true;
551
+ }
552
+ // --- comment cards
553
+ const list = $("cards");
554
+ list.textContent = "";
555
+ for (const comment of comments) {
556
+ list.append(renderCommentCard(comment, "drawer"));
557
+ }
558
+ renderAlignedCard(comments);
559
+ // --- your edits
560
+ const box = $("editsBox");
561
+ box.hidden = edits.length === 0;
562
+ if (edits.length) {
563
+ $("editCount").textContent = String(edits.length);
564
+ const rows = $("editList");
565
+ rows.textContent = "";
566
+ const LIMIT = 5;
567
+ const shown = state.editsExpanded ? edits : edits.slice(0, LIMIT);
568
+ for (const edit of shown) {
569
+ const row = document.createElement("div");
570
+ row.className = `edit-row${edit.kind === "deleted" ? " deleted" : ""}`;
571
+ const pip = document.createElement("span");
572
+ pip.className = "pip";
573
+ const label = document.createElement("span");
574
+ label.className = "label";
575
+ label.textContent = edit.label;
576
+ const kind = document.createElement("span");
577
+ kind.className = "kind";
578
+ kind.textContent = edit.kind;
579
+ row.append(pip, label, kind);
580
+ rows.append(row);
581
+ }
582
+ if (edits.length > LIMIT) {
583
+ const more = document.createElement("button");
584
+ more.type = "button";
585
+ more.className = "edit-more";
586
+ more.textContent = state.editsExpanded ? "Show fewer" : `${edits.length - LIMIT} more…`;
587
+ more.addEventListener("click", () => {
588
+ state.editsExpanded = !state.editsExpanded;
589
+ render();
590
+ });
591
+ rows.append(more);
592
+ }
593
+ renderSave();
594
+ }
595
+ // --- pages you left feedback on but are not looking at
596
+ const others = state.others || [];
597
+ const othersBox = $("othersBox");
598
+ othersBox.hidden = others.length === 0;
599
+ if (others.length) {
600
+ $("othersCount").textContent = String(others.length);
601
+ const list = $("othersList");
602
+ list.textContent = "";
603
+ for (const other of others) {
604
+ const row = document.createElement("button");
605
+ row.type = "button";
606
+ row.className = "edit-row other-row";
607
+ const label = document.createElement("span");
608
+ label.className = "label";
609
+ label.textContent = other.filename;
610
+ const count = document.createElement("span");
611
+ count.className = "kind";
612
+ count.textContent = String(other.count);
613
+ row.append(label, count);
614
+ row.addEventListener("click", async () => {
615
+ try {
616
+ await reviewController.navigate({ key: other.key });
617
+ }
618
+ catch (err) {
619
+ toast(`${err.message}. Stay on this page and retry.`);
620
+ }
621
+ });
622
+ list.append(row);
623
+ }
624
+ }
625
+ // --- send
626
+ const otherTotal = others.reduce((sum, o) => sum + o.count, 0);
627
+ const total = comments.length + edits.length + otherTotal;
628
+ // An overall note is sendable on its own — the server already accepts
629
+ // note-only batches; the button must not stay dead while one is typed.
630
+ const hasNote = $("note").value.trim().length > 0;
631
+ const send = $("send");
632
+ const delivered = state.agent === "working";
633
+ const stranded = state.agent === "stranded";
634
+ const busy = delivered || stranded || feedbackController.sent;
635
+ send.disabled = (total === 0 && !hasNote) || busy || feedbackController.sending;
636
+ send.textContent = feedbackController.sending ? "Sending feedback…" : delivered
637
+ ? "Feedback delivered"
638
+ : stranded
639
+ ? "Sent — agent is not listening"
640
+ : feedbackController.sent
641
+ ? "Sent — waiting for agent"
642
+ : total
643
+ ? `Send ${total} to agent`
644
+ : hasNote
645
+ ? "Send note to agent"
646
+ : "Nothing to send yet";
647
+ // After sending, say what happens next. If nothing is polling, the loop would
648
+ // otherwise dead-end silently, so hand over the exact command to run.
649
+ $("agentLine").hidden = !delivered;
650
+ $("agentText").textContent = "Feedback delivered — page reloads when fixes land";
651
+ // Server-authoritative, so it survives a browser refresh.
652
+ $("handoff").hidden = !stranded;
653
+ if (stranded)
654
+ $("handoffCmd").textContent = handoffPrompt(state.pollCommand || page.pollCommand);
655
+ const excluded = draftCount(state);
656
+ $("draftWarning").hidden = excluded === 0;
657
+ $("draftWarning").textContent = `${excluded} open ${excluded === 1 ? "draft is" : "drafts are"} not included. Save comments explicitly before sending.`;
658
+ restoreTransientFocus(editWasFocused);
659
+ }
660
+ function positionCompose() {
661
+ if (!state.compose || state.composeLifecycle === "closed") {
662
+ setComposePlacement("hidden");
663
+ return;
664
+ }
665
+ if (state.compose.unresolved) {
666
+ const surface = $("compose");
667
+ surface.hidden = false;
668
+ surface.classList.add("sheet");
669
+ surface.classList.remove("edge-top", "edge-bottom");
670
+ $("composeDirection").hidden = true;
671
+ setComposePlacement("sheet");
672
+ return;
673
+ }
674
+ const viewport = visibleViewport();
675
+ const frameRect = frameHost.current.getBoundingClientRect();
676
+ const surface = $("compose");
677
+ if (state.compose.relation !== "unavailable")
678
+ surface.hidden = false;
679
+ const placement = placeContextualSurface(state.compose, {
680
+ frameRect,
681
+ viewport,
682
+ surfaceWidth: Math.min(340, viewport.width - 24),
683
+ surfaceHeight: Math.max(190, surface.offsetHeight),
684
+ narrow: matchMedia("(max-width: 720px)").matches,
685
+ toolbarHeight: document.querySelector(".toolbar").getBoundingClientRect().height,
686
+ });
687
+ surface.classList.toggle("sheet", placement.kind === "sheet");
688
+ surface.classList.toggle("edge-top", placement.kind === "edge-top");
689
+ surface.classList.toggle("edge-bottom", placement.kind === "edge-bottom");
690
+ setComposePlacement(placement.kind);
691
+ const edge = placement.kind === "edge-top" || placement.kind === "edge-bottom";
692
+ $("composeDirection").hidden = !edge;
693
+ $("composeDirectionText").textContent = placement.kind === "edge-top"
694
+ ? "Selection is above"
695
+ : placement.kind === "edge-bottom"
696
+ ? "Selection is below"
697
+ : "";
698
+ surface.hidden = placement.kind === "hidden";
699
+ if (placement.kind !== "sheet" && placement.kind !== "hidden") {
700
+ surface.style.left = `${placement.left}px`;
701
+ surface.style.top = `${placement.top}px`;
702
+ surface.style.width = `${placement.width}px`;
703
+ }
704
+ else {
705
+ surface.style.left = "";
706
+ surface.style.top = "";
707
+ surface.style.width = "";
708
+ }
709
+ }
710
+ function makeAction(label, className = "card-action") {
711
+ const button = document.createElement("button");
712
+ button.type = "button";
713
+ button.className = className;
714
+ button.textContent = label;
715
+ return button;
716
+ }
717
+ function makeWho(comment, surface) {
718
+ const who = document.createElement("span");
719
+ who.className = "who";
720
+ who.append("You");
721
+ if (surface === "drawer") {
722
+ const sep = document.createElement("span");
723
+ sep.className = "sep";
724
+ sep.textContent = "·";
725
+ const when = document.createElement("span");
726
+ when.className = "when";
727
+ when.textContent = ago(comment.updatedAt || comment.createdAt);
728
+ who.append(sep, when);
729
+ }
730
+ if (comment.correction) {
731
+ const badge = document.createElement("span");
732
+ badge.className = "badge correction";
733
+ badge.textContent = "correction";
734
+ who.append(badge);
735
+ }
736
+ else if (comment.updatedAt) {
737
+ const badge = document.createElement("span");
738
+ badge.className = "badge";
739
+ badge.textContent = "edited";
740
+ who.append(badge);
741
+ }
742
+ if (state.orphans.has(comment.id)) {
743
+ const badge = document.createElement("span");
744
+ badge.className = "badge";
745
+ badge.textContent = "orphaned";
746
+ who.append(badge);
747
+ }
748
+ return who;
749
+ }
750
+ function commentUiKind(commentId) {
751
+ if (state.commentUi.edit?.commentId === commentId)
752
+ return "edit";
753
+ if (state.commentUi.confirmation?.commentId === commentId)
754
+ return "confirmation";
755
+ if (state.commentUi.menu?.commentId === commentId)
756
+ return "menu";
757
+ return "normal";
758
+ }
759
+ function renderMore(comment, surface, open, disabled = false) {
760
+ const triggerId = controlId(comment.id, surface, "more");
761
+ const menuId = controlId(comment.id, surface, "menu");
762
+ const trigger = makeAction("More", "card-action more-trigger");
763
+ trigger.id = triggerId;
764
+ trigger.setAttribute("aria-haspopup", "menu");
765
+ trigger.setAttribute("aria-expanded", String(open));
766
+ trigger.setAttribute("aria-controls", menuId);
767
+ trigger.disabled = disabled;
768
+ trigger.prepend(createIcon("moreHorizontal", { size: 14 }));
769
+ trigger.addEventListener("click", (event) => {
770
+ event.stopPropagation();
771
+ if (open) {
772
+ closeCommentMenu({ restoreFocus: true });
773
+ }
774
+ else {
775
+ if (!ownMenu(state.commentUi, comment.id, surface, triggerId)) {
776
+ focusCurrentCommentEdit();
777
+ return;
778
+ }
779
+ toFrame({ type: "eh:modeMenuState", open: true });
780
+ requestControlFocus(controlId(comment.id, surface, "delete-item"));
781
+ render();
782
+ }
783
+ });
784
+ return trigger;
785
+ }
786
+ function renderCommentCard(comment, surface) {
787
+ const card = document.createElement(surface === "aligned" ? "article" : "div");
788
+ if (surface === "drawer") {
789
+ card.className = `comment${state.activeSavedCommentId === comment.id ? " active" : ""}`;
790
+ }
791
+ card.dataset.id = comment.id;
792
+ card.dataset.surface = surface;
793
+ const kind = commentUiKind(comment.id);
794
+ const editOwnedElsewhere = !!(state.commentUi.edit &&
795
+ state.commentUi.edit.commentId !== comment.id);
796
+ const head = document.createElement("div");
797
+ head.className = "comment-head";
798
+ head.append(makeWho(comment, surface));
799
+ if (kind === "normal") {
800
+ if (surface === "drawer") {
801
+ const jump = makeAction("Jump to");
802
+ jump.disabled = editOwnedElsewhere;
803
+ jump.addEventListener("click", (event) => {
804
+ event.stopPropagation();
805
+ setActive(comment.id, true);
806
+ });
807
+ head.append(jump);
808
+ }
809
+ const edit = makeAction("Edit");
810
+ edit.id = controlId(comment.id, surface, "edit");
811
+ edit.setAttribute("aria-label", "Edit comment");
812
+ edit.disabled = editOwnedElsewhere;
813
+ edit.addEventListener("click", (event) => {
814
+ event.stopPropagation();
815
+ startCommentEdit(comment, surface);
816
+ });
817
+ head.append(edit);
818
+ if (surface === "aligned") {
819
+ const close = makeAction("Close");
820
+ close.setAttribute("aria-label", "Close comment card");
821
+ close.addEventListener("click", (event) => {
822
+ event.stopPropagation();
823
+ dismissActiveComment("close", { restoreFocus: true });
824
+ });
825
+ head.append(close);
826
+ }
827
+ head.append(renderMore(comment, surface, false, editOwnedElsewhere));
828
+ }
829
+ else if (kind === "menu") {
830
+ head.append(renderMore(comment, surface, true));
831
+ }
832
+ const quote = document.createElement("p");
833
+ quote.className = "quote";
834
+ quote.textContent = tidyMiddle(comment.quote, 140);
835
+ card.append(head, quote);
836
+ if (kind === "edit") {
837
+ const edit = state.commentUi.edit;
838
+ const input = document.createElement("textarea");
839
+ input.className = "body-edit";
840
+ input.rows = 3;
841
+ input.value = edit.draft;
842
+ input.readOnly = edit.status === "saving";
843
+ input.dataset.commentEdit = comment.id;
844
+ input.setAttribute("aria-label", "Edit comment text");
845
+ input.addEventListener("input", () => {
846
+ edit.draft = input.value;
847
+ edit.selectionStart = input.selectionStart;
848
+ edit.selectionEnd = input.selectionEnd;
849
+ edit.validation = "";
850
+ });
851
+ const rememberSelection = () => {
852
+ edit.selectionStart = input.selectionStart;
853
+ edit.selectionEnd = input.selectionEnd;
854
+ };
855
+ input.addEventListener("select", rememberSelection);
856
+ input.addEventListener("keyup", rememberSelection);
857
+ input.addEventListener("click", (event) => {
858
+ event.stopPropagation();
859
+ rememberSelection();
860
+ });
861
+ input.addEventListener("compositionstart", () => {
862
+ edit.composing = true;
863
+ });
864
+ input.addEventListener("compositionend", () => {
865
+ edit.composing = false;
866
+ rememberSelection();
867
+ });
868
+ input.addEventListener("keydown", (event) => {
869
+ event.stopPropagation();
870
+ rememberSelection();
871
+ if (event.key === "Enter" && !event.shiftKey) {
872
+ if (edit.composing || event.isComposing)
873
+ return;
874
+ event.preventDefault();
875
+ void saveCommentEdit();
876
+ }
877
+ else if (event.key === "Escape") {
878
+ event.preventDefault();
879
+ cancelCommentEdit();
880
+ }
881
+ });
882
+ card.append(input);
883
+ const helper = document.createElement("p");
884
+ helper.className = "edit-help";
885
+ helper.textContent = "Enter to save · Shift+Enter for new line";
886
+ card.append(helper);
887
+ if (edit.validation) {
888
+ const validation = document.createElement("p");
889
+ validation.className = "comment-validation";
890
+ validation.setAttribute("role", "alert");
891
+ validation.textContent = edit.validation;
892
+ card.append(validation);
893
+ }
894
+ const actions = document.createElement("div");
895
+ actions.className = "comment-edit-actions";
896
+ const save = makeAction(edit.status === "saving" ? "Saving…" : "Save", "btn-primary");
897
+ save.disabled = edit.status === "saving";
898
+ save.addEventListener("click", (event) => {
899
+ event.stopPropagation();
900
+ void saveCommentEdit();
901
+ });
902
+ const cancel = makeAction("Cancel", "btn-ghost");
903
+ cancel.disabled = edit.status === "saving";
904
+ cancel.addEventListener("click", (event) => {
905
+ event.stopPropagation();
906
+ cancelCommentEdit();
907
+ });
908
+ actions.append(save, cancel);
909
+ card.append(actions);
910
+ }
911
+ else if (kind === "confirmation") {
912
+ const confirmation = state.commentUi.confirmation;
913
+ const prompt = document.createElement("p");
914
+ prompt.className = "delete-prompt";
915
+ prompt.textContent = "Delete this comment?";
916
+ const actions = document.createElement("div");
917
+ actions.className = "delete-actions";
918
+ const cancel = makeAction("Cancel", "btn-ghost");
919
+ cancel.disabled = confirmation.status === "deleting";
920
+ cancel.addEventListener("click", (event) => {
921
+ event.stopPropagation();
922
+ cancelDeleteConfirmation();
923
+ });
924
+ const remove = makeAction(confirmation.status === "deleting" ? "Deleting…" : "Delete", "btn-danger");
925
+ remove.id = controlId(comment.id, surface, "confirm-delete");
926
+ remove.disabled = confirmation.status === "deleting";
927
+ remove.addEventListener("click", (event) => {
928
+ event.stopPropagation();
929
+ void deleteComment(comment.id);
930
+ });
931
+ actions.append(cancel, remove);
932
+ card.append(prompt, actions);
933
+ }
934
+ else {
935
+ const body = document.createElement("p");
936
+ body.className = "body";
937
+ body.textContent = comment.feedback;
938
+ body.title = "Click to edit";
939
+ if (!editOwnedElsewhere) {
940
+ body.addEventListener("click", (event) => {
941
+ event.stopPropagation();
942
+ startCommentEdit(comment, surface);
943
+ });
944
+ }
945
+ card.append(body);
946
+ }
947
+ if (kind === "menu") {
948
+ const menu = document.createElement("div");
949
+ menu.id = controlId(comment.id, surface, "menu");
950
+ menu.className = "comment-menu";
951
+ menu.setAttribute("role", "menu");
952
+ menu.setAttribute("aria-labelledby", controlId(comment.id, surface, "more"));
953
+ const remove = makeAction("Delete", "comment-menu-item");
954
+ remove.id = controlId(comment.id, surface, "delete-item");
955
+ remove.setAttribute("role", "menuitem");
956
+ remove.prepend(createIcon("trash", { size: 14 }));
957
+ remove.addEventListener("click", (event) => {
958
+ event.stopPropagation();
959
+ toFrame({ type: "eh:modeMenuState", open: false });
960
+ if (!ownConfirmation(state.commentUi, comment.id, surface)) {
961
+ focusCurrentCommentEdit();
962
+ return;
963
+ }
964
+ requestControlFocus(controlId(comment.id, surface, "confirm-delete"));
965
+ render();
966
+ });
967
+ menu.append(remove);
968
+ card.append(menu);
969
+ }
970
+ if (surface === "drawer") {
971
+ card.addEventListener("click", () => {
972
+ if (kind === "normal" && !editOwnedElsewhere)
973
+ setActive(comment.id, false);
974
+ });
975
+ }
976
+ return card;
977
+ }
978
+ function positionAlignedCard() {
979
+ const host = $("alignedCard");
980
+ const comment = commentById(state.activeSavedCommentId);
981
+ const geometry = comment ? state.activeGeometry.get(comment.id) : null;
982
+ if (!comment || state.drawerOpen || matchMedia("(max-width: 720px)").matches || !geometry?.visible) {
983
+ host.hidden = true;
984
+ return false;
985
+ }
986
+ const viewport = visibleViewport();
987
+ const position = alignedCardPosition(geometry.rects, {
988
+ frameRect: frameHost.current.getBoundingClientRect(),
989
+ viewport,
990
+ });
991
+ if (!position) {
992
+ host.hidden = true;
993
+ return false;
994
+ }
995
+ host.style.left = `${position.left}px`;
996
+ host.style.top = `${position.top}px`;
997
+ host.hidden = false;
998
+ return true;
999
+ }
1000
+ function renderAlignedCard(comments) {
1001
+ const host = $("alignedCard");
1002
+ host.textContent = "";
1003
+ const comment = comments.find((item) => item.id === state.activeSavedCommentId);
1004
+ if (!comment) {
1005
+ host.hidden = true;
1006
+ return;
1007
+ }
1008
+ const card = renderCommentCard(comment, "aligned");
1009
+ while (card.firstChild)
1010
+ host.append(card.firstChild);
1011
+ positionAlignedCard();
1012
+ }
1013
+ async function deleteComment(id) {
1014
+ if (deleteFlights.has(id))
1015
+ return deleteFlights.get(id);
1016
+ const confirmation = state.commentUi.confirmation;
1017
+ if (!confirmation || confirmation.commentId !== id || confirmation.status === "deleting")
1018
+ return false;
1019
+ confirmation.status = "deleting";
1020
+ render();
1021
+ const startEpoch = state.pageEpoch;
1022
+ const flight = (async () => {
1023
+ try {
1024
+ const result = await api(`/api/page/${frameController.state.key}/comment/${id}`, { method: "DELETE" });
1025
+ if (!mutationIsCurrent(startEpoch, state.pageEpoch, state.page?.comments, id))
1026
+ return false;
1027
+ reconcilePage(result.page, { reason: "mutation" });
1028
+ toFrame({ type: "eh:remove", id });
1029
+ state.activeGeometry.delete(id);
1030
+ if (state.activeSavedCommentId === id)
1031
+ state.activeSavedCommentId = null;
1032
+ render();
1033
+ return true;
1034
+ }
1035
+ catch (err) {
1036
+ if (mutationIsCurrent(startEpoch, state.pageEpoch, state.page?.comments, id)) {
1037
+ if (state.commentUi.confirmation?.commentId === id)
1038
+ state.commentUi.confirmation.status = "idle";
1039
+ toast(err.message);
1040
+ render();
1041
+ }
1042
+ return false;
1043
+ }
1044
+ })().finally(() => {
1045
+ if (deleteFlights.get(id) === flight)
1046
+ deleteFlights.delete(id);
1047
+ });
1048
+ deleteFlights.set(id, flight);
1049
+ return flight;
1050
+ }
1051
+ function cancelDeleteConfirmation() {
1052
+ const confirmation = state.commentUi.confirmation;
1053
+ if (!confirmation || confirmation.status === "deleting")
1054
+ return false;
1055
+ const triggerId = controlId(confirmation.commentId, confirmation.surface, "more");
1056
+ clearOwned(state.commentUi, "confirmation");
1057
+ requestControlFocus(triggerId);
1058
+ render();
1059
+ return true;
1060
+ }
1061
+ function startCommentEdit(comment, surface) {
1062
+ if (!ownEdit(state.commentUi, comment, surface)) {
1063
+ focusCurrentCommentEdit();
1064
+ return false;
1065
+ }
1066
+ editFocusRequested = true;
1067
+ render();
1068
+ return true;
1069
+ }
1070
+ function focusCurrentCommentEdit() {
1071
+ editFocusRequested = true;
1072
+ announce("Save or cancel the current comment edit first");
1073
+ afterPaint(() => {
1074
+ const edit = state.commentUi.edit;
1075
+ editTextarea(edit?.commentId)?.focus();
1076
+ });
1077
+ }
1078
+ function cancelCommentEdit() {
1079
+ const edit = state.commentUi.edit;
1080
+ if (!edit || edit.status === "saving")
1081
+ return false;
1082
+ const surface = state.drawerOpen ? "drawer" : edit.originSurface;
1083
+ const focusId = controlId(edit.commentId, surface, "edit");
1084
+ clearOwned(state.commentUi, "edit");
1085
+ requestControlFocus(focusId);
1086
+ render();
1087
+ return true;
1088
+ }
1089
+ function saveCommentEdit() {
1090
+ const edit = state.commentUi.edit;
1091
+ if (!edit || edit.status === "saving")
1092
+ return edit ? patchFlights.get(edit.commentId) : false;
1093
+ captureEditState();
1094
+ const feedback = edit.draft.trim();
1095
+ if (!feedback) {
1096
+ edit.validation = "Comment text is required.";
1097
+ editFocusRequested = true;
1098
+ render();
1099
+ return false;
1100
+ }
1101
+ if (feedback === edit.original) {
1102
+ clearOwned(state.commentUi, "edit");
1103
+ requestControlFocus(controlId(edit.commentId, state.drawerOpen ? "drawer" : edit.originSurface, "edit"));
1104
+ render();
1105
+ return true;
1106
+ }
1107
+ if (patchFlights.has(edit.commentId))
1108
+ return patchFlights.get(edit.commentId);
1109
+ edit.status = "saving";
1110
+ edit.validation = "";
1111
+ const id = edit.commentId;
1112
+ const startEpoch = state.pageEpoch;
1113
+ editFocusRequested = true;
1114
+ render();
1115
+ const flight = executeCommentPatch({ ...edit, draft: feedback }, startEpoch).finally(() => {
1116
+ if (patchFlights.get(id) === flight)
1117
+ patchFlights.delete(id);
1118
+ });
1119
+ patchFlights.set(id, flight);
1120
+ return flight;
1121
+ }
1122
+ async function executeCommentPatch(edit, startEpoch) {
1123
+ const id = edit.commentId;
1124
+ try {
1125
+ const commentIndex = state.page.comments.findIndex((item) => item.id === id);
1126
+ const previousGeometry = state.activeGeometry.get(id);
1127
+ const wasOrphaned = state.orphans.has(id);
1128
+ const remainsActive = state.activeSavedCommentId === id;
1129
+ const result = await api(`/api/page/${frameController.state.key}/comment/${id}`, {
1130
+ method: "PATCH",
1131
+ body: JSON.stringify({ feedback: edit.draft }),
1132
+ });
1133
+ if (!mutationIsCurrent(startEpoch, state.pageEpoch, state.page?.comments, id))
1134
+ return false;
1135
+ const replacement = commentIndex >= 0 ? result.page.comments[commentIndex] : null;
1136
+ if (replacement && replacement.id !== id) {
1137
+ migrateCommentUi(state.commentUi, id, replacement.id);
1138
+ if (remainsActive && previousGeometry)
1139
+ state.activeGeometry.set(replacement.id, previousGeometry);
1140
+ if (remainsActive)
1141
+ state.activeSavedCommentId = replacement.id;
1142
+ if (wasOrphaned)
1143
+ state.orphans.add(replacement.id);
1144
+ }
1145
+ reconcilePage(result.page, { reason: "mutation" });
1146
+ clearOwned(state.commentUi, "edit");
1147
+ if (result.delivery === "updated-pending") {
1148
+ toast("Updated the feedback waiting for your agent");
1149
+ }
1150
+ else if (result.delivery === "correction") {
1151
+ feedbackController.clearSent();
1152
+ toFrame({ type: "eh:remove", id });
1153
+ toFrame({ type: "eh:anchors", comments: state.page.comments });
1154
+ if (remainsActive && replacement)
1155
+ toFrame({ type: "eh:activate", id: replacement.id, scroll: false });
1156
+ toast("Saved as a correction — send it after the current batch is acknowledged");
1157
+ }
1158
+ else {
1159
+ feedbackController.clearSent();
1160
+ }
1161
+ render();
1162
+ return true;
1163
+ }
1164
+ catch (err) {
1165
+ if (mutationIsCurrent(startEpoch, state.pageEpoch, state.page?.comments, id)) {
1166
+ const current = state.commentUi.edit;
1167
+ if (current?.commentId === id) {
1168
+ current.status = "idle";
1169
+ current.validation = "";
1170
+ editFocusRequested = true;
1171
+ }
1172
+ toast(err.message);
1173
+ render();
1174
+ }
1175
+ return false;
1176
+ }
1177
+ }
1178
+ function renderSave() {
1179
+ const line = $("saveLine");
1180
+ if (saveController.state.conflict) {
1181
+ line.className = "save-line failed";
1182
+ $("saveText").textContent = "Source changed — reload latest before saving. Your page edits remain in this tab.";
1183
+ return;
1184
+ }
1185
+ if (state.page && state.page.kind === "url") {
1186
+ line.className = "save-line dynamic";
1187
+ $("saveText").textContent = "Localhost page — your direct edits go to the agent for source updates";
1188
+ return;
1189
+ }
1190
+ if (state.page && state.page.markdown) {
1191
+ line.className = "save-line dynamic";
1192
+ $("saveText").textContent = "Markdown source — edits go to the agent as feedback";
1193
+ return;
1194
+ }
1195
+ if (saveController.state.dynamic) {
1196
+ // The page's own scripts render it, so writing the live DOM back would
1197
+ // corrupt the file. Edits still reach the agent as feedback.
1198
+ line.className = "save-line dynamic";
1199
+ $("saveText").textContent = "Live page — edits go to the agent, the file is left alone";
1200
+ return;
1201
+ }
1202
+ line.className = `save-line ${saveController.state.status === "saving" ? "saving" : saveController.state.status === "failed" ? "failed" : ""}`;
1203
+ const name = state.page ? state.page.filename : "";
1204
+ if (saveController.state.status === "saving")
1205
+ $("saveText").textContent = `Saving to ${name}…`;
1206
+ else if (saveController.state.status === "failed")
1207
+ $("saveText").textContent = "Couldn't save — retry before sending";
1208
+ else
1209
+ $("saveText").textContent = saveController.state.savedAt ? `Saved to ${name} · ${saveController.state.savedAt}` : `Saved to ${name}`;
1210
+ }
1211
+ function toast(message) {
1212
+ const el = document.createElement("div");
1213
+ el.className = "toast";
1214
+ el.textContent = message;
1215
+ document.body.append(el);
1216
+ afterDelay(() => el.remove(), 3200);
1217
+ }
1218
+ function setActive(id, scroll) {
1219
+ state.activeSavedCommentId = id;
1220
+ toFrame({ type: "eh:activate", id, scroll: !!scroll });
1221
+ render();
1222
+ }
1223
+ function dismissActiveComment(reason, { restoreFocus = false } = {}) {
1224
+ const id = state.activeSavedCommentId;
1225
+ if (!id)
1226
+ return false;
1227
+ state.activeSavedCommentId = null;
1228
+ state.activeGeometry.delete(id);
1229
+ toFrame({ type: "eh:deactivateComment" });
1230
+ render();
1231
+ announce("Comment card closed");
1232
+ diagnostic("saved-card-deactivated", { reason });
1233
+ if (restoreFocus)
1234
+ frameHost.current.focus();
1235
+ return true;
1236
+ }
1237
+ // ------------------------------------------------------------------ compose
1238
+ async function openCompose(detail) {
1239
+ if (state.compose && state.compose.generation === detail.generation) {
1240
+ if (state.composeLifecycle === "closed")
1241
+ setComposeLifecycle("open", "accepted");
1242
+ $("composeText").focus();
1243
+ return true;
1244
+ }
1245
+ if (state.compose && $("composeText").value.trim()) {
1246
+ const submitted = await commitCompose();
1247
+ if (!submitted) {
1248
+ diagnostic("comment-retarget-blocked", { reason: "submit-failed" });
1249
+ return false;
1250
+ }
1251
+ }
1252
+ else if (state.compose) {
1253
+ cancelCompose({ restoreFocus: false, preserveRetarget: true });
1254
+ }
1255
+ dismissActiveComment("composer-open");
1256
+ state.compose = detail;
1257
+ setComposeLifecycle("open", "accepted");
1258
+ $("composeText").value = "";
1259
+ $("composeError").hidden = true;
1260
+ $("composeAddLabel").textContent = "Comment";
1261
+ render();
1262
+ afterPaint(() => {
1263
+ positionCompose();
1264
+ $("composeText").focus();
1265
+ });
1266
+ announce(`Comment dialog opened for ${detail.kind === "element" ? "element" : "selected text"}`);
1267
+ return true;
1268
+ }
1269
+ function cancelCompose({ restoreFocus = true, preserveRetarget = false } = {}) {
1270
+ if (!state.compose || state.composeLifecycle === "submitting")
1271
+ return false;
1272
+ const generation = state.compose.generation;
1273
+ const discardThroughGeneration = Math.max(generation, Number(state.compose.rejectedTargetGeneration) || generation);
1274
+ state.compose = null;
1275
+ setComposeLifecycle("closed", "cancel");
1276
+ setComposePlacement("hidden");
1277
+ toFrame({
1278
+ type: "eh:cancel",
1279
+ targetGeneration: generation,
1280
+ discardThroughGeneration,
1281
+ restoreFocus,
1282
+ preserveRetarget,
1283
+ });
1284
+ render();
1285
+ return true;
1286
+ }
1287
+ let composeSubmitPromise = null;
1288
+ function commitCompose() {
1289
+ if (composeSubmitPromise) {
1290
+ diagnostic("comment-submit-suppressed", { reason: "in-flight" });
1291
+ return composeSubmitPromise;
1292
+ }
1293
+ composeSubmitPromise = executeComposeSubmit().finally(() => {
1294
+ composeSubmitPromise = null;
1295
+ });
1296
+ return composeSubmitPromise;
1297
+ }
1298
+ async function executeComposeSubmit() {
1299
+ const compose = state.compose;
1300
+ const feedback = $("composeText").value.trim();
1301
+ if (!compose || !feedback)
1302
+ return false;
1303
+ const button = $("composeAdd");
1304
+ button.disabled = true;
1305
+ setComposeLifecycle("submitting", "submit");
1306
+ diagnostic("comment-submit-executed");
1307
+ $("composeError").hidden = true;
1308
+ try {
1309
+ const result = await api(`/api/page/${frameController.state.key}/comment`, {
1310
+ method: "POST",
1311
+ body: JSON.stringify({ kind: compose.kind, quote: compose.quote, anchor: compose.unresolved ? null : compose.anchor, feedback }),
1312
+ });
1313
+ toFrame({
1314
+ type: "eh:commit",
1315
+ id: result.comment.id,
1316
+ targetGeneration: compose.generation,
1317
+ restoreFocus: true,
1318
+ });
1319
+ state.compose = null;
1320
+ setComposeLifecycle("closed", "submitted");
1321
+ setComposePlacement("hidden");
1322
+ state.page = result.page;
1323
+ feedbackController.clearSent();
1324
+ render();
1325
+ announce("Comment added");
1326
+ return true;
1327
+ }
1328
+ catch (err) {
1329
+ $("composeError").textContent = `${err.message}. Retry or cancel.`;
1330
+ $("composeError").hidden = false;
1331
+ $("composeAddLabel").textContent = "Retry";
1332
+ diagnostic("comment-request-failure", { status: err.status || 0 });
1333
+ announce("Comment could not be saved. Your draft is still here.");
1334
+ setComposeLifecycle("open", "submit-failed");
1335
+ $("compose").classList.remove("pass-through");
1336
+ afterPaint(() => $("composeText").focus());
1337
+ return false;
1338
+ }
1339
+ finally {
1340
+ button.disabled = false;
1341
+ }
1342
+ }
1343
+ // ------------------------------------------------------------ review history
1344
+ const currentRender = () => frameController.identity();
1345
+ const captures = createCaptureRequests({ send: toFrame, current: currentRender });
1346
+ const comparisonView = createComparisonView($("changeDetail"));
1347
+ const historyUrl = (suffix = "") => `/api/session/${state.sessionId}/history${suffix}`;
1348
+ const historyController = createHistoryController({
1349
+ request: (suffix) => api(historyUrl(suffix)), changed: renderHistory, refreshed: scheduleResultCapture,
1350
+ });
1351
+ const history = historyController.state;
1352
+ let manualCaptureController = null;
1353
+ const captureCoordinator = createCaptureCoordinator({
1354
+ ready: () => !state.ended && !frameController.loading && !frameController.state.pendingReload && !saveController.state.dirty &&
1355
+ !saveController.state.conflict && !feedbackController.sending && !history.captureBusy && !history.finalizing &&
1356
+ (state.page?.kind === "url" || !!saveController.state.baseHash),
1357
+ candidates: () => [...history.rounds].reverse().flatMap((round) => {
1358
+ const target = pendingCaptureTarget(round, frameController.state.key, frameController.state.readyAt);
1359
+ return target ? [{ id: `${roundId(round)}:${frameController.state.renderId}:${frameController.state.generation}`, round, target }] : [];
1360
+ }),
1361
+ capture: ({ round, target }, signal) => captureResult(round, target, true, signal),
1362
+ });
1363
+ const fullSaveBarrier = () => saveController.barrier();
1364
+ const captureStablePage = (options) => saveController.captureStable(() => captures.request(options), options?.signal);
1365
+ function syncFrameInteraction() {
1366
+ frameHost.current.inert = state.comparing || feedbackController.sending;
1367
+ }
1368
+ function roundId(round) { return round?.id || round?.roundId; }
1369
+ function roundTargets(round) { return round?.targets || []; }
1370
+ function selectedTarget() {
1371
+ const targets = roundTargets(history.round);
1372
+ return targets.find((target) => target.key === history.targetKey) || targets[0] || null;
1373
+ }
1374
+ function targetComparison(target) { return target?.comparison || {}; }
1375
+ function comparisonItems() {
1376
+ const comparison = targetComparison(selectedTarget());
1377
+ const value = history.mode === "source" ? comparison.source : comparison.content;
1378
+ return value?.changes || value?.items || (history.mode === "content" ? comparison.changes || comparison.items : []) || [];
1379
+ }
1380
+ const refreshHistory = () => state.ended ? Promise.resolve(false) : historyController.refresh();
1381
+ function renderHistory() {
1382
+ if (state.ended)
1383
+ return;
1384
+ syncFrameInteraction();
1385
+ const focusedMode = document.activeElement?.dataset.comparisonMode;
1386
+ const picker = $("roundPicker");
1387
+ picker.replaceChildren();
1388
+ for (const [index, round] of history.rounds.entries()) {
1389
+ const option = document.createElement("option");
1390
+ option.value = roundId(round);
1391
+ option.textContent = `Round ${round.ordinal || round.number || history.rounds.length - index} · ${round.captureStatus === "ready" ? "completed" : round.captureStatus || round.status || round.feedbackStatus || "pending"}`;
1392
+ picker.append(option);
1393
+ }
1394
+ picker.value = history.selectedId || "";
1395
+ picker.disabled = !history.rounds.length;
1396
+ const targets = roundTargets(history.round);
1397
+ const target = selectedTarget();
1398
+ if (history.round)
1399
+ history.targetKey = target?.key || null;
1400
+ $("historyTarget").replaceChildren();
1401
+ for (const item of targets) {
1402
+ const option = document.createElement("option");
1403
+ option.value = item.key;
1404
+ option.textContent = item.filename || item.label || item.key;
1405
+ $("historyTarget").append(option);
1406
+ }
1407
+ $("historyTarget").value = history.targetKey || "";
1408
+ $("historyTargetLabel").hidden = targets.length < 2;
1409
+ const comparison = targetComparison(target);
1410
+ const failedCapture = history.failures.get(`${roundId(history.round)}:${target?.key}`);
1411
+ const presentation = historyPresentation({ ...history, target, comparison, failure: failedCapture });
1412
+ const modes = presentation.modes;
1413
+ history.mode = modes.includes(history.preferredMode) ? history.preferredMode : modes[0] || "content";
1414
+ const displayedComparison = comparison[history.mode] || {};
1415
+ $("historyUnavailable").replaceChildren();
1416
+ for (const mode of ["content", "source"]) {
1417
+ const representation = comparison[mode];
1418
+ if (representation && representation.available === false) {
1419
+ const reason = document.createElement("p");
1420
+ reason.textContent = `${mode === "content" ? "Content" : "Source"} comparison unavailable: ${representation.reason || "This representation could not be compared."}`;
1421
+ $("historyUnavailable").append(reason);
1422
+ }
1423
+ }
1424
+ $("historyUnavailable").hidden = !$("historyUnavailable").childElementCount;
1425
+ $("historyTiming").replaceChildren();
1426
+ for (const [label, timestamp] of [
1427
+ ["Before captured", displayedComparison.beforeCapturedAt],
1428
+ ["Agent acknowledged", history.round?.acknowledgedAt],
1429
+ ["After captured", displayedComparison.afterCapturedAt],
1430
+ ]) {
1431
+ const row = document.createElement("div");
1432
+ const term = document.createElement("dt");
1433
+ term.textContent = label;
1434
+ const value = document.createElement("dd");
1435
+ const date = timestamp == null ? null : new Date(timestamp);
1436
+ value.textContent = date && Number.isFinite(date.getTime()) ? date.toLocaleString() : "Not available";
1437
+ row.append(term, value);
1438
+ $("historyTiming").append(row);
1439
+ }
1440
+ $("historyTiming").hidden = !history.round;
1441
+ const afterAt = displayedComparison.afterCapturedAt == null ? NaN : new Date(displayedComparison.afterCapturedAt).getTime();
1442
+ const acknowledgedAt = history.round?.acknowledgedAt == null ? NaN : new Date(history.round.acknowledgedAt).getTime();
1443
+ const delay = afterAt - acknowledgedAt;
1444
+ $("historyCaptureDelay").hidden = !Number.isFinite(delay);
1445
+ $("historyCaptureDelay").textContent = delay >= 0
1446
+ ? `Result captured ${Math.round(delay / 1000)} seconds after acknowledgment—not at the acknowledgment instant. A delayed capture can include later changes.`
1447
+ : "This result snapshot predates acknowledgment. It is not proof of the page state at acknowledgment.";
1448
+ $("historyCurrentStatus").hidden = !target?.resultRevisionId && !displayedComparison.afterCapturedAt;
1449
+ $("historyCurrentStatus").textContent = comparisonFreshness(displayedComparison, target?.key, {
1450
+ key: frameController.state.key, kind: state.page?.kind, ready: !frameController.loading && !!frameController.state.readyAt,
1451
+ pendingReload: frameController.state.pendingReload, dirty: saveController.state.dirty || saveController.state.conflict,
1452
+ sourceHash: frameController.state.sourceHash || saveController.state.baseHash,
1453
+ sessionId: state.sessionId, generation: frameController.state.generation,
1454
+ });
1455
+ const viewComparison = history.mode === "content" ? displayedComparison.viewComparison : null;
1456
+ $("historyViewCoverage").hidden = !viewComparison?.message;
1457
+ $("historyViewCoverage").textContent = viewComparison?.message || "";
1458
+ $("historyViewCoverage").dataset.status = viewComparison?.status || "";
1459
+ $("comparisonModes").replaceChildren();
1460
+ for (const mode of modes) {
1461
+ const button = makeAction(mode === "source" ? "Source" : "Content", "btn-ghost");
1462
+ button.dataset.comparisonMode = mode;
1463
+ button.setAttribute("aria-pressed", String(history.mode === mode));
1464
+ button.addEventListener("click", () => {
1465
+ history.preferredMode = mode;
1466
+ history.mode = mode;
1467
+ history.index = 0;
1468
+ renderHistory();
1469
+ $("comparisonModes").querySelector(`[data-comparison-mode="${mode}"]`)?.focus({ preventScroll: true });
1470
+ });
1471
+ $("comparisonModes").append(button);
1472
+ }
1473
+ if (focusedMode)
1474
+ $("comparisonModes").querySelector(`[data-comparison-mode="${focusedMode}"]`)?.focus({ preventScroll: true });
1475
+ if ($("historyStatus").textContent !== presentation.message)
1476
+ $("historyStatus").textContent = presentation.message;
1477
+ $("historyStatus").dataset.state = presentation.state;
1478
+ const detail = history.error?.message || failedCapture || target?.capture?.error;
1479
+ $("historyError").hidden = !detail;
1480
+ $("historyError").textContent = detail || "";
1481
+ const captureAllowed = target && !target.resultRevisionId && target.capture?.status !== "unavailable" && history.round?.feedbackStatus === "acknowledged";
1482
+ $("captureResult").hidden = !captureAllowed;
1483
+ $("captureResult").disabled = history.captureBusy || history.finalizing || target?.key !== frameController.state.key || frameController.loading;
1484
+ $("captureResult").textContent = history.captureBusy ? "Capturing result…" : "Capture result";
1485
+ const canFinalize = target && !target.resultRevisionId && history.round?.feedbackStatus === "acknowledged" &&
1486
+ ["pending", "failed"].includes(target.capture?.status || target.captureStatus || "pending");
1487
+ $("finishCapture").hidden = !canFinalize;
1488
+ $("finishCaptureHelp").hidden = !canFinalize;
1489
+ $("finishCapture").disabled = history.finalizing || history.captureBusy;
1490
+ $("finishCapture").setAttribute("aria-describedby", "finishCaptureHelp");
1491
+ $("finishCapture").textContent = history.finalizing ? "Finishing…" : "Finish with available snapshots";
1492
+ const items = comparisonItems();
1493
+ const limitations = [...new Set([
1494
+ ...(comparison.content?.limitations || []),
1495
+ ...(comparison.source?.limitations || []),
1496
+ ])];
1497
+ $("historyLimitations").hidden = limitations.length === 0;
1498
+ $("historyLimitationsList").replaceChildren();
1499
+ for (const limitation of limitations) {
1500
+ const line = document.createElement("li");
1501
+ line.textContent = String(limitation).replaceAll("-", " ").replaceAll("_", " ");
1502
+ $("historyLimitationsList").append(line);
1503
+ }
1504
+ const counts = displayedComparison.counts;
1505
+ $("historyCounts").textContent = modes.length && counts
1506
+ ? `${counts.added} Added · ${counts.modified} Modified · ${counts.removed} Removed`
1507
+ : "";
1508
+ $("historyCounts").hidden = !counts;
1509
+ history.index = Math.max(0, Math.min(history.index, items.length - 1));
1510
+ $("changeDetail").hidden = !modes.length;
1511
+ const comparisonHeader = $("historyPanel").querySelector(".comparison-header");
1512
+ if (comparisonHeader)
1513
+ comparisonHeader.hidden = !modes.length;
1514
+ if (modes.length) {
1515
+ comparisonView.render({ ...displayedComparison, changes: items }, {
1516
+ mode: history.mode, key: `${history.selectedId}:${history.targetKey}`,
1517
+ });
1518
+ comparisonView.select(history.index);
1519
+ }
1520
+ $("changeJump").replaceChildren();
1521
+ for (const [index, item] of items.entries()) {
1522
+ const option = document.createElement("option");
1523
+ option.value = index;
1524
+ option.textContent = `${index + 1}. ${changeKind(item)} · ${tidyMiddle(item.label || excerpt(item.after) || excerpt(item.before) || "Structure", 65)}`;
1525
+ $("changeJump").append(option);
1526
+ }
1527
+ $("changeJump").value = String(history.index);
1528
+ $("changeNavigation").hidden = items.length < 2;
1529
+ $("previousChange").disabled = history.index === 0;
1530
+ $("nextChange").disabled = history.index >= items.length - 1;
1531
+ $("changePosition").textContent = `${items.length ? history.index + 1 : 0} of ${items.length}`;
1532
+ }
1533
+ async function captureResult(round, target, automatic = false, signal) {
1534
+ if (history.captureBusy || !round || target?.key !== frameController.state.key)
1535
+ return;
1536
+ const manualController = automatic ? null : new AbortController();
1537
+ if (manualController) {
1538
+ manualCaptureController = manualController;
1539
+ signal = manualController.signal;
1540
+ }
1541
+ const identity = currentRender();
1542
+ history.captureBusy = true;
1543
+ renderHistory();
1544
+ let phase = "saving";
1545
+ try {
1546
+ await fullSaveBarrier();
1547
+ if (signal?.aborted || state.ended || !sameRender(identity, currentRender()))
1548
+ throw captureError("CAPTURE_CANCELLED", "Capture cancelled");
1549
+ phase = "snapshot";
1550
+ const captured = await captureStablePage({ signal });
1551
+ phase = "publishing";
1552
+ const result = await api(historyUrl(`/${roundId(round)}/capture`), {
1553
+ method: "POST",
1554
+ signal,
1555
+ body: JSON.stringify({
1556
+ sessionId: state.sessionId, roundId: roundId(round), key: captured.key,
1557
+ renderId: captured.renderId, generation: captured.generation,
1558
+ semantic: captured.semantic, expectedSourceHash: captured.sourceHash || saveController.state.baseHash || frameController.state.sourceHash,
1559
+ semanticCapturedAt: captured.semanticCapturedAt, view: captured.view,
1560
+ manual: !automatic,
1561
+ }),
1562
+ });
1563
+ requireCaptureSuccess(result, target.key);
1564
+ if (signal?.aborted || state.ended || !sameRender(identity, currentRender()))
1565
+ return;
1566
+ history.failures.delete(`${roundId(round)}:${target.key}`);
1567
+ await refreshHistory();
1568
+ }
1569
+ catch (err) {
1570
+ if (signal?.aborted || state.ended || !sameRender(identity, currentRender()) || err.code === "CAPTURE_CANCELLED")
1571
+ return;
1572
+ history.failures.set(`${roundId(round)}:${target.key}`, err.message);
1573
+ if (phase === "snapshot" && sameRender(identity, currentRender()) && !frameController.loading) {
1574
+ await api(historyUrl(`/${roundId(round)}/capture`), {
1575
+ method: "POST",
1576
+ signal,
1577
+ body: JSON.stringify({
1578
+ key: identity.key, renderId: identity.renderId, generation: identity.generation,
1579
+ manual: !automatic, error: String(err.message).slice(0, 500),
1580
+ }),
1581
+ }).catch((reportError) => {
1582
+ if (!state.ended)
1583
+ diagnostic("capture-failure-report-failed", { message: reportError.message });
1584
+ });
1585
+ }
1586
+ $("historyError").hidden = false;
1587
+ $("historyError").textContent = `${err.message} Use Capture result to retry; existing captures are unchanged.`;
1588
+ if (automatic)
1589
+ throw err;
1590
+ }
1591
+ finally {
1592
+ if (manualCaptureController === manualController)
1593
+ manualCaptureController = null;
1594
+ history.captureBusy = false;
1595
+ renderHistory();
1596
+ scheduleResultCapture();
1597
+ }
1598
+ }
1599
+ function scheduleResultCapture() {
1600
+ captureCoordinator.tick();
1601
+ }
1602
+ function setHistoryView(comparing) {
1603
+ captureEditState();
1604
+ state.comparing = comparing;
1605
+ closeModeMenu("history-switch");
1606
+ document.body.classList.toggle("comparing", comparing);
1607
+ syncFrameInteraction();
1608
+ frameHost.current.setAttribute("aria-hidden", String(comparing));
1609
+ $("historyPanel").hidden = !comparing;
1610
+ $("latestVersion").setAttribute("aria-pressed", String(!comparing));
1611
+ $("seeChanges").setAttribute("aria-pressed", String(comparing));
1612
+ if (!comparing && frameController.state.pendingReload)
1613
+ $("reloadNotice").hidden = false;
1614
+ if (comparing) {
1615
+ closeDrawer();
1616
+ void refreshHistory();
1617
+ }
1618
+ render();
1619
+ }
1620
+ listen($("latestVersion"), "click", () => setHistoryView(false));
1621
+ listen($("seeChanges"), "click", () => setHistoryView(true));
1622
+ listen($("roundPicker"), "change", () => void historyController.selectRound($("roundPicker").value));
1623
+ listen($("historyTarget"), "change", () => void historyController.selectTarget($("historyTarget").value));
1624
+ function jumpToChange(index) {
1625
+ history.index = index;
1626
+ renderHistory();
1627
+ comparisonView.select(history.index, { scroll: true });
1628
+ }
1629
+ listen($("previousChange"), "click", () => jumpToChange(history.index - 1));
1630
+ listen($("nextChange"), "click", () => jumpToChange(history.index + 1));
1631
+ listen($("changeJump"), "change", (event) => jumpToChange(Number(event.target.value)));
1632
+ listen($("captureResult"), "click", () => void captureResult(history.round, selectedTarget()));
1633
+ listen($("finishCapture"), "click", async () => {
1634
+ const target = selectedTarget();
1635
+ const round = history.round;
1636
+ if (!target || !round || history.finalizing || history.captureBusy)
1637
+ return;
1638
+ history.finalizing = true;
1639
+ renderHistory();
1640
+ try {
1641
+ await api(historyUrl(`/${roundId(round)}/capture`), {
1642
+ method: "POST",
1643
+ body: JSON.stringify({ key: target.key, manual: true, finalUnavailable: true }),
1644
+ });
1645
+ history.failures.delete(`${roundId(round)}:${target.key}`);
1646
+ await refreshHistory();
1647
+ announce("Finished with available snapshots. Missing Content remains unavailable.");
1648
+ }
1649
+ catch (err) {
1650
+ $("historyError").hidden = false;
1651
+ $("historyError").textContent = `${err.message} The capture is still open; you can retry.`;
1652
+ }
1653
+ finally {
1654
+ history.finalizing = false;
1655
+ renderHistory();
1656
+ }
1657
+ });
1658
+ // -------------------------------------------------------------------- saving
1659
+ const saveNow = (html) => saveController.save(html);
1660
+ // ------------------------------------------------------------ frame messages
1661
+ function targetPayload(msg) {
1662
+ const viewport = {
1663
+ width: Number(msg.viewport?.width),
1664
+ height: Number(msg.viewport?.height),
1665
+ };
1666
+ const generation = Number(msg.targetGeneration);
1667
+ const rawRelation = String(msg.relation || "");
1668
+ if (!["visible", "above", "below", "unavailable"].includes(rawRelation))
1669
+ return null;
1670
+ const relation = sanitizeRelation(rawRelation);
1671
+ const clip = sanitizeClipRect(msg.clip, viewport);
1672
+ const rects = sanitizeClientRects(msg.rects, viewport);
1673
+ if (!Number.isSafeInteger(generation) || generation < 1 || !clip)
1674
+ return null;
1675
+ if (relation === "visible" && !rects.length)
1676
+ return null;
1677
+ return {
1678
+ kind: msg.kind === "element" ? "element" : "selection",
1679
+ quote: String(msg.quote || ""),
1680
+ anchor: msg.anchor || null,
1681
+ rects,
1682
+ generation,
1683
+ relation,
1684
+ clip,
1685
+ horizontal: Number.isFinite(msg.horizontal) ? Number(msg.horizontal) : null,
1686
+ };
1687
+ }
1688
+ listen(window, "message", async (event) => {
1689
+ if (!frameController.accepts(event))
1690
+ return;
1691
+ const msg = event.data;
1692
+ switch (msg.type) {
1693
+ case "eh:ready": {
1694
+ const readyIdentity = currentRender();
1695
+ const readyState = await frameController.ready();
1696
+ if (!readyState || !sameRender(readyIdentity, currentRender()))
1697
+ return;
1698
+ state.page = { ...state.page, ...readyState };
1699
+ toFrame({ type: "eh:anchors", comments: state.page ? state.page.comments : [] });
1700
+ if (frameController.state.reloading) {
1701
+ toFrame({ type: "eh:restoreScroll", x: state.scroll.x, y: state.scroll.y });
1702
+ frameController.restoredScroll();
1703
+ }
1704
+ const configuration = reviewConfiguration(state.page, state.reviewMode);
1705
+ state.savePolicy = configuration.savePolicy;
1706
+ void frameController.configure(configuration.mode, configuration.savePolicy, false);
1707
+ render();
1708
+ if (state.page?.kind !== "url") {
1709
+ const rawIdentity = currentRender();
1710
+ void api(`/api/page/${frameController.state.key}/raw`).then((raw) => {
1711
+ if (!sameRender(rawIdentity, currentRender()) || frameController.state.pendingReload)
1712
+ return;
1713
+ if (frameController.state.sourceHash && frameController.state.sourceHash !== raw.hash) {
1714
+ saveController.markConflict();
1715
+ holdReload();
1716
+ return;
1717
+ }
1718
+ saveController.baseline(raw.hash || null);
1719
+ if (configuration.savePolicy === "writable")
1720
+ toFrame({ type: "eh:raw", html: raw.html });
1721
+ scheduleResultCapture();
1722
+ }).catch((error) => {
1723
+ if (sameRender(rawIdentity, currentRender()) && !state.ended) {
1724
+ toast(`Source could not be loaded: ${error.message}. Reload before saving.`);
1725
+ }
1726
+ });
1727
+ }
1728
+ void refreshHistory();
1729
+ break;
1730
+ }
1731
+ case "eh:configurationApplied":
1732
+ if (!frameController.configured(msg.mode, msg.savePolicy))
1733
+ break;
1734
+ scheduleResultCapture();
1735
+ announce(`${state.reviewMode === "edit" ? "Edit" : "View"} mode active`);
1736
+ break;
1737
+ case "eh:target": {
1738
+ const detail = targetPayload(msg);
1739
+ if (!detail)
1740
+ return;
1741
+ if (state.target && detail.generation < state.target.generation)
1742
+ return;
1743
+ state.target = detail;
1744
+ break;
1745
+ }
1746
+ case "eh:openComment": {
1747
+ const requestedGeneration = Number(msg.targetGeneration);
1748
+ const detail = targetPayload(msg);
1749
+ let accepted = false;
1750
+ if (detail && (!state.target || detail.generation >= state.target.generation)) {
1751
+ accepted = await openCompose(detail);
1752
+ }
1753
+ if (!accepted && state.compose) {
1754
+ state.compose.rejectedTargetGeneration = Math.max(Number(state.compose.rejectedTargetGeneration) || 0, requestedGeneration);
1755
+ }
1756
+ toFrame({
1757
+ type: "eh:commentOpenResult",
1758
+ accepted,
1759
+ requestedGeneration,
1760
+ targetGeneration: state.compose?.generation || null,
1761
+ });
1762
+ break;
1763
+ }
1764
+ case "eh:targetGeometry":
1765
+ if (state.compose && msg.targetGeneration !== state.compose.generation) {
1766
+ diagnostic("geometry-rejected", { reason: "stale" });
1767
+ break;
1768
+ }
1769
+ if (state.compose) {
1770
+ const geometry = targetPayload({ ...msg, kind: state.compose.kind });
1771
+ if (!geometry) {
1772
+ diagnostic("geometry-rejected", { reason: "invalid" });
1773
+ break;
1774
+ }
1775
+ state.compose.rects = geometry.rects;
1776
+ state.compose.relation = geometry.relation;
1777
+ state.compose.clip = geometry.clip;
1778
+ state.compose.horizontal = geometry.horizontal ?? state.compose.horizontal;
1779
+ positionCompose();
1780
+ }
1781
+ break;
1782
+ case "eh:commentGeometry": {
1783
+ if (!msg.id)
1784
+ break;
1785
+ const id = String(msg.id);
1786
+ if (!state.page?.comments?.some((comment) => comment.id === id)) {
1787
+ state.activeGeometry.delete(id);
1788
+ break;
1789
+ }
1790
+ const rects = sanitizeClientRects(msg.rects, {
1791
+ width: Number(msg.viewport?.width),
1792
+ height: Number(msg.viewport?.height),
1793
+ });
1794
+ state.activeGeometry.set(id, {
1795
+ rects,
1796
+ visible: msg.visible !== false && rects.length > 0,
1797
+ });
1798
+ if (state.activeSavedCommentId === id) {
1799
+ positionAlignedCard();
1800
+ restoreTransientFocus(false);
1801
+ }
1802
+ break;
1803
+ }
1804
+ case "eh:revealTargetResult":
1805
+ if (!state.compose || msg.targetGeneration !== state.compose.generation)
1806
+ break;
1807
+ announce(msg.success ? "Selection revealed" : "Selection is no longer available");
1808
+ diagnostic(msg.success ? "reveal-target-succeeded" : "reveal-target-failed");
1809
+ break;
1810
+ case "eh:interaction":
1811
+ closeModeMenu("frame-interaction");
1812
+ closeCommentMenu();
1813
+ break;
1814
+ case "eh:dismiss":
1815
+ if (!$("composeText").value.trim())
1816
+ cancelCompose();
1817
+ break;
1818
+ case "eh:activate":
1819
+ setActive(msg.id, false);
1820
+ break;
1821
+ case "eh:anchorStatus":
1822
+ state.orphans = new Set(msg.orphaned || []);
1823
+ render();
1824
+ break;
1825
+ case "eh:notInView":
1826
+ toast("That comment is not visible in this view");
1827
+ break;
1828
+ case "eh:formBlocked":
1829
+ toast(String(msg.reason || "This form cannot be submitted from View mode"));
1830
+ break;
1831
+ case "eh:edit":
1832
+ saveController.markEdit();
1833
+ void persistEdit(frameController.state.key, {
1834
+ label: msg.label,
1835
+ kind: msg.kind,
1836
+ before: msg.before,
1837
+ after: msg.after,
1838
+ before_html: msg.before_html,
1839
+ after_html: msg.after_html,
1840
+ moved_after: msg.moved_after,
1841
+ moved_before: msg.moved_before,
1842
+ staged_assets: msg.staged_assets,
1843
+ });
1844
+ break;
1845
+ case "eh:asset": {
1846
+ const identity = currentRender();
1847
+ const query = new URLSearchParams({
1848
+ type: msg.assetType || "", sessionId: state.sessionId,
1849
+ renderId: identity.renderId, generation: String(identity.generation),
1850
+ savePolicy: frameController.state.execution?.savePolicy || "feedback-only",
1851
+ });
1852
+ try {
1853
+ const data = await api(`/api/page/${identity.key}/asset?${query}`, {
1854
+ method: "POST",
1855
+ headers: { "content-type": "application/octet-stream" },
1856
+ body: msg.bytes,
1857
+ });
1858
+ if (!sameRender(identity, currentRender()))
1859
+ break;
1860
+ toFrame({ type: "eh:assetSaved", id: msg.id, src: data.src, stagedId: data.stagedId });
1861
+ }
1862
+ catch (err) {
1863
+ if (!sameRender(identity, currentRender()))
1864
+ break;
1865
+ toast(err.message);
1866
+ toFrame({ type: "eh:assetFailed", id: msg.id });
1867
+ }
1868
+ break;
1869
+ }
1870
+ case "eh:saving":
1871
+ saveController.markSaving();
1872
+ renderSave();
1873
+ break;
1874
+ case "eh:html":
1875
+ await saveNow(msg.html);
1876
+ break;
1877
+ case "eh:clean":
1878
+ saveController.observeClean();
1879
+ break;
1880
+ case "eh:snapshot":
1881
+ captures.receive(msg);
1882
+ break;
1883
+ case "eh:viewChanged": {
1884
+ // Only a deduplicated identity-change signal can reopen this render's
1885
+ // automatic attempt. Snapshot and ordinary mutation messages cannot.
1886
+ captureCoordinator.reset();
1887
+ manualCaptureController?.abort();
1888
+ scheduleResultCapture();
1889
+ break;
1890
+ }
1891
+ case "eh:dynamic":
1892
+ saveController.markDynamic();
1893
+ renderSave();
1894
+ break;
1895
+ case "eh:flushed":
1896
+ frameController.flushed(msg.requestId);
1897
+ break;
1898
+ case "eh:scroll":
1899
+ state.scroll = { x: msg.x, y: msg.y };
1900
+ break;
1901
+ case "eh:external": {
1902
+ // This side is what actually calls window.open, so it re-checks the
1903
+ // scheme rather than trusting the frame: a javascript: or data: URL
1904
+ // arriving here would run on this origin, next to the token.
1905
+ const external = externalHref(msg.href, location.href);
1906
+ if (external)
1907
+ window.open(external, "_blank", "noopener");
1908
+ break;
1909
+ }
1910
+ case "eh:navigate":
1911
+ try {
1912
+ await reviewController.navigate({ href: msg.href });
1913
+ }
1914
+ catch (err) {
1915
+ toast(err.message);
1916
+ }
1917
+ break;
1918
+ default:
1919
+ break;
1920
+ }
1921
+ });
1922
+ // --------------------------------------------------------------- UI wiring
1923
+ let composeComposing = false;
1924
+ listen($("composeAdd"), "click", commitCompose);
1925
+ listen($("composeCancel"), "click", cancelCompose);
1926
+ listen($("composeClose"), "click", cancelCompose);
1927
+ listen($("composeReveal"), "click", () => {
1928
+ if (!state.compose)
1929
+ return;
1930
+ diagnostic("reveal-target-requested");
1931
+ toFrame({ type: "eh:revealTarget", targetGeneration: state.compose.generation });
1932
+ });
1933
+ listen($("compose"), "mousedown", (event) => {
1934
+ if (event.target.closest("button"))
1935
+ return;
1936
+ if (event.target !== $("composeText"))
1937
+ $("composeText").focus();
1938
+ });
1939
+ listen($("composeText"), "compositionstart", () => {
1940
+ composeComposing = true;
1941
+ });
1942
+ listen($("composeText"), "compositionend", () => {
1943
+ composeComposing = false;
1944
+ });
1945
+ listen($("composeText"), "keydown", (event) => {
1946
+ if (event.key === "Enter") {
1947
+ event.stopPropagation();
1948
+ if (composeComposing || event.isComposing || event.shiftKey)
1949
+ return;
1950
+ event.preventDefault();
1951
+ void commitCompose();
1952
+ }
1953
+ if (event.key === "Escape") {
1954
+ event.stopPropagation();
1955
+ event.preventDefault();
1956
+ cancelCompose();
1957
+ }
1958
+ });
1959
+ listen($("modeButton"), "click", () => {
1960
+ if ($("modeMenu").hidden)
1961
+ openModeMenu();
1962
+ else
1963
+ closeModeMenu("trigger", { restoreFocus: true });
1964
+ });
1965
+ listen($("modeMenu"), "click", (event) => {
1966
+ const item = event.target.closest("[data-mode]");
1967
+ if (item)
1968
+ void setReviewMode(item.dataset.mode);
1969
+ });
1970
+ listen($("modeMenu"), "keydown", (event) => {
1971
+ const items = [...$("modeMenu").querySelectorAll("[data-mode]")];
1972
+ const current = items.indexOf(document.activeElement);
1973
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
1974
+ event.preventDefault();
1975
+ const delta = event.key === "ArrowDown" ? 1 : -1;
1976
+ items[(current + delta + items.length) % items.length].focus();
1977
+ }
1978
+ else if (event.key === "Escape") {
1979
+ event.preventDefault();
1980
+ event.stopPropagation();
1981
+ closeModeMenu("escape", { restoreFocus: true });
1982
+ }
1983
+ });
1984
+ listen($("commentsButton"), "click", openDrawer);
1985
+ listen($("drawerClose"), "click", closeDrawer);
1986
+ listen($("drawerBackdrop"), "click", closeDrawer);
1987
+ const dismissModeMenuOutside = (event) => {
1988
+ if (!state.modeMenuOpen || event.target.closest(".mode-control"))
1989
+ return;
1990
+ closeModeMenu(event.type === "focusin" ? "parent-focus" : "parent-pointer");
1991
+ };
1992
+ listen(document, "pointerdown", dismissModeMenuOutside, true);
1993
+ listen(document, "focusin", dismissModeMenuOutside, true);
1994
+ function closeCommentMenu({ restoreFocus = false } = {}) {
1995
+ const menu = state.commentUi.menu;
1996
+ if (!menu)
1997
+ return false;
1998
+ clearOwned(state.commentUi, "menu");
1999
+ toFrame({ type: "eh:modeMenuState", open: false });
2000
+ if (restoreFocus)
2001
+ requestControlFocus(menu.triggerId);
2002
+ render();
2003
+ return true;
2004
+ }
2005
+ const dismissCommentMenuOutside = (event) => {
2006
+ const menu = state.commentUi.menu;
2007
+ if (!menu)
2008
+ return;
2009
+ const menuElement = document.getElementById(controlId(menu.commentId, menu.surface, "menu"));
2010
+ const trigger = document.getElementById(menu.triggerId);
2011
+ if (menuElement?.contains(event.target) || trigger?.contains(event.target))
2012
+ return;
2013
+ closeCommentMenu();
2014
+ };
2015
+ listen(document, "pointerdown", dismissCommentMenuOutside, true);
2016
+ listen(document, "focusin", dismissCommentMenuOutside, true);
2017
+ const sendFeedback = () => feedbackController.send();
2018
+ listen($("send"), "click", () => void sendFeedback());
2019
+ listen($("revert"), "click", async () => {
2020
+ const count = state.page.edits.length;
2021
+ if (!window.confirm(`Discard all ${count} of your edits?`))
2022
+ return;
2023
+ try {
2024
+ await saveController.revert();
2025
+ }
2026
+ catch (err) {
2027
+ toast(err.message);
2028
+ }
2029
+ });
2030
+ /** The session is over: freeze the page and say so. Feedback is already safe. */
2031
+ function showEnded() {
2032
+ if (document.querySelector(".ended"))
2033
+ return;
2034
+ state.ended = true;
2035
+ captureCoordinator.stop();
2036
+ manualCaptureController?.abort();
2037
+ captures.cancel("Review ended");
2038
+ historyController.cancel();
2039
+ reviewController.dispose();
2040
+ const overlay = document.createElement("div");
2041
+ overlay.className = "ended";
2042
+ const title = document.createElement("h2");
2043
+ title.textContent = "Review ended";
2044
+ const line = document.createElement("p");
2045
+ line.textContent = "Unsent feedback is saved and ships next time you review this page. You can close this tab.";
2046
+ overlay.append(title, line);
2047
+ document.body.append(overlay);
2048
+ }
2049
+ listen($("endReview"), "click", async () => {
2050
+ const page = state.page;
2051
+ const otherTotal = (state.others || []).reduce((sum, o) => sum + o.count, 0);
2052
+ const unsent = page ? (page.comments || []).length + (page.edits || []).length + otherTotal : 0;
2053
+ const message = unsent
2054
+ ? `End this review? ${unsent} unsent ${unsent === 1 ? "item" : "items"} will be kept for next time.`
2055
+ : "End this review? The waiting agent will be told to stop polling.";
2056
+ if (!window.confirm(message))
2057
+ return;
2058
+ try {
2059
+ // Ship anything still sitting in the SDK's debounce windows first.
2060
+ await flushFrame();
2061
+ await api(`/api/session/${state.sessionId}/end`, { method: "POST" });
2062
+ showEnded();
2063
+ }
2064
+ catch (err) {
2065
+ toast(err.message);
2066
+ }
2067
+ });
2068
+ listen($("handoffCopy"), "click", async (event) => {
2069
+ const button = event.currentTarget;
2070
+ try {
2071
+ await navigator.clipboard.writeText($("handoffCmd").textContent);
2072
+ button.textContent = "Copied";
2073
+ afterDelay(() => {
2074
+ button.textContent = "Copy prompt";
2075
+ }, 1600);
2076
+ }
2077
+ catch {
2078
+ toast("Couldn't copy — select the prompt and copy it manually");
2079
+ }
2080
+ });
2081
+ listen($("note"), "input", (event) => {
2082
+ const el = event.target;
2083
+ el.style.height = "auto";
2084
+ el.style.height = `${Math.min(el.scrollHeight + 2, window.innerHeight * 0.4)}px`;
2085
+ render(); // keep the send button in step with note-only feedback
2086
+ });
2087
+ listen($("theme"), "click", () => {
2088
+ const dark = document.documentElement.dataset.theme !== "dark";
2089
+ applyTheme(dark);
2090
+ try {
2091
+ localStorage.setItem("doc-review:theme", dark ? "dark" : "light");
2092
+ }
2093
+ catch { }
2094
+ });
2095
+ function applyTheme(dark) {
2096
+ document.documentElement.dataset.theme = dark ? "dark" : "light";
2097
+ const button = $("theme");
2098
+ button.title = dark ? "Switch chrome to light" : "Switch chrome to dark";
2099
+ button.setAttribute("aria-label", button.title);
2100
+ replaceIcon(button, dark ? "sun" : "moon");
2101
+ }
2102
+ listen(document, "keydown", (event) => {
2103
+ const meta = event.metaKey || event.ctrlKey;
2104
+ // ⌘S is reassurance only: flush pending keystrokes, never a state change.
2105
+ if (meta && event.key.toLowerCase() === "s") {
2106
+ event.preventDefault();
2107
+ toFrame({ type: "eh:flush" });
2108
+ renderSave();
2109
+ return;
2110
+ }
2111
+ if (event.key === "Tab" && state.commentUi.menu) {
2112
+ closeCommentMenu();
2113
+ return;
2114
+ }
2115
+ if (event.key !== "Escape")
2116
+ return;
2117
+ const recoveryMenu = event.target.closest?.("#reviewDetails");
2118
+ if (recoveryMenu) {
2119
+ recoveryMenu.open = false;
2120
+ recoveryMenu.querySelector("summary")?.focus({ preventScroll: true });
2121
+ event.preventDefault();
2122
+ event.stopPropagation();
2123
+ return;
2124
+ }
2125
+ let handled = false;
2126
+ if (state.commentUi.confirmation)
2127
+ handled = cancelDeleteConfirmation();
2128
+ else if (state.commentUi.menu)
2129
+ handled = closeCommentMenu({ restoreFocus: true });
2130
+ else if (state.commentUi.edit)
2131
+ handled = cancelCommentEdit();
2132
+ else if (state.compose)
2133
+ handled = cancelCompose();
2134
+ else if (state.modeMenuOpen)
2135
+ handled = closeModeMenu("escape", { restoreFocus: true });
2136
+ else if (state.drawerOpen) {
2137
+ closeDrawer();
2138
+ handled = true;
2139
+ }
2140
+ else if (state.activeSavedCommentId)
2141
+ handled = dismissActiveComment("escape", { restoreFocus: true });
2142
+ if (handled) {
2143
+ event.preventDefault();
2144
+ event.stopPropagation();
2145
+ }
2146
+ });
2147
+ // ------------------------------------------------------------------ events
2148
+ function holdReload() {
2149
+ frameController.holdReload();
2150
+ saveController.hold();
2151
+ $("reloadNotice").hidden = false;
2152
+ $("reloadMessage").textContent = saveController.state.dirty || saveController.state.conflict
2153
+ ? "The source changed. This page has unsaved edits; reload discards those page edits, but keeps open comment drafts. Stale edits will not overwrite the new source."
2154
+ : "The source changed. Reload keeps your comment drafts as unresolved excerpts so they cannot attach to the wrong content.";
2155
+ captureCoordinator.reset();
2156
+ manualCaptureController?.abort();
2157
+ captures.cancel();
2158
+ renderExecution();
2159
+ if (state.comparing)
2160
+ renderHistory();
2161
+ }
2162
+ async function reloadLatest({ explicit = false } = {}) {
2163
+ if (!explicit && (draftCount(state) || saveController.state.dirty || saveController.state.conflict || feedbackController.sending)) {
2164
+ holdReload();
2165
+ return;
2166
+ }
2167
+ const key = frameController.state.key;
2168
+ advancePageEpoch("reload");
2169
+ captureEditState();
2170
+ if (state.compose) {
2171
+ state.compose.unresolved = true;
2172
+ state.compose.relation = "unavailable";
2173
+ state.compose.rects = [];
2174
+ state.compose.generation = -1;
2175
+ }
2176
+ const generation = beginFrameTransition();
2177
+ frameController.resetRetries();
2178
+ frameController.startReload();
2179
+ saveController.reset();
2180
+ $("reloadNotice").hidden = true;
2181
+ try {
2182
+ const page = await api(pageUrl(key, state.sessionId), undefined, decodePage);
2183
+ if (frameController.state.key !== key || frameController.state.generation !== generation)
2184
+ return;
2185
+ state.executionPreference = page.executionPreference || null;
2186
+ // Keep parent-owned drafts rather than replacing their text on a source update.
2187
+ replacePage(state, page);
2188
+ saveController.reset();
2189
+ render();
2190
+ if (state.compose) {
2191
+ $("compose").hidden = false;
2192
+ $("compose").classList.add("sheet");
2193
+ $("composeError").hidden = false;
2194
+ $("composeError").textContent = "The source changed. This draft keeps its original excerpt; cancel it to select a new target.";
2195
+ }
2196
+ await registerFrame(key, generation);
2197
+ }
2198
+ catch (err) {
2199
+ if (frameController.state.key === key && frameController.state.generation === generation)
2200
+ failFrame(err.message);
2201
+ }
2202
+ }
2203
+ listen($("safeReload"), "click", () => void reloadLatest({ explicit: true }));
2204
+ listen($("keepCurrent"), "click", () => { $("reloadNotice").hidden = true; announce("Keeping the current page. Return to Latest version to reload when ready."); });
2205
+ listen(window, "beforeunload", (event) => {
2206
+ if (!saveController.state.dirty && !draftCount(state, $("note").value) && !saveController.queued(frameController.state.key))
2207
+ return;
2208
+ event.preventDefault();
2209
+ event.returnValue = "";
2210
+ });
2211
+ listen(window, "pagehide", (event) => {
2212
+ if (event.persisted)
2213
+ return;
2214
+ state.ended = true;
2215
+ captureCoordinator.stop();
2216
+ manualCaptureController?.abort();
2217
+ captures.cancel("Review closed");
2218
+ historyController.cancel();
2219
+ reviewController.dispose();
2220
+ });
2221
+ const connect = () => reviewController.connect();
2222
+ // -------------------------------------------------------------------- start
2223
+ (async function start() {
2224
+ installStaticIcons();
2225
+ try {
2226
+ applyTheme(localStorage.getItem("doc-review:theme") === "dark");
2227
+ }
2228
+ catch { }
2229
+ const bootstrap = await api(`/api/session/${state.sessionId}/page`);
2230
+ if (bootstrap && bootstrap.page)
2231
+ state.pollCommand = bootstrap.page.pollCommand;
2232
+ if (bootstrap && Number.isSafeInteger(bootstrap.generation))
2233
+ frameController.seedGeneration(bootstrap.generation);
2234
+ const key = bootstrap ? bootstrap.key : new URLSearchParams(location.search).get("key");
2235
+ await loadPage(key);
2236
+ connect();
2237
+ void refreshHistory();
2238
+ })().catch((error) => {
2239
+ failFrame(`Review could not start: ${error.message}`);
2240
+ });
2241
+ listen(window, "resize", () => {
2242
+ positionCompose();
2243
+ if (state.activeSavedCommentId)
2244
+ positionAlignedCard();
2245
+ });
2246
+ if (window.visualViewport) {
2247
+ listen(window.visualViewport, "resize", positionCompose);
2248
+ listen(window.visualViewport, "scroll", positionCompose);
2249
+ }
2250
+ reviewController.own(frameHost.onFocus(() => {
2251
+ closeCommentMenu();
2252
+ if (state.compose)
2253
+ $("compose").classList.add("pass-through");
2254
+ }));
2255
+ listen($("compose"), "focusin", () => $("compose").classList.remove("pass-through"));