@autono/pinbox-toolbar 0.14.0 → 0.16.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.
@@ -22,254 +22,170 @@ function watchAnchors(win, onChange) {
22
22
  } };
23
23
  }
24
24
  //#endregion
25
- //#region src/targeting/dom.ts
26
- /**
27
- * Deepest element under (clientX, clientY) that the caller does not ignore, or null when there is
28
- * nothing there but page chrome (html/body).
29
- *
30
- * Looks THROUGH our own overlay rather than giving up at it. The single-element form could not:
31
- * the drag-aim grip sits exactly on the point being aimed at, so it is always the topmost thing
32
- * under the crosshair, and every probe came back "nothing" the moment touch aiming existed.
33
- */
34
- function hitTest(doc, x, y, ignore) {
35
- const stack = doc.elementsFromPoint?.(x, y) ?? [doc.elementFromPoint(x, y)];
36
- for (const el of stack) {
37
- if (!el || el === doc.body || el === doc.documentElement) return null;
38
- if (!ignore(el)) return el;
39
- }
40
- return null;
25
+ //#region src/capture-mode.ts
26
+ function captureKey(prefix) {
27
+ return `${prefix}:capture`;
41
28
  }
42
- /** CLASS-or-TAG display name with a sibling index when needed (prototype nodeName). */
43
- function nodeName(el) {
44
- const key = el.classList[0];
45
- let name = (key ?? el.tagName).toUpperCase();
46
- const parent = el.parentElement;
47
- if (parent) {
48
- const sibs = [...parent.children].filter((c) => c.classList[0] === key && c.tagName === el.tagName);
49
- if (sibs.length > 1) name += ` ${sibs.indexOf(el) + 1}`;
50
- }
51
- return name;
52
- }
53
- /**
54
- * Human label for a target: an explicit data-pb-el annotation wins; otherwise a
55
- * CLASS/TAG ancestry chain of at most 3 parts joined with ›, terminating early
56
- * at the first annotated ancestor.
57
- */
58
- function targetLabel(el) {
59
- const own = el.getAttribute("data-pb-el");
60
- if (own) return own;
61
- const parts = [nodeName(el)];
62
- const body = el.ownerDocument.body;
63
- let node = el.parentElement;
64
- while (node && node !== body && parts.length < 3) {
65
- const anchor = node.getAttribute("data-pb-el");
66
- if (anchor) {
67
- parts.unshift(anchor);
68
- break;
69
- }
70
- if (node.classList[0]) parts.unshift(nodeName(node));
71
- node = node.parentElement;
72
- }
73
- return parts.join(" › ");
29
+ function loadCaptureMode(storage, key, fallback) {
30
+ try {
31
+ const raw = storage?.getItem(key);
32
+ if (raw === "dom" || raw === "tab") return raw;
33
+ } catch {}
34
+ return fallback;
74
35
  }
75
- const SAFE_ID = /^[A-Za-z][\w-]*$/;
76
- /** Data attributes trusted as stable hooks, in priority order. */
77
- const STABLE_DATA_ATTRS = [
78
- "data-pb-anchor",
79
- "data-pb-el",
80
- "data-testid"
81
- ];
82
- function attrSegment(el, doc) {
83
- for (const attr of STABLE_DATA_ATTRS) {
84
- const value = el.getAttribute(attr);
85
- if (value === null || value.includes("\"") || value.includes("\\")) continue;
86
- const selector = `${el.tagName.toLowerCase()}[${attr}="${value}"]`;
87
- if (doc.querySelectorAll(selector).length === 1) return selector;
88
- }
89
- return null;
36
+ function saveCaptureMode(storage, key, mode) {
37
+ try {
38
+ storage?.setItem(key, mode);
39
+ } catch {}
90
40
  }
91
- function nthSegment(el) {
92
- const tag = el.tagName.toLowerCase();
93
- const parent = el.parentElement;
94
- if (!parent) return tag;
95
- const sameTag = [...parent.children].filter((c) => c.tagName === el.tagName);
96
- return sameTag.length > 1 ? `${tag}:nth-of-type(${sameTag.indexOf(el) + 1})` : tag;
41
+ //#endregion
42
+ //#region src/ui/actions.ts
43
+ const PIN_GLYPH = "<rect x=\"3\" y=\"1.5\" width=\"10\" height=\"6.5\" rx=\"1\"/><path d=\"M8 8v6.5\"/>";
44
+ const INBOX_GLYPH = "<path d=\"M1.8 8.5h3.4l1 2h3.6l1-2h3.4\"/><path d=\"M2.6 3.2h10.8l1.2 5.3v4a1 1 0 01-1 1H2.4a1 1 0 01-1-1v-4z\"/>";
45
+ const THEME_GLYPH = "<path d=\"M8 2a4 4 0 0 0 6 6 6 6 0 1 1-6-6z\"/>";
46
+ const COPY_GLYPH = "<rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1\"/><path d=\"M10.5 3.5v-1a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h1\"/>";
47
+ const EYE_GLYPH = "<path d=\"M1.6 8S4 3.8 8 3.8 14.4 8 14.4 8 12 12.2 8 12.2 1.6 8 1.6 8z\"/><circle cx=\"8\" cy=\"8\" r=\"1.8\"/>";
48
+ const EYE_OFF_GLYPH = "<path d=\"M2.3 2.3l11.4 11.4\"/><path d=\"M4.9 4.9C2.7 6.2 1.6 8 1.6 8s2.4 4.2 6.4 4.2c1.2 0 2.3-.3 3.1-.8M6.7 4c.4-.1.9-.2 1.3-.2 4 0 6.4 4.2 6.4 4.2s-.8 1.4-2.2 2.5\"/>";
49
+ const MIN_GLYPH = "<path d=\"M6.5 2.5v4h-4\"/><path d=\"M9.5 13.5v-4h4\"/>";
50
+ const CAMERA_GLYPH = "<path d=\"M2 5.5h2.6l1.2-1.8h4.4L11.4 5.5H14v7.5H2z\"/><circle cx=\"8\" cy=\"9\" r=\"2.3\"/>";
51
+ const EXPAND_GLYPH = "<path d=\"M9.5 6.5v-4h4\"/><path d=\"M6.5 9.5v4h-4\"/>";
52
+ /** Frame a glyph as an inline SVG at `size` px. */
53
+ function icon(glyph, size) {
54
+ return `<svg width="${size}" height="${size}" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4">${glyph}</svg>`;
97
55
  }
98
- /**
99
- * Stable CSS path for an element: ids > stable data attributes > an
100
- * nth-of-type chain. Guaranteed round-trip: querySelector(buildSelector(el)) === el.
101
- */
102
- function buildSelector(el) {
103
- const doc = el.ownerDocument;
104
- const segments = [];
105
- let node = el;
106
- while (node && node !== doc.documentElement) {
107
- const id = node.getAttribute("id");
108
- if (id && SAFE_ID.test(id) && doc.querySelectorAll(`#${id}`).length === 1) {
109
- segments.unshift(`#${id}`);
110
- return segments.join(" > ");
111
- }
112
- const byAttr = attrSegment(node, doc);
113
- if (byAttr) {
114
- segments.unshift(byAttr);
115
- return segments.join(" > ");
56
+ /** Ordered as the bar and fan lay them out. */
57
+ const ACTIONS = [
58
+ {
59
+ id: "pin",
60
+ label: "Drop a pin",
61
+ key: "p",
62
+ glyph: PIN_GLYPH,
63
+ bar: { text: "PIN" },
64
+ fan: {}
65
+ },
66
+ {
67
+ id: "inbox",
68
+ label: "Open inbox",
69
+ key: "i",
70
+ glyph: INBOX_GLYPH,
71
+ bar: { count: true },
72
+ fan: {}
73
+ },
74
+ {
75
+ id: "copy",
76
+ label: "Copy open pins",
77
+ key: "c",
78
+ glyph: COPY_GLYPH,
79
+ bar: {},
80
+ fan: {}
81
+ },
82
+ {
83
+ id: "theme",
84
+ label: "Toggle theme",
85
+ key: "d",
86
+ glyph: THEME_GLYPH,
87
+ bar: {},
88
+ fan: {}
89
+ },
90
+ {
91
+ id: "hide",
92
+ label: "Hide / show pins",
93
+ key: "h",
94
+ glyph: EYE_OFF_GLYPH,
95
+ bar: {},
96
+ fan: { label: "Hide pins" }
97
+ },
98
+ {
99
+ id: "capture",
100
+ label: "Tab capture for screenshots (Chrome asks once)",
101
+ key: "s",
102
+ glyph: CAMERA_GLYPH,
103
+ bar: {}
104
+ },
105
+ {
106
+ id: "help",
107
+ label: "Shortcuts",
108
+ key: "?",
109
+ bar: {},
110
+ help: false
111
+ },
112
+ {
113
+ id: "minimize",
114
+ label: "Minimize toolbar",
115
+ key: "m",
116
+ glyph: MIN_GLYPH,
117
+ bar: { ariaLabel: "Minimize toolbar" },
118
+ fan: {
119
+ act: "expand",
120
+ label: "Expand"
116
121
  }
117
- segments.unshift(nthSegment(node));
118
- node = node.parentElement;
122
+ },
123
+ {
124
+ id: "resolve",
125
+ label: "Mark pin resolved",
126
+ key: "r"
127
+ },
128
+ {
129
+ id: "escape",
130
+ label: "Cancel",
131
+ key: "escape",
132
+ keyLabel: "ESC"
119
133
  }
120
- return segments.join(" > ");
121
- }
122
- //#endregion
123
- //#region src/capture.ts
124
- /** Curated computed-style subset — enough to reconstruct layout intent, tiny on the wire. */
125
- const STYLE_KEYS = [
126
- "display",
127
- "position",
128
- "font-size",
129
- "color",
130
- "background-color",
131
- "margin",
132
- "padding",
133
- "overflow"
134
134
  ];
135
- const NEARBY_TEXT_MAX = 160;
136
- function styleSubset(win, el) {
137
- let cs;
138
- try {
139
- cs = win.getComputedStyle(el);
140
- } catch {
141
- return;
142
- }
143
- const out = {};
144
- for (const key of STYLE_KEYS) {
145
- const value = cs.getPropertyValue(key);
146
- if (value !== "") out[key] = value;
147
- }
148
- return Object.keys(out).length > 0 ? out : void 0;
149
- }
150
- function ariaMap(el) {
151
- const out = {};
152
- for (const name of el.getAttributeNames()) if (name.startsWith("aria-")) out[name] = el.getAttribute(name) ?? "";
153
- return Object.keys(out).length > 0 ? out : void 0;
154
- }
155
- function nearbyText(el) {
156
- const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
157
- return text === "" ? void 0 : text.slice(0, NEARBY_TEXT_MAX);
158
- }
159
- /** The user's selection, only when it intersects the captured element. */
160
- function selectedText(win, el) {
161
- try {
162
- const sel = win.getSelection?.();
163
- if (!sel || sel.isCollapsed || sel.rangeCount === 0) return void 0;
164
- if (!sel.getRangeAt(0).intersectsNode(el)) return void 0;
165
- const text = sel.toString().trim();
166
- return text === "" ? void 0 : text;
167
- } catch {
168
- return;
169
- }
135
+ function keyLabelOf(a) {
136
+ return a.keyLabel ?? (a.key ?? "").toUpperCase();
170
137
  }
171
- /** `fixed` detected via ancestry: any ancestor with computed position: fixed. */
172
- function isFixed(win, el) {
173
- for (let node = el; node !== null; node = node.parentElement) try {
174
- if (win.getComputedStyle(node).position === "fixed") return true;
175
- } catch {
176
- return false;
177
- }
178
- return false;
138
+ /** "Drop a pin (P)" the bar's hover title. */
139
+ function titleOf(a) {
140
+ return a.key === void 0 ? a.label : `${a.label} (${keyLabelOf(a)})`;
179
141
  }
180
- /** Beyond this an element is not a thing you pinned, it is a region. Too many to rewrite as a set. */
181
- const MAX_RUNS = 40;
182
- const MAX_RUN_LENGTH = 200;
183
- /** Text that is not content: a script body or a stylesheet is not something to rewrite. */
184
- const NON_CONTENT = /* @__PURE__ */ new Set([
185
- "SCRIPT",
186
- "STYLE",
187
- "NOSCRIPT",
188
- "TEMPLATE"
142
+ /** Lower-cased `KeyboardEvent.key` action. `?` keeps its case: it only exists shifted. */
143
+ const ACTION_BY_KEY = new Map(ACTIONS.filter((a) => a.key !== void 0).map((a) => [a.key, a.id]));
144
+ //#endregion
145
+ //#region src/keys.ts
146
+ /** Hosts mark a subtree the toolbar must ignore keys from (custom editors, games). */
147
+ const IGNORE_KEYS_ATTR = "data-pinbox-ignore-keys";
148
+ const TEXT_TAGS = /* @__PURE__ */ new Set([
149
+ "TEXTAREA",
150
+ "INPUT",
151
+ "SELECT"
189
152
  ]);
153
+ const TEXT_ROLE_SELECTOR = [
154
+ "textbox",
155
+ "combobox",
156
+ "searchbox",
157
+ "spinbutton"
158
+ ].map((r) => `[role="${r}"]`).join(",");
190
159
  /**
191
- * The element's text, split the way the browser stores it: one entry per run of characters.
192
- *
193
- * This walks TEXT NODES, not elements, and that distinction is the whole point — it makes no
194
- * assumption about how a site is built. A heading is one run. A nav bar is one per link. A
195
- * paragraph with a bold word in the middle is three, in reading order, including the halves either
196
- * side of the bold. An earlier version keyed off "elements with no element children", which
197
- * quietly lost the "Hello " in `<p>Hello <b>world</b></p>` — text a person can obviously see and
198
- * would obviously expect to be able to change.
199
- *
200
- * `nearbyText` runs them all together, which is fine to read and useless to edit: it cannot tell
201
- * an agent that "work approach people contact" is four separate places. This can.
160
+ * Is the key going into a text control? `INPUT`/`TEXTAREA`/contentEditable, plus
161
+ * the things the old check missed: `<select>`, ARIA text roles on custom editors,
162
+ * and any ancestor flagged with `data-pinbox-ignore-keys`.
202
163
  */
203
- function textRuns(el) {
204
- const runs = [];
205
- const walk = (node) => {
206
- if (node.nodeType === 3) {
207
- const text = (node.nodeValue ?? "").trim();
208
- if (text.length > 0) runs.push(text.slice(0, MAX_RUN_LENGTH));
209
- return runs.length <= MAX_RUNS;
210
- }
211
- if (node.nodeType !== 1 || NON_CONTENT.has(node.tagName)) return true;
212
- for (const child of node.childNodes) if (!walk(child)) return false;
213
- return true;
214
- };
215
- if (!walk(el) || runs.length === 0) return void 0;
216
- return runs;
217
- }
218
- function buildContext(win, el) {
219
- const context = {};
220
- if (el.classList.length > 0) context.classes = [...el.classList];
221
- const styles = styleSubset(win, el);
222
- if (styles !== void 0) context.styles = styles;
223
- const aria = ariaMap(el);
224
- if (aria !== void 0) context.aria = aria;
225
- const nearby = nearbyText(el);
226
- if (nearby !== void 0) context.nearbyText = nearby;
227
- const selected = selectedText(win, el);
228
- if (selected !== void 0) context.selectedText = selected;
229
- const runs = textRuns(el);
230
- if (runs !== void 0) context.textRuns = runs;
231
- return Object.keys(context).length > 0 ? context : void 0;
164
+ function isTextEntry(target) {
165
+ const el = target;
166
+ if (!el || typeof el.tagName !== "string") return false;
167
+ if (TEXT_TAGS.has(el.tagName)) return true;
168
+ if (el.isContentEditable === true) return true;
169
+ if (el.closest?.(TEXT_ROLE_SELECTOR) != null) return true;
170
+ return el.closest?.(`[${IGNORE_KEYS_ATTR}]`) != null;
232
171
  }
233
- /** Fills PinInput.target/env from a chosen element (shapes come from the pin schema). */
234
- function captureTarget(el, opts) {
235
- const win = el.ownerDocument.defaultView;
236
- const r = el.getBoundingClientRect();
237
- const target = {
238
- url: win.location.href,
239
- selector: buildSelector(el),
240
- tag: el.tagName.toLowerCase(),
241
- rect: {
242
- x: r.left + win.scrollX,
243
- y: r.top + win.scrollY,
244
- width: r.width,
245
- height: r.height
246
- },
247
- fixed: isFixed(win, el)
248
- };
249
- if (opts?.anchor !== void 0) target.anchor = opts.anchor;
250
- if (opts?.at !== void 0 && r.width > 0 && r.height > 0) {
251
- const fx = (opts.at.x - (r.left + win.scrollX)) / r.width;
252
- const fy = (opts.at.y - (r.top + win.scrollY)) / r.height;
253
- if (fx >= 0 && fx <= 1 && fy >= 0 && fy <= 1) target.spot = {
254
- x: fx,
255
- y: fy
256
- };
257
- }
258
- const context = buildContext(win, el);
259
- if (context !== void 0) target.context = context;
260
- return {
261
- target,
262
- env: {
263
- viewport: {
264
- w: win.innerWidth,
265
- h: win.innerHeight,
266
- dpr: win.devicePixelRatio
267
- },
268
- browser: win.navigator.userAgent,
269
- os: win.navigator.platform || "unknown",
270
- colorScheme: win.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
271
- }
272
- };
172
+ /**
173
+ * Which action, if any, a keydown asks for.
174
+ *
175
+ * Modifier chords are never ours (⌘P is print, ⌃I is italics, ⌥ types
176
+ * characters); Shift is allowed because `?` needs it. Repeats and IME
177
+ * composition are ignored so a held key acts once and a composing keyboard is
178
+ * left alone.
179
+ */
180
+ function shortcutFor(e, mode = "all") {
181
+ if (mode === "off") return null;
182
+ if (e.metaKey || e.ctrlKey || e.altKey || e.repeat || e.isComposing) return null;
183
+ if (isTextEntry(e.composedPath()[0] ?? e.target)) return null;
184
+ const key = e.key === "?" ? "?" : e.key.toLowerCase();
185
+ const id = ACTION_BY_KEY.get(key);
186
+ if (id === void 0) return null;
187
+ if (mode === "escape-only" && id !== "escape") return null;
188
+ return id;
273
189
  }
274
190
  //#endregion
275
191
  //#region src/markdown.ts
@@ -317,18 +233,122 @@ function pinToMarkdown(pin, thread) {
317
233
  return `${block(pin, thread)}\n`;
318
234
  }
319
235
  //#endregion
320
- //#region src/motion/spring.ts
321
- /** Bar puck morphs and the post-drag settle. */
322
- const MORPH_SPRING = {
323
- k: 300,
324
- c: 30
325
- };
326
- /** The morph surface chasing the pointer mid-drag. */
327
- const FOLLOW_SPRING = {
328
- k: 600,
329
- c: 38
330
- };
331
- /** Integration substep — small enough that MORPH/FOLLOW stay stable at any dt. */
236
+ //#region src/motion/drag.ts
237
+ /** Movement that begins a drag */
238
+ const DRAG_START = 8;
239
+ /** …but a release under this much TOTAL travel is still a tap. */
240
+ const TAP_MAX = 12;
241
+ /**
242
+ * Attach the drag rules to `el`. Move/up listeners live on `el` itself with pointer capture
243
+ * (a capture failure on a synthetic pointer is tolerated); `touch-action: none` on the element
244
+ * is the caller's job.
245
+ */
246
+ function attachDrag(el, on) {
247
+ let hold = null;
248
+ function onPointerDown(e) {
249
+ if (e.button !== 0) return;
250
+ const origin = on.origin();
251
+ if (origin === null) return;
252
+ try {
253
+ el.setPointerCapture(e.pointerId);
254
+ } catch {}
255
+ hold = {
256
+ px: e.clientX,
257
+ py: e.clientY,
258
+ origin,
259
+ lx: e.clientX,
260
+ ly: e.clientY,
261
+ started: false
262
+ };
263
+ }
264
+ function onPointerMove(e) {
265
+ if (hold === null) return;
266
+ hold.lx = e.clientX;
267
+ hold.ly = e.clientY;
268
+ const dx = e.clientX - hold.px;
269
+ const dy = e.clientY - hold.py;
270
+ if (!hold.started) {
271
+ if (!on.canStart()) {
272
+ hold = null;
273
+ return;
274
+ }
275
+ if (Math.hypot(dx, dy) < DRAG_START) return;
276
+ hold.started = true;
277
+ on.onStart(hold.origin);
278
+ }
279
+ on.onMove({
280
+ x: hold.origin.x + dx,
281
+ y: hold.origin.y + dy
282
+ });
283
+ }
284
+ function onPointerUp() {
285
+ if (hold === null) return;
286
+ const h = hold;
287
+ hold = null;
288
+ const total = Math.hypot(h.lx - h.px, h.ly - h.py);
289
+ on.onEnd({
290
+ dragged: h.started && total >= TAP_MAX,
291
+ started: h.started,
292
+ origin: h.origin,
293
+ target: {
294
+ x: h.origin.x + (h.lx - h.px),
295
+ y: h.origin.y + (h.ly - h.py)
296
+ }
297
+ });
298
+ }
299
+ el.addEventListener("pointerdown", onPointerDown);
300
+ el.addEventListener("pointermove", onPointerMove);
301
+ el.addEventListener("pointerup", onPointerUp);
302
+ el.addEventListener("pointercancel", onPointerUp);
303
+ return {
304
+ cancel() {
305
+ hold = null;
306
+ },
307
+ destroy() {
308
+ hold = null;
309
+ el.removeEventListener("pointerdown", onPointerDown);
310
+ el.removeEventListener("pointermove", onPointerMove);
311
+ el.removeEventListener("pointerup", onPointerUp);
312
+ el.removeEventListener("pointercancel", onPointerUp);
313
+ }
314
+ };
315
+ }
316
+ /** Keep a top-left corner of a `size`-square (or w×h box) `margin` px inside the viewport. */
317
+ function clampToViewport(p, win, box, margin) {
318
+ const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
319
+ return {
320
+ x: clamp(p.x, margin, Math.max(margin, win.innerWidth - margin - box.w)),
321
+ y: clamp(p.y, margin, Math.max(margin, win.innerHeight - margin - box.h))
322
+ };
323
+ }
324
+ /** A persisted `{x,y}` (mirror convention: reads never throw upward); null when absent or malformed. */
325
+ function readPoint(storage, key) {
326
+ try {
327
+ const raw = storage?.getItem(key);
328
+ if (raw == null) return null;
329
+ const parsed = JSON.parse(raw);
330
+ if (typeof parsed.x !== "number" || typeof parsed.y !== "number") return null;
331
+ return {
332
+ x: parsed.x,
333
+ y: parsed.y
334
+ };
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+ //#endregion
340
+ //#region src/motion/spring.ts
341
+ /** Bar ⇄ puck morphs and the post-drag settle. */
342
+ const MORPH_SPRING = {
343
+ k: 300,
344
+ c: 30
345
+ };
346
+ /** The morph surface chasing the pointer mid-drag. */
347
+ const FOLLOW_SPRING = {
348
+ k: 600,
349
+ c: 38
350
+ };
351
+ /** Integration substep — small enough that MORPH/FOLLOW stay stable at any dt. */
332
352
  const SUBSTEP = 1 / 240;
333
353
  /** A property this close to target, moving this slowly, counts as settled. */
334
354
  const SETTLE = .5;
@@ -382,11 +402,7 @@ function mkSpring(init) {
382
402
  //#endregion
383
403
  //#region src/minimize.ts
384
404
  const PUCK = 48;
385
- const MARGIN = 16;
386
- /** Movement that begins a drag… */
387
- const DRAG_START = 8;
388
- /** …but a release under this much TOTAL travel is still a tap. */
389
- const TAP_MAX = 12;
405
+ const MARGIN$1 = 16;
390
406
  /** Spring hold while the surface swap crossfades (ms). */
391
407
  const HOLD_MINIMIZE = 90;
392
408
  const HOLD_RESTORE = 70;
@@ -411,7 +427,6 @@ function createMinimize(host) {
411
427
  let mode = "bar";
412
428
  let puckPos = null;
413
429
  let dock = loadDock();
414
- let pdown = null;
415
430
  let keyboardToggle = false;
416
431
  let raf = 0;
417
432
  let last = 0;
@@ -421,18 +436,7 @@ function createMinimize(host) {
421
436
  let fanOpen = false;
422
437
  let fanTimer = 0;
423
438
  function loadDock() {
424
- try {
425
- const raw = host.storage?.getItem(`${host.storagePrefix}:dock`);
426
- if (raw == null) return null;
427
- const parsed = JSON.parse(raw);
428
- if (typeof parsed.x !== "number" || typeof parsed.y !== "number") return null;
429
- return {
430
- x: parsed.x,
431
- y: parsed.y
432
- };
433
- } catch {
434
- return null;
435
- }
439
+ return readPoint(host.storage, `${host.storagePrefix}:dock`);
436
440
  }
437
441
  function persist() {
438
442
  try {
@@ -448,12 +452,11 @@ function createMinimize(host) {
448
452
  return host.initialMinimized;
449
453
  }
450
454
  }
451
- const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
452
455
  function clampPos(p) {
453
- return {
454
- x: clamp(p.x, MARGIN, win.innerWidth - MARGIN - PUCK),
455
- y: clamp(p.y, MARGIN, win.innerHeight - MARGIN - PUCK)
456
- };
456
+ return clampToViewport(p, win, {
457
+ w: PUCK,
458
+ h: PUCK
459
+ }, MARGIN$1);
457
460
  }
458
461
  function defaultDock() {
459
462
  const r = bar.getBoundingClientRect();
@@ -530,7 +533,7 @@ function createMinimize(host) {
530
533
  }
531
534
  function minimize(keyboard = false) {
532
535
  if (mode !== "bar") return;
533
- pdown = null;
536
+ drag.cancel();
534
537
  keyboardToggle = keyboard;
535
538
  const r = bar.getBoundingClientRect();
536
539
  const d = clampPos(dock ?? defaultDock());
@@ -568,7 +571,7 @@ function createMinimize(host) {
568
571
  function restore(keyboard = false) {
569
572
  if (mode !== "puck" || puckPos === null) return;
570
573
  closeFan();
571
- pdown = null;
574
+ drag.cancel();
572
575
  keyboardToggle = keyboard;
573
576
  dock = { ...puckPos };
574
577
  ui.puck.classList.add("pb-ghost");
@@ -650,42 +653,17 @@ function createMinimize(host) {
650
653
  if (path.includes(ui.fan) || path.includes(ui.puck)) return;
651
654
  closeFan();
652
655
  }
653
- function onPointerDown(e) {
654
- if (mode !== "puck" || e.button !== 0) return;
655
- try {
656
- ui.puck.setPointerCapture(e.pointerId);
657
- } catch {}
658
- if (puckPos === null) return;
659
- pdown = {
660
- px: e.clientX,
661
- py: e.clientY,
662
- ox: puckPos.x,
663
- oy: puckPos.y,
664
- lx: e.clientX,
665
- ly: e.clientY,
666
- moved: false
667
- };
668
- }
669
- function onPointerMove(e) {
670
- if (pdown === null) return;
671
- pdown.lx = e.clientX;
672
- pdown.ly = e.clientY;
673
- const dx = e.clientX - pdown.px;
674
- const dy = e.clientY - pdown.py;
675
- if (!pdown.moved) {
676
- if (mode !== "puck") {
677
- pdown = null;
678
- return;
679
- }
680
- if (Math.hypot(dx, dy) < DRAG_START) return;
681
- pdown.moved = true;
656
+ const drag = attachDrag(ui.puck, {
657
+ origin: () => mode === "puck" ? puckPos : null,
658
+ canStart: () => mode === "puck",
659
+ onStart(origin) {
682
660
  closeFan();
683
661
  mode = "drag";
684
662
  if (!host.reduced) {
685
663
  ui.puck.classList.add("pb-ghost");
686
664
  main.snap({
687
- x: pdown.ox,
688
- y: pdown.oy,
665
+ x: origin.x,
666
+ y: origin.y,
689
667
  w: PUCK,
690
668
  h: PUCK,
691
669
  r: PUCK / 2
@@ -693,140 +671,706 @@ function createMinimize(host) {
693
671
  render();
694
672
  showMorph();
695
673
  }
696
- }
697
- const next = {
698
- x: pdown.ox + dx,
699
- y: pdown.oy + dy
700
- };
701
- if (host.reduced) {
702
- const p = clampPos(next);
703
- placePuck(p.x, p.y);
704
- } else {
674
+ },
675
+ onMove(next) {
676
+ if (host.reduced) {
677
+ const p = clampPos(next);
678
+ placePuck(p.x, p.y);
679
+ } else {
680
+ main.to({
681
+ ...next,
682
+ w: PUCK,
683
+ h: PUCK,
684
+ r: PUCK / 2
685
+ }, FOLLOW_SPRING);
686
+ ensureLoop();
687
+ }
688
+ },
689
+ onEnd({ dragged, started, origin }) {
690
+ if (!dragged) {
691
+ if (started && mode === "drag") {
692
+ main.snap({
693
+ x: origin.x,
694
+ y: origin.y,
695
+ w: PUCK,
696
+ h: PUCK,
697
+ r: PUCK / 2
698
+ });
699
+ placePuck(origin.x, origin.y);
700
+ ui.puck.classList.remove("pb-ghost");
701
+ hideMorph();
702
+ mode = "puck";
703
+ }
704
+ if (!closeFan()) openFan();
705
+ return;
706
+ }
707
+ if (host.reduced) {
708
+ if (puckPos) {
709
+ const p = clampPos(puckPos);
710
+ placePuck(p.x, p.y);
711
+ dock = { ...p };
712
+ }
713
+ mode = "puck";
714
+ persist();
715
+ return;
716
+ }
717
+ const p = clampPos({
718
+ x: main.tgt.x,
719
+ y: main.tgt.y
720
+ });
705
721
  main.to({
706
- ...next,
722
+ ...p,
707
723
  w: PUCK,
708
724
  h: PUCK,
709
725
  r: PUCK / 2
710
- }, FOLLOW_SPRING);
726
+ }, MORPH_SPRING);
727
+ mode = "settle";
711
728
  ensureLoop();
712
729
  }
730
+ });
731
+ /** Keyboard/AT activation is a synthesized click (detail 0) with no pointer events. */
732
+ function onClick(e) {
733
+ if (e.detail !== 0) return;
734
+ if (!closeFan()) openFan();
713
735
  }
714
- function onPointerUp() {
715
- if (pdown === null) return;
716
- const total = Math.hypot(pdown.lx - pdown.px, pdown.ly - pdown.py);
717
- const wasDrag = pdown.moved && total >= TAP_MAX;
718
- const origin = {
719
- x: pdown.ox,
720
- y: pdown.oy
721
- };
722
- const startedDrag = pdown.moved;
723
- pdown = null;
724
- if (!wasDrag) {
725
- if (startedDrag && mode === "drag") {
726
- main.snap({
727
- x: origin.x,
728
- y: origin.y,
729
- w: PUCK,
730
- h: PUCK,
731
- r: PUCK / 2
732
- });
733
- placePuck(origin.x, origin.y);
736
+ function onResize() {
737
+ closeFan();
738
+ if (mode === "puck" && puckPos !== null) {
739
+ const p = clampPos(puckPos);
740
+ placePuck(p.x, p.y);
741
+ }
742
+ if (dock !== null) dock = clampPos(dock);
743
+ }
744
+ ui.puck.addEventListener("click", onClick);
745
+ ui.fan.addEventListener("click", onFanClick);
746
+ win.document.addEventListener("pointerdown", onDocPointerDown);
747
+ win.addEventListener("resize", onResize);
748
+ return {
749
+ minimized: () => mode !== "bar",
750
+ mode: () => mode,
751
+ minimize,
752
+ restore,
753
+ closeFan,
754
+ applyInitial() {
755
+ if (!loadMinimized()) return;
756
+ const apply = () => {
757
+ if (mode !== "bar") return;
758
+ const d = clampPos(dock ?? defaultDock());
759
+ bar.classList.add("pb-ghost");
760
+ placePuck(d.x, d.y);
734
761
  ui.puck.classList.remove("pb-ghost");
735
- hideMorph();
736
762
  mode = "puck";
737
- }
738
- if (!closeFan()) openFan();
739
- return;
763
+ host.onSettled(true, false);
764
+ };
765
+ if (host.reduced) apply();
766
+ else win.requestAnimationFrame(apply);
767
+ },
768
+ destroy() {
769
+ drag.destroy();
770
+ ui.puck.removeEventListener("click", onClick);
771
+ ui.fan.removeEventListener("click", onFanClick);
772
+ win.document.removeEventListener("pointerdown", onDocPointerDown);
773
+ win.removeEventListener("resize", onResize);
774
+ if (raf !== 0) win.cancelAnimationFrame(raf);
775
+ raf = 0;
776
+ win.clearTimeout(holdTimer);
777
+ win.clearTimeout(fadeTimer);
778
+ win.clearTimeout(hideTimer);
779
+ win.clearTimeout(fanTimer);
780
+ ui.fan.hidden = true;
781
+ ui.fan.classList.remove("on");
782
+ fanOpen = false;
740
783
  }
741
- if (host.reduced) {
742
- if (puckPos) {
743
- const p = clampPos(puckPos);
744
- placePuck(p.x, p.y);
745
- dock = { ...p };
746
- }
747
- mode = "puck";
748
- persist();
749
- return;
784
+ };
785
+ }
786
+ //#endregion
787
+ //#region src/targeting/dom.ts
788
+ /**
789
+ * Deepest element under (clientX, clientY) that the caller does not ignore, or null when there is
790
+ * nothing there but page chrome (html/body).
791
+ *
792
+ * Looks THROUGH our own overlay rather than giving up at it. The single-element form could not:
793
+ * the drag-aim grip sits exactly on the point being aimed at, so it is always the topmost thing
794
+ * under the crosshair, and every probe came back "nothing" the moment touch aiming existed.
795
+ */
796
+ function hitTest(doc, x, y, ignore) {
797
+ const stack = doc.elementsFromPoint?.(x, y) ?? [doc.elementFromPoint(x, y)];
798
+ for (const el of stack) {
799
+ if (!el || el === doc.body || el === doc.documentElement) return null;
800
+ if (!ignore(el)) return el;
801
+ }
802
+ return null;
803
+ }
804
+ /** CLASS-or-TAG display name with a sibling index when needed (prototype nodeName). */
805
+ function nodeName(el) {
806
+ const key = el.classList[0];
807
+ let name = (key ?? el.tagName).toUpperCase();
808
+ const parent = el.parentElement;
809
+ if (parent) {
810
+ const sibs = [...parent.children].filter((c) => c.classList[0] === key && c.tagName === el.tagName);
811
+ if (sibs.length > 1) name += ` ${sibs.indexOf(el) + 1}`;
812
+ }
813
+ return name;
814
+ }
815
+ /**
816
+ * Human label for a target: an explicit data-pb-el annotation wins; otherwise a
817
+ * CLASS/TAG ancestry chain of at most 3 parts joined with ›, terminating early
818
+ * at the first annotated ancestor.
819
+ */
820
+ function targetLabel(el) {
821
+ const own = el.getAttribute("data-pb-el");
822
+ if (own) return own;
823
+ const parts = [nodeName(el)];
824
+ const body = el.ownerDocument.body;
825
+ let node = el.parentElement;
826
+ while (node && node !== body && parts.length < 3) {
827
+ const anchor = node.getAttribute("data-pb-el");
828
+ if (anchor) {
829
+ parts.unshift(anchor);
830
+ break;
750
831
  }
751
- const p = clampPos({
752
- x: main.tgt.x,
753
- y: main.tgt.y
754
- });
755
- main.to({
756
- ...p,
757
- w: PUCK,
758
- h: PUCK,
759
- r: PUCK / 2
760
- }, MORPH_SPRING);
761
- mode = "settle";
762
- ensureLoop();
832
+ if (node.classList[0]) parts.unshift(nodeName(node));
833
+ node = node.parentElement;
763
834
  }
764
- /** Keyboard/AT activation is a synthesized click (detail 0) with no pointer events. */
765
- function onClick(e) {
766
- if (e.detail !== 0) return;
767
- if (!closeFan()) openFan();
835
+ return parts.join(" ");
836
+ }
837
+ const SAFE_ID = /^[A-Za-z][\w-]*$/;
838
+ /** Data attributes trusted as stable hooks, in priority order. */
839
+ const STABLE_DATA_ATTRS = [
840
+ "data-pb-anchor",
841
+ "data-pb-el",
842
+ "data-testid"
843
+ ];
844
+ function attrSegment(el, doc) {
845
+ for (const attr of STABLE_DATA_ATTRS) {
846
+ const value = el.getAttribute(attr);
847
+ if (value === null || value.includes("\"") || value.includes("\\")) continue;
848
+ const selector = `${el.tagName.toLowerCase()}[${attr}="${value}"]`;
849
+ if (doc.querySelectorAll(selector).length === 1) return selector;
850
+ }
851
+ return null;
852
+ }
853
+ function nthSegment(el) {
854
+ const tag = el.tagName.toLowerCase();
855
+ const parent = el.parentElement;
856
+ if (!parent) return tag;
857
+ const sameTag = [...parent.children].filter((c) => c.tagName === el.tagName);
858
+ return sameTag.length > 1 ? `${tag}:nth-of-type(${sameTag.indexOf(el) + 1})` : tag;
859
+ }
860
+ /**
861
+ * Stable CSS path for an element: ids > stable data attributes > an
862
+ * nth-of-type chain. Guaranteed round-trip: querySelector(buildSelector(el)) === el.
863
+ */
864
+ function buildSelector(el) {
865
+ const doc = el.ownerDocument;
866
+ const segments = [];
867
+ let node = el;
868
+ while (node && node !== doc.documentElement) {
869
+ const id = node.getAttribute("id");
870
+ if (id && SAFE_ID.test(id) && doc.querySelectorAll(`#${id}`).length === 1) {
871
+ segments.unshift(`#${id}`);
872
+ return segments.join(" > ");
873
+ }
874
+ const byAttr = attrSegment(node, doc);
875
+ if (byAttr) {
876
+ segments.unshift(byAttr);
877
+ return segments.join(" > ");
878
+ }
879
+ segments.unshift(nthSegment(node));
880
+ node = node.parentElement;
881
+ }
882
+ return segments.join(" > ");
883
+ }
884
+ //#endregion
885
+ //#region src/capture.ts
886
+ /** Curated computed-style subset — enough to reconstruct layout intent, tiny on the wire. */
887
+ const STYLE_KEYS = [
888
+ "display",
889
+ "position",
890
+ "font-size",
891
+ "color",
892
+ "background-color",
893
+ "margin",
894
+ "padding",
895
+ "overflow"
896
+ ];
897
+ const NEARBY_TEXT_MAX = 160;
898
+ function styleSubset(win, el) {
899
+ let cs;
900
+ try {
901
+ cs = win.getComputedStyle(el);
902
+ } catch {
903
+ return;
904
+ }
905
+ const out = {};
906
+ for (const key of STYLE_KEYS) {
907
+ const value = cs.getPropertyValue(key);
908
+ if (value !== "") out[key] = value;
909
+ }
910
+ return Object.keys(out).length > 0 ? out : void 0;
911
+ }
912
+ function ariaMap(el) {
913
+ const out = {};
914
+ for (const name of el.getAttributeNames()) if (name.startsWith("aria-")) out[name] = el.getAttribute(name) ?? "";
915
+ return Object.keys(out).length > 0 ? out : void 0;
916
+ }
917
+ function nearbyText(el) {
918
+ const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
919
+ return text === "" ? void 0 : text.slice(0, NEARBY_TEXT_MAX);
920
+ }
921
+ /** The user's selection, only when it intersects the captured element. */
922
+ function selectedText(win, el) {
923
+ try {
924
+ const sel = win.getSelection?.();
925
+ if (!sel || sel.isCollapsed || sel.rangeCount === 0) return void 0;
926
+ if (!sel.getRangeAt(0).intersectsNode(el)) return void 0;
927
+ const text = sel.toString().trim();
928
+ return text === "" ? void 0 : text;
929
+ } catch {
930
+ return;
931
+ }
932
+ }
933
+ /** `fixed` detected via ancestry: any ancestor with computed position: fixed. */
934
+ function isFixed(win, el) {
935
+ for (let node = el; node !== null; node = node.parentElement) try {
936
+ if (win.getComputedStyle(node).position === "fixed") return true;
937
+ } catch {
938
+ return false;
939
+ }
940
+ return false;
941
+ }
942
+ /** Beyond this an element is not a thing you pinned, it is a region. Too many to rewrite as a set. */
943
+ const MAX_RUNS = 40;
944
+ const MAX_RUN_LENGTH = 200;
945
+ /** Text that is not content: a script body or a stylesheet is not something to rewrite. */
946
+ const NON_CONTENT = /* @__PURE__ */ new Set([
947
+ "SCRIPT",
948
+ "STYLE",
949
+ "NOSCRIPT",
950
+ "TEMPLATE"
951
+ ]);
952
+ /**
953
+ * The element's text, split the way the browser stores it: one entry per run of characters.
954
+ *
955
+ * This walks TEXT NODES, not elements, and that distinction is the whole point — it makes no
956
+ * assumption about how a site is built. A heading is one run. A nav bar is one per link. A
957
+ * paragraph with a bold word in the middle is three, in reading order, including the halves either
958
+ * side of the bold. An earlier version keyed off "elements with no element children", which
959
+ * quietly lost the "Hello " in `<p>Hello <b>world</b></p>` — text a person can obviously see and
960
+ * would obviously expect to be able to change.
961
+ *
962
+ * `nearbyText` runs them all together, which is fine to read and useless to edit: it cannot tell
963
+ * an agent that "work approach people contact" is four separate places. This can.
964
+ */
965
+ function textRuns(el) {
966
+ const runs = [];
967
+ const walk = (node) => {
968
+ if (node.nodeType === 3) {
969
+ const text = (node.nodeValue ?? "").trim();
970
+ if (text.length > 0) runs.push(text.slice(0, MAX_RUN_LENGTH));
971
+ return runs.length <= MAX_RUNS;
972
+ }
973
+ if (node.nodeType !== 1 || NON_CONTENT.has(node.tagName)) return true;
974
+ for (const child of node.childNodes) if (!walk(child)) return false;
975
+ return true;
976
+ };
977
+ if (!walk(el) || runs.length === 0) return void 0;
978
+ return runs;
979
+ }
980
+ function buildContext(win, el) {
981
+ const context = {};
982
+ if (el.classList.length > 0) context.classes = [...el.classList];
983
+ const styles = styleSubset(win, el);
984
+ if (styles !== void 0) context.styles = styles;
985
+ const aria = ariaMap(el);
986
+ if (aria !== void 0) context.aria = aria;
987
+ const nearby = nearbyText(el);
988
+ if (nearby !== void 0) context.nearbyText = nearby;
989
+ const selected = selectedText(win, el);
990
+ if (selected !== void 0) context.selectedText = selected;
991
+ const runs = textRuns(el);
992
+ if (runs !== void 0) context.textRuns = runs;
993
+ return Object.keys(context).length > 0 ? context : void 0;
994
+ }
995
+ /** Fills PinInput.target/env from a chosen element (shapes come from the pin schema). */
996
+ function captureTarget(el, opts) {
997
+ const win = el.ownerDocument.defaultView;
998
+ const r = el.getBoundingClientRect();
999
+ const target = {
1000
+ url: win.location.href,
1001
+ selector: buildSelector(el),
1002
+ tag: el.tagName.toLowerCase(),
1003
+ rect: {
1004
+ x: r.left + win.scrollX,
1005
+ y: r.top + win.scrollY,
1006
+ width: r.width,
1007
+ height: r.height
1008
+ },
1009
+ fixed: isFixed(win, el)
1010
+ };
1011
+ if (opts?.anchor !== void 0) target.anchor = opts.anchor;
1012
+ if (opts?.at !== void 0 && r.width > 0 && r.height > 0) {
1013
+ const fx = (opts.at.x - (r.left + win.scrollX)) / r.width;
1014
+ const fy = (opts.at.y - (r.top + win.scrollY)) / r.height;
1015
+ if (fx >= 0 && fx <= 1 && fy >= 0 && fy <= 1) target.spot = {
1016
+ x: fx,
1017
+ y: fy
1018
+ };
1019
+ }
1020
+ const context = buildContext(win, el);
1021
+ if (context !== void 0) target.context = context;
1022
+ return {
1023
+ target,
1024
+ env: {
1025
+ viewport: {
1026
+ w: win.innerWidth,
1027
+ h: win.innerHeight,
1028
+ dpr: win.devicePixelRatio
1029
+ },
1030
+ browser: win.navigator.userAgent,
1031
+ os: win.navigator.platform || "unknown",
1032
+ colorScheme: win.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
1033
+ }
1034
+ };
1035
+ }
1036
+ //#endregion
1037
+ //#region src/ui/aim.ts
1038
+ /**
1039
+ * True when aiming has to be done by dragging rather than by pointing.
1040
+ *
1041
+ * Two independent reasons, either of which is sufficient. A coarse pointer means there is no
1042
+ * hover to follow at all — the mouse crosshair cannot work, whatever the screen size. The width
1043
+ * check is the design's own rule (720px) and catches the case a media query cannot: a device that
1044
+ * reports a fine pointer but is being used at phone width.
1045
+ */
1046
+ function needsDragAim(win) {
1047
+ return win.matchMedia?.("(pointer: coarse)").matches === true || win.innerWidth < 720;
1048
+ }
1049
+ /**
1050
+ * Where the reticle starts.
1051
+ *
1052
+ * Slightly above centre: the confirm bar owns the bottom of the screen, and a reticle that opens
1053
+ * underneath your own thumb is one you have to move before you can even see it.
1054
+ */
1055
+ function startPoint(win) {
1056
+ return {
1057
+ x: win.innerWidth / 2,
1058
+ y: win.innerHeight * .42
1059
+ };
1060
+ }
1061
+ const MARKUP = "<div class=\"h\"></div><div class=\"v\"></div><div class=\"grip\" aria-label=\"Pin position — arrow keys to aim\" tabindex=\"0\"><i></i></div><div class=\"bar\"><span class=\"lab\" role=\"status\" aria-live=\"polite\"></span><button type=\"button\" class=\"cancel\" data-aim=\"cancel\">CANCEL</button><button type=\"button\" class=\"ok\" data-aim=\"confirm\">PIN IT HERE</button></div>";
1062
+ function createAim(doc, handlers) {
1063
+ const win = doc.defaultView;
1064
+ const root = doc.createElement("div");
1065
+ root.className = "pb-aim";
1066
+ root.innerHTML = MARKUP;
1067
+ const h = root.querySelector(".h");
1068
+ const v = root.querySelector(".v");
1069
+ const grip = root.querySelector(".grip");
1070
+ const label = root.querySelector(".lab");
1071
+ const point = {
1072
+ x: 0,
1073
+ y: 0
1074
+ };
1075
+ /** Grab offset, so the reticle does not jump to your fingertip when you take hold of it. */
1076
+ let grab = null;
1077
+ function put(x, y) {
1078
+ point.x = Math.max(0, Math.min(win.innerWidth, x));
1079
+ point.y = Math.max(0, Math.min(win.innerHeight, y));
1080
+ h.style.top = `${point.y}px`;
1081
+ v.style.left = `${point.x}px`;
1082
+ grip.style.left = `${point.x}px`;
1083
+ grip.style.top = `${point.y}px`;
1084
+ }
1085
+ const onPointerMove = (e) => {
1086
+ if (grab === null) return;
1087
+ e.preventDefault();
1088
+ put(e.clientX + grab.dx, e.clientY + grab.dy);
1089
+ handlers.onAim(point.x, point.y);
1090
+ };
1091
+ const onPointerUp = () => {
1092
+ grab = null;
1093
+ };
1094
+ grip.addEventListener("pointerdown", (e) => {
1095
+ e.preventDefault();
1096
+ e.stopPropagation();
1097
+ grab = {
1098
+ dx: point.x - e.clientX,
1099
+ dy: point.y - e.clientY
1100
+ };
1101
+ grip.setPointerCapture?.(e.pointerId);
1102
+ });
1103
+ grip.addEventListener("keydown", (e) => {
1104
+ const step = e.shiftKey ? 20 : 2;
1105
+ const delta = {
1106
+ ArrowLeft: [-step, 0],
1107
+ ArrowRight: [step, 0],
1108
+ ArrowUp: [0, -step],
1109
+ ArrowDown: [0, step]
1110
+ }[e.key];
1111
+ if (!delta) return;
1112
+ e.preventDefault();
1113
+ put(point.x + delta[0], point.y + delta[1]);
1114
+ handlers.onAim(point.x, point.y);
1115
+ });
1116
+ root.addEventListener("click", (e) => {
1117
+ const action = e.target.closest?.("[data-aim]")?.getAttribute("data-aim");
1118
+ if (!action) return;
1119
+ e.preventDefault();
1120
+ e.stopPropagation();
1121
+ if (action === "confirm") handlers.onConfirm();
1122
+ else handlers.onCancel();
1123
+ });
1124
+ win.addEventListener("pointermove", onPointerMove, { passive: false });
1125
+ win.addEventListener("pointerup", onPointerUp);
1126
+ win.addEventListener("pointercancel", onPointerUp);
1127
+ return {
1128
+ root,
1129
+ point,
1130
+ show(x, y) {
1131
+ put(x, y);
1132
+ root.classList.add("on");
1133
+ },
1134
+ hide() {
1135
+ grab = null;
1136
+ root.classList.remove("on");
1137
+ },
1138
+ setLabel(text) {
1139
+ label.textContent = text;
1140
+ },
1141
+ destroy() {
1142
+ win.removeEventListener("pointermove", onPointerMove);
1143
+ win.removeEventListener("pointerup", onPointerUp);
1144
+ win.removeEventListener("pointercancel", onPointerUp);
1145
+ }
1146
+ };
1147
+ }
1148
+ //#endregion
1149
+ //#region src/ui/multimarks.ts
1150
+ const MARK_CLASS = "pb-multi-mark";
1151
+ /** Replace the mark set to mirror `targets`; entries with no rect draw nothing. */
1152
+ function renderMultiMarks(layer, targets, scroll = {
1153
+ x: 0,
1154
+ y: 0
1155
+ }) {
1156
+ for (const node of [...layer.querySelectorAll(`.${MARK_CLASS}`)]) node.remove();
1157
+ targets.forEach((target, i) => {
1158
+ const rect = target.rect;
1159
+ if (rect === void 0) return;
1160
+ const mark = layer.ownerDocument.createElement("div");
1161
+ mark.className = MARK_CLASS;
1162
+ mark.style.left = `${rect.x - scroll.x}px`;
1163
+ mark.style.top = `${rect.y - scroll.y}px`;
1164
+ mark.style.width = `${rect.width}px`;
1165
+ mark.style.height = `${rect.height}px`;
1166
+ mark.innerHTML = `<span>${i + 1}</span>`;
1167
+ layer.appendChild(mark);
1168
+ });
1169
+ }
1170
+ //#endregion
1171
+ //#region src/ui/reticle.ts
1172
+ function createReticle(doc) {
1173
+ const crosshair = doc.createElement("div");
1174
+ crosshair.className = "pb-reticle";
1175
+ crosshair.innerHTML = "<div class=\"h\"></div><div class=\"v\"></div><div class=\"box\"></div><div class=\"ro\"></div>";
1176
+ const h = crosshair.querySelector(".h");
1177
+ const v = crosshair.querySelector(".v");
1178
+ const box = crosshair.querySelector(".box");
1179
+ const readout = crosshair.querySelector(".ro");
1180
+ const outline = doc.createElement("div");
1181
+ outline.className = "pb-outline";
1182
+ outline.innerHTML = "<span class=\"lab\"></span>";
1183
+ const lab = outline.querySelector(".lab");
1184
+ function setOutlineRect(rect) {
1185
+ outline.style.left = `${rect.left - 5}px`;
1186
+ outline.style.top = `${rect.top - 5}px`;
1187
+ outline.style.width = `${rect.width + 10}px`;
1188
+ outline.style.height = `${rect.height + 10}px`;
1189
+ }
1190
+ return {
1191
+ crosshair,
1192
+ outline,
1193
+ move(pos) {
1194
+ h.style.top = `${pos.clientY}px`;
1195
+ v.style.left = `${pos.clientX}px`;
1196
+ box.style.left = `${pos.clientX}px`;
1197
+ box.style.top = `${pos.clientY}px`;
1198
+ readout.style.left = `${pos.clientX}px`;
1199
+ readout.style.top = `${pos.clientY}px`;
1200
+ readout.textContent = `${Math.round(pos.pageX)} × ${Math.round(pos.pageY)}`;
1201
+ },
1202
+ snap(rect, label) {
1203
+ if (!outline.classList.contains("on")) {
1204
+ outline.style.transition = "none";
1205
+ setOutlineRect(rect);
1206
+ outline.offsetWidth;
1207
+ outline.style.transition = "";
1208
+ } else setOutlineRect(rect);
1209
+ lab.textContent = label;
1210
+ outline.classList.add("on");
1211
+ },
1212
+ release() {
1213
+ outline.classList.remove("on");
1214
+ }
1215
+ };
1216
+ }
1217
+ //#endregion
1218
+ //#region src/placement.ts
1219
+ function createPlacement(deps) {
1220
+ const { win, host, store, pinsLayer } = deps;
1221
+ const doc = host.ownerDocument;
1222
+ const reticle = createReticle(doc);
1223
+ let aim = null;
1224
+ let hover = null;
1225
+ /** Shift+click accumulation while placing — extra loci for ONE pending pin. */
1226
+ let extraTargets = [];
1227
+ /** Pending viewport-refresh frame, 0 when none is queued. */
1228
+ let viewportFrame = 0;
1229
+ const placing = () => store.get().mode === "placing";
1230
+ /**
1231
+ * Work out what sits under a viewport point and highlight it. Shared by both ways of aiming —
1232
+ * following a mouse, and dragging the reticle — so the two can never disagree.
1233
+ */
1234
+ function probe(clientX, clientY) {
1235
+ const el = hitTest(doc, clientX, clientY, (hit) => hit === host);
1236
+ hover = el;
1237
+ if (el) reticle.snap(el.getBoundingClientRect(), targetLabel(el));
1238
+ else reticle.release();
1239
+ aim?.setLabel(el ? targetLabel(el) : "NOTHING UNDER THE PIN");
1240
+ }
1241
+ /**
1242
+ * Bring the drag-aim reticle up with placing mode, seeded mid-screen and already showing what
1243
+ * it is over — the first thing you see is a live target, not an empty crosshair.
1244
+ */
1245
+ function syncAim(on) {
1246
+ if (!aim) return;
1247
+ if (!on || !needsDragAim(win)) {
1248
+ aim.hide();
1249
+ return;
1250
+ }
1251
+ if (aim.root.classList.contains("on")) {
1252
+ if (aim.point.x <= win.innerWidth && aim.point.y <= win.innerHeight) return;
1253
+ aim.show(Math.min(aim.point.x, win.innerWidth), Math.min(aim.point.y, win.innerHeight));
1254
+ return;
1255
+ }
1256
+ const { x, y } = startPoint(win);
1257
+ aim.show(x, y);
1258
+ probe(x, y);
1259
+ }
1260
+ /** Commit the pin the drag-aim reticle is sitting on. */
1261
+ function confirmAim() {
1262
+ if (!aim) return;
1263
+ probe(aim.point.x, aim.point.y);
1264
+ const el = hover ?? doc.body;
1265
+ const at = {
1266
+ x: aim.point.x + win.scrollX,
1267
+ y: aim.point.y + win.scrollY
1268
+ };
1269
+ store.place({
1270
+ target: captureTarget(el, { at }),
1271
+ placedAt: at
1272
+ });
1273
+ reticle.release();
1274
+ }
1275
+ function drawMarks() {
1276
+ renderMultiMarks(pinsLayer, extraTargets, {
1277
+ x: win.scrollX,
1278
+ y: win.scrollY
1279
+ });
1280
+ }
1281
+ function clearExtraTargets() {
1282
+ if (extraTargets.length === 0) return;
1283
+ extraTargets = [];
1284
+ drawMarks();
1285
+ }
1286
+ /** Placement click: capture the hovered target (or body) into a client-only draft. */
1287
+ function placeDraft(e) {
1288
+ e.preventDefault();
1289
+ e.stopPropagation();
1290
+ const capture = captureTarget(hover ?? doc.body, { at: {
1291
+ x: e.pageX,
1292
+ y: e.pageY
1293
+ } });
1294
+ if (extraTargets.length > 0) capture.target.targets = extraTargets;
1295
+ clearExtraTargets();
1296
+ store.place({
1297
+ target: capture,
1298
+ placedAt: {
1299
+ x: e.pageX,
1300
+ y: e.pageY
1301
+ }
1302
+ });
1303
+ reticle.release();
768
1304
  }
769
- function onResize() {
770
- closeFan();
771
- if (mode === "puck" && puckPos !== null) {
772
- const p = clampPos(puckPos);
773
- placePuck(p.x, p.y);
774
- }
775
- if (dock !== null) dock = clampPos(dock);
1305
+ /** Shift+click while placing: capture WITHOUT committing; a numbered dashed outline is the receipt. */
1306
+ function accumulateTarget(e) {
1307
+ e.preventDefault();
1308
+ e.stopPropagation();
1309
+ extraTargets = [...extraTargets, captureTarget(hover ?? doc.body).target];
1310
+ drawMarks();
1311
+ }
1312
+ /**
1313
+ * Keep the drag-aim reticle honest while the viewport moves under it — one probe per frame,
1314
+ * not per event: momentum scrolling on a phone dispatches faster than frames.
1315
+ */
1316
+ const onViewportChange = () => {
1317
+ if (!placing() || viewportFrame !== 0) return;
1318
+ viewportFrame = win.requestAnimationFrame(() => {
1319
+ viewportFrame = 0;
1320
+ if (!placing()) return;
1321
+ syncAim(true);
1322
+ if (aim?.root.classList.contains("on") === true) probe(aim.point.x, aim.point.y);
1323
+ });
1324
+ };
1325
+ const onMouseMove = (e) => {
1326
+ if (!placing()) return;
1327
+ reticle.move(e);
1328
+ probe(e.clientX, e.clientY);
1329
+ };
1330
+ function mountAim(shadow) {
1331
+ shadow.querySelector(".pb-aim")?.remove();
1332
+ aim = createAim(doc, {
1333
+ onAim: probe,
1334
+ onConfirm: confirmAim,
1335
+ onCancel: deps.onCancel
1336
+ });
1337
+ shadow.appendChild(aim.root);
776
1338
  }
777
- ui.puck.addEventListener("pointerdown", onPointerDown);
778
- ui.puck.addEventListener("pointermove", onPointerMove);
779
- ui.puck.addEventListener("pointerup", onPointerUp);
780
- ui.puck.addEventListener("pointercancel", onPointerUp);
781
- ui.puck.addEventListener("click", onClick);
782
- ui.fan.addEventListener("click", onFanClick);
783
- win.document.addEventListener("pointerdown", onDocPointerDown);
784
- win.addEventListener("resize", onResize);
785
1339
  return {
786
- minimized: () => mode !== "bar",
787
- mode: () => mode,
788
- minimize,
789
- restore,
790
- closeFan,
791
- applyInitial() {
792
- if (!loadMinimized()) return;
793
- const apply = () => {
794
- if (mode !== "bar") return;
795
- const d = clampPos(dock ?? defaultDock());
796
- bar.classList.add("pb-ghost");
797
- placePuck(d.x, d.y);
798
- ui.puck.classList.remove("pb-ghost");
799
- mode = "puck";
800
- host.onSettled(true, false);
801
- };
802
- if (host.reduced) apply();
803
- else win.requestAnimationFrame(apply);
1340
+ outline: reticle.outline,
1341
+ crosshair: reticle.crosshair,
1342
+ connect(shadow) {
1343
+ if (aim === null) mountAim(shadow);
1344
+ doc.addEventListener("mousemove", onMouseMove);
1345
+ win.addEventListener("scroll", onViewportChange, { passive: true });
1346
+ win.addEventListener("resize", onViewportChange);
804
1347
  },
805
- destroy() {
806
- ui.puck.removeEventListener("pointerdown", onPointerDown);
807
- ui.puck.removeEventListener("pointermove", onPointerMove);
808
- ui.puck.removeEventListener("pointerup", onPointerUp);
809
- ui.puck.removeEventListener("pointercancel", onPointerUp);
810
- ui.puck.removeEventListener("click", onClick);
811
- ui.fan.removeEventListener("click", onFanClick);
812
- win.document.removeEventListener("pointerdown", onDocPointerDown);
813
- win.removeEventListener("resize", onResize);
814
- if (raf !== 0) win.cancelAnimationFrame(raf);
815
- raf = 0;
816
- win.clearTimeout(holdTimer);
817
- win.clearTimeout(fadeTimer);
818
- win.clearTimeout(hideTimer);
819
- win.clearTimeout(fanTimer);
820
- ui.fan.hidden = true;
821
- ui.fan.classList.remove("on");
822
- fanOpen = false;
1348
+ disconnect() {
1349
+ doc.removeEventListener("mousemove", onMouseMove);
1350
+ win.removeEventListener("scroll", onViewportChange);
1351
+ win.removeEventListener("resize", onViewportChange);
1352
+ if (viewportFrame !== 0) win.cancelAnimationFrame(viewportFrame);
1353
+ viewportFrame = 0;
1354
+ aim?.destroy();
1355
+ aim = null;
1356
+ },
1357
+ render(on) {
1358
+ if (!on) clearExtraTargets();
1359
+ if (!on) reticle.release();
1360
+ if (on && extraTargets.length > 0) drawMarks();
1361
+ syncAim(on);
1362
+ },
1363
+ handleClick(e) {
1364
+ if (needsDragAim(win)) return;
1365
+ if (e.shiftKey) accumulateTarget(e);
1366
+ else placeDraft(e);
823
1367
  }
824
1368
  };
825
1369
  }
826
1370
  //#endregion
827
1371
  //#region src/screenshot.ts
828
- const WEBP_QUALITY = .7;
829
- const PLACEHOLDER_MAX = 32;
1372
+ const WEBP_QUALITY$1 = .7;
1373
+ const PLACEHOLDER_MAX$1 = 32;
830
1374
  /** Element rect clamped to the viewport (CSS px); null when nothing is visible. */
831
1375
  function visibleCropRect(el) {
832
1376
  const win = el.ownerDocument.defaultView;
@@ -907,12 +1451,12 @@ async function encode(bmp) {
907
1451
  const image = {
908
1452
  blob: await canvas.convertToBlob({
909
1453
  type: "image/webp",
910
- quality: WEBP_QUALITY
1454
+ quality: WEBP_QUALITY$1
911
1455
  }),
912
1456
  width: bmp.width,
913
1457
  height: bmp.height
914
1458
  };
915
- const scale = PLACEHOLDER_MAX / Math.max(bmp.width, bmp.height);
1459
+ const scale = PLACEHOLDER_MAX$1 / Math.max(bmp.width, bmp.height);
916
1460
  const tw = Math.max(1, Math.round(bmp.width * Math.min(scale, 1)));
917
1461
  const th = Math.max(1, Math.round(bmp.height * Math.min(scale, 1)));
918
1462
  const thumb = new OffscreenCanvas(tw, th);
@@ -971,7 +1515,137 @@ async function uploadAttachment(endpoint, token, img) {
971
1515
  return body.data.attachment;
972
1516
  }
973
1517
  //#endregion
974
- //#region src/state.ts
1518
+ //#region src/screenshot-dom.ts
1519
+ const MAX_NODES = 1500;
1520
+ const MAX_EDGE = 1600;
1521
+ const WEBP_QUALITY = .7;
1522
+ const PLACEHOLDER_MAX = 32;
1523
+ /** Elements SVG-as-image cannot render (external resources) — replaced by a same-size box. */
1524
+ const REPLACED = /* @__PURE__ */ new Set([
1525
+ "IMG",
1526
+ "VIDEO",
1527
+ "CANVAS",
1528
+ "IFRAME",
1529
+ "OBJECT",
1530
+ "EMBED",
1531
+ "PICTURE"
1532
+ ]);
1533
+ function realmOf(el) {
1534
+ return el.ownerDocument.defaultView;
1535
+ }
1536
+ /** Copy every computed property onto the clone so it renders without the page's stylesheets. */
1537
+ function inlineStyles(win, source, clone) {
1538
+ const cs = win.getComputedStyle(source);
1539
+ const style = clone.style;
1540
+ if (style === void 0) return;
1541
+ let css = "";
1542
+ for (let i = 0; i < cs.length; i += 1) {
1543
+ const prop = cs[i];
1544
+ if (prop === void 0) continue;
1545
+ css += `${prop}:${cs.getPropertyValue(prop)};`;
1546
+ }
1547
+ style.cssText = css;
1548
+ }
1549
+ /**
1550
+ * A same-size neutral box in place of an element the snapshot cannot draw. Keeps the layout
1551
+ * honest (the agent sees where the image sits) without a tainted or empty canvas.
1552
+ */
1553
+ function placeholderFor(doc, source) {
1554
+ const r = source.getBoundingClientRect();
1555
+ const box = doc.createElement("span");
1556
+ box.style.cssText = `display:inline-block;width:${r.width}px;height:${r.height}px;background:rgba(127,127,127,.25);border-radius:4px;vertical-align:top;`;
1557
+ return box;
1558
+ }
1559
+ /**
1560
+ * Deep-clone `root` with computed styles inlined and un-renderable elements replaced.
1561
+ * Returns null when the subtree is too large to snapshot responsively.
1562
+ */
1563
+ function cloneForSnapshot(root) {
1564
+ const doc = root.ownerDocument;
1565
+ const win = doc.defaultView;
1566
+ if (win === null) return null;
1567
+ const sources = [root, ...root.querySelectorAll("*")];
1568
+ if (sources.length > MAX_NODES) return null;
1569
+ const clone = root.cloneNode(true);
1570
+ const clones = [clone, ...clone.querySelectorAll("*")];
1571
+ for (let i = 0; i < sources.length; i += 1) {
1572
+ const source = sources[i];
1573
+ const target = clones[i];
1574
+ if (target === void 0) break;
1575
+ const keepDataImage = source.tagName === "IMG" && (source.getAttribute("src") ?? "").startsWith("data:");
1576
+ if (REPLACED.has(source.tagName) && !keepDataImage) {
1577
+ target.replaceWith(placeholderFor(doc, source));
1578
+ continue;
1579
+ }
1580
+ inlineStyles(win, source, target);
1581
+ }
1582
+ for (const script of clone.querySelectorAll("script")) script.remove();
1583
+ return clone;
1584
+ }
1585
+ /** The SVG document that renders `clone` at the element's size. */
1586
+ function svgFor(clone, width, height) {
1587
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${new ((realmOf(clone)?.XMLSerializer) ?? XMLSerializer)().serializeToString(clone)}</div></foreignObject></svg>`;
1588
+ }
1589
+ function loadImage(ImageCtor, url) {
1590
+ return new Promise((resolve, reject) => {
1591
+ const img = new ImageCtor();
1592
+ img.onload = () => resolve(img);
1593
+ img.onerror = () => reject(/* @__PURE__ */ new Error("snapshot image failed to load"));
1594
+ img.src = url;
1595
+ });
1596
+ }
1597
+ function toBlob(canvas, type, quality) {
1598
+ return new Promise((resolve, reject) => {
1599
+ canvas.toBlob((b) => b === null ? reject(/* @__PURE__ */ new Error("toBlob")) : resolve(b), type, quality);
1600
+ });
1601
+ }
1602
+ async function rasterize(win, img, width, height) {
1603
+ const scale = Math.min(win.devicePixelRatio || 1, 2, MAX_EDGE / Math.max(width, height));
1604
+ const canvas = win.document.createElement("canvas");
1605
+ canvas.width = Math.max(1, Math.round(width * scale));
1606
+ canvas.height = Math.max(1, Math.round(height * scale));
1607
+ const ctx = canvas.getContext("2d");
1608
+ if (ctx === null) throw new Error("no 2d context");
1609
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
1610
+ const image = {
1611
+ blob: await toBlob(canvas, "image/webp", WEBP_QUALITY),
1612
+ width: canvas.width,
1613
+ height: canvas.height
1614
+ };
1615
+ const t = PLACEHOLDER_MAX / Math.max(canvas.width, canvas.height);
1616
+ const thumb = win.document.createElement("canvas");
1617
+ thumb.width = Math.max(1, Math.round(canvas.width * Math.min(t, 1)));
1618
+ thumb.height = Math.max(1, Math.round(canvas.height * Math.min(t, 1)));
1619
+ thumb.getContext("2d")?.drawImage(canvas, 0, 0, thumb.width, thumb.height);
1620
+ image.placeholder = `data:image/webp;base64,${toBase64(await (await toBlob(thumb, "image/webp", .5)).arrayBuffer())}`;
1621
+ return image;
1622
+ }
1623
+ /**
1624
+ * Snapshot `el` without any permission prompt. Resolves null whenever the environment cannot
1625
+ * (no canvas/Image, zero-size element, subtree too large, a tainted canvas) — never throws.
1626
+ */
1627
+ async function captureElementDom(el) {
1628
+ const win = realmOf(el);
1629
+ if (win === null || typeof win.Image !== "function" || typeof win.XMLSerializer !== "function") return null;
1630
+ const ImageCtor = win.Image;
1631
+ const r = el.getBoundingClientRect();
1632
+ const width = Math.ceil(r.width);
1633
+ const height = Math.ceil(r.height);
1634
+ if (width < 1 || height < 1) return null;
1635
+ const clone = cloneForSnapshot(el);
1636
+ if (clone === null) return null;
1637
+ const svg = svgFor(clone, width, height);
1638
+ const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml;charset=utf-8" }));
1639
+ try {
1640
+ return await rasterize(win, await loadImage(ImageCtor, url), width, height);
1641
+ } catch {
1642
+ return null;
1643
+ } finally {
1644
+ URL.revokeObjectURL(url);
1645
+ }
1646
+ }
1647
+ /** A session seen more recently than this counts as an agent that is listening. */
1648
+ const AGENT_LIVE_MS = 9e5;
975
1649
  function initialState() {
976
1650
  return {
977
1651
  pins: [],
@@ -983,7 +1657,10 @@ function initialState() {
983
1657
  connection: "connecting",
984
1658
  queuedIds: /* @__PURE__ */ new Set(),
985
1659
  minimized: false,
986
- pinsHidden: false
1660
+ pinsHidden: false,
1661
+ clock: 0,
1662
+ agentLive: null,
1663
+ captureMode: "dom"
987
1664
  };
988
1665
  }
989
1666
  function createStore() {
@@ -1059,20 +1736,60 @@ function applyHubEvent(store, event) {
1059
1736
  if (typeof pin?.id !== "string") return;
1060
1737
  upsertPin(store, pin);
1061
1738
  }
1739
+ /** Unknown clock, unknown agent — the pre-clock derivation. */
1740
+ const NO_VIEW = {
1741
+ clock: 0,
1742
+ agentLive: null
1743
+ };
1744
+ /** When the human last spoke on this pin: the last message if it is theirs, else the pin itself. */
1745
+ function lastHumanAt(pin, thread) {
1746
+ const last = thread[thread.length - 1];
1747
+ return Date.parse(last === void 0 ? pin.createdAt : last.at);
1748
+ }
1749
+ /**
1750
+ * How long the agent has owed a reply, as a state the card can draw.
1751
+ *
1752
+ * Dogfood: a THINKING row spun for two weeks on a pin nobody ever answered, because the row
1753
+ * meant only "the last word is yours". Now that means thinking for 90 s, then a quiet WAITING
1754
+ * FOR AGENT, then NO RESPONSE after ten minutes — or after those 90 s when the hub reports no
1755
+ * agent listening at all. "none" for anything not owed a reply. A 0 clock never goes stale.
1756
+ */
1757
+ function pendingKind(pin, thread, view = NO_VIEW) {
1758
+ if (pin.status !== "open" || pin.kind === "comment") return "none";
1759
+ const last = thread[thread.length - 1];
1760
+ if (last !== void 0 && last.role !== "human") return "none";
1761
+ if (view.clock === 0) return "thinking";
1762
+ const age = view.clock - lastHumanAt(pin, thread);
1763
+ if (age < 9e4) return "thinking";
1764
+ if (view.agentLive === false || age >= 6e5) return "stale";
1765
+ return "waiting";
1766
+ }
1062
1767
  /**
1063
1768
  * Wire-status → UI-status mapping:
1064
1769
  * resolved + no verification ⇒ "verify" (accept/reopen prompt);
1065
1770
  * resolved + verification ⇒ "resolved";
1771
+ * open comment pin ⇒ "note" (nobody owes a reply — never "waiting");
1772
+ * open + reply owed too long (pendingKind "stale") ⇒ "stale";
1066
1773
  * open + empty thread or last message human ⇒ "waiting";
1067
1774
  * open + last message agent|mirror ⇒ "replied".
1068
1775
  * The prototype's WORKING/APPLIED chips need an event vocabulary the hub does not emit — excluded here.
1069
1776
  */
1070
- function deriveUiStatus(pin, thread) {
1777
+ function deriveUiStatus(pin, thread, view = NO_VIEW) {
1071
1778
  if (pin.status === "resolved") return pin.verification ? "resolved" : "verify";
1072
- const last = thread[thread.length - 1];
1073
- if (!last || last.role === "human") return "waiting";
1779
+ if (pin.kind === "comment") return "note";
1780
+ const pending = pendingKind(pin, thread, view);
1781
+ if (pending === "stale") return "stale";
1782
+ if (pending !== "none") return "waiting";
1074
1783
  return "replied";
1075
1784
  }
1785
+ /** Is anyone listening? A session not ended and seen within AGENT_LIVE_MS. */
1786
+ function agentIsLive(sessions, now) {
1787
+ return sessions.some((s) => s.endedAt === void 0 && now - Date.parse(s.lastSeenAt) < AGENT_LIVE_MS);
1788
+ }
1789
+ /** Open pins that ask something of someone — comment pins are remarks, so the badges skip them. */
1790
+ function openTaskCount(pins) {
1791
+ return pins.filter((p) => p.status !== "resolved" && p.kind !== "comment").length;
1792
+ }
1076
1793
  //#endregion
1077
1794
  //#region src/transport/mirror.ts
1078
1795
  function randomBase36(length) {
@@ -1230,6 +1947,10 @@ var RestClient = class {
1230
1947
  listPins() {
1231
1948
  return this.#request("GET", "/pins");
1232
1949
  }
1950
+ /** Agent sessions the hub knows, most recently seen first (routes-sessions.ts). */
1951
+ listSessions() {
1952
+ return this.#request("GET", "/sessions");
1953
+ }
1233
1954
  createPin(input) {
1234
1955
  return this.#request("POST", "/pins", input);
1235
1956
  }
@@ -1308,6 +2029,8 @@ var HubTransport = class {
1308
2029
  #timer = null;
1309
2030
  /** One flush at a time — reconnect and the live write path both drain the outbox. */
1310
2031
  #flushing = false;
2032
+ /** Bumped per `GET /sessions`; only the newest request's snapshot reaches `onSessions`. */
2033
+ #sessionsGen = 0;
1311
2034
  constructor(opts) {
1312
2035
  this.#opts = opts;
1313
2036
  const storage = opts.storage ?? globalThis.localStorage ?? memoryStorage();
@@ -1513,6 +2236,7 @@ var HubTransport = class {
1513
2236
  }
1514
2237
  /** Refresh listPins (hub wins on status) → flush the outbox (client wins on new pins) → persist the fresh mirror. */
1515
2238
  async #reconcile() {
2239
+ this.#refreshSessions();
1516
2240
  try {
1517
2241
  const pins = await this.#snapshotPins();
1518
2242
  if (pins !== null) this.#opts.onPins?.(pins);
@@ -1539,6 +2263,18 @@ var HubTransport = class {
1539
2263
  }
1540
2264
  return null;
1541
2265
  }
2266
+ /** Best-effort: a hub without the route (or unreachable) simply leaves liveness unknown.
2267
+ * Reconnects can overlap; a slow older GET must not overwrite a newer snapshot, so only
2268
+ * the latest request applies. */
2269
+ async #refreshSessions() {
2270
+ if (this.#opts.onSessions === void 0) return;
2271
+ this.#sessionsGen += 1;
2272
+ const gen = this.#sessionsGen;
2273
+ try {
2274
+ const sessions = await this.#rest.listSessions();
2275
+ if (gen === this.#sessionsGen) this.#opts.onSessions(sessions);
2276
+ } catch {}
2277
+ }
1542
2278
  async #flushOutbox() {
1543
2279
  if (this.#flushing) return [];
1544
2280
  this.#flushing = true;
@@ -1561,155 +2297,132 @@ var HubTransport = class {
1561
2297
  }
1562
2298
  };
1563
2299
  //#endregion
1564
- //#region src/ui/aim.ts
1565
- /**
1566
- * True when aiming has to be done by dragging rather than by pointing.
1567
- *
1568
- * Two independent reasons, either of which is sufficient. A coarse pointer means there is no
1569
- * hover to follow at all — the mouse crosshair cannot work, whatever the screen size. The width
1570
- * check is the design's own rule (720px) and catches the case a media query cannot: a device that
1571
- * reports a fine pointer but is being used at phone width.
1572
- */
1573
- function needsDragAim(win) {
1574
- return win.matchMedia?.("(pointer: coarse)").matches === true || win.innerWidth < 720;
1575
- }
1576
- /**
1577
- * Where the reticle starts.
1578
- *
1579
- * Slightly above centre: the confirm bar owns the bottom of the screen, and a reticle that opens
1580
- * underneath your own thumb is one you have to move before you can even see it.
1581
- */
1582
- function startPoint(win) {
1583
- return {
1584
- x: win.innerWidth / 2,
1585
- y: win.innerHeight * .42
1586
- };
1587
- }
1588
- const MARKUP = "<div class=\"h\"></div><div class=\"v\"></div><div class=\"grip\" aria-label=\"Pin position — arrow keys to aim\" tabindex=\"0\"><i></i></div><div class=\"bar\"><span class=\"lab\" role=\"status\" aria-live=\"polite\"></span><button type=\"button\" class=\"cancel\" data-aim=\"cancel\">CANCEL</button><button type=\"button\" class=\"ok\" data-aim=\"confirm\">PIN IT HERE</button></div>";
1589
- function createAim(doc, handlers) {
1590
- const win = doc.defaultView;
1591
- const root = doc.createElement("div");
1592
- root.className = "pb-aim";
1593
- root.innerHTML = MARKUP;
1594
- const h = root.querySelector(".h");
1595
- const v = root.querySelector(".v");
1596
- const grip = root.querySelector(".grip");
1597
- const label = root.querySelector(".lab");
1598
- const point = {
1599
- x: 0,
1600
- y: 0
1601
- };
1602
- /** Grab offset, so the reticle does not jump to your fingertip when you take hold of it. */
1603
- let grab = null;
1604
- function put(x, y) {
1605
- point.x = Math.max(0, Math.min(win.innerWidth, x));
1606
- point.y = Math.max(0, Math.min(win.innerHeight, y));
1607
- h.style.top = `${point.y}px`;
1608
- v.style.left = `${point.x}px`;
1609
- grip.style.left = `${point.x}px`;
1610
- grip.style.top = `${point.y}px`;
1611
- }
1612
- const onPointerMove = (e) => {
1613
- if (grab === null) return;
1614
- e.preventDefault();
1615
- put(e.clientX + grab.dx, e.clientY + grab.dy);
1616
- handlers.onAim(point.x, point.y);
1617
- };
1618
- const onPointerUp = () => {
1619
- grab = null;
1620
- };
1621
- grip.addEventListener("pointerdown", (e) => {
1622
- e.preventDefault();
1623
- e.stopPropagation();
1624
- grab = {
1625
- dx: point.x - e.clientX,
1626
- dy: point.y - e.clientY
1627
- };
1628
- grip.setPointerCapture?.(e.pointerId);
1629
- });
1630
- grip.addEventListener("keydown", (e) => {
1631
- const step = e.shiftKey ? 20 : 2;
1632
- const delta = {
1633
- ArrowLeft: [-step, 0],
1634
- ArrowRight: [step, 0],
1635
- ArrowUp: [0, -step],
1636
- ArrowDown: [0, step]
1637
- }[e.key];
1638
- if (!delta) return;
1639
- e.preventDefault();
1640
- put(point.x + delta[0], point.y + delta[1]);
1641
- handlers.onAim(point.x, point.y);
1642
- });
1643
- root.addEventListener("click", (e) => {
1644
- const action = e.target.closest?.("[data-aim]")?.getAttribute("data-aim");
1645
- if (!action) return;
1646
- e.preventDefault();
1647
- e.stopPropagation();
1648
- if (action === "confirm") handlers.onConfirm();
1649
- else handlers.onCancel();
1650
- });
1651
- win.addEventListener("pointermove", onPointerMove, { passive: false });
1652
- win.addEventListener("pointerup", onPointerUp);
1653
- win.addEventListener("pointercancel", onPointerUp);
1654
- return {
1655
- root,
1656
- point,
1657
- show(x, y) {
1658
- put(x, y);
1659
- root.classList.add("on");
1660
- },
1661
- hide() {
1662
- grab = null;
1663
- root.classList.remove("on");
1664
- },
1665
- setLabel(text) {
1666
- label.textContent = text;
1667
- },
1668
- destroy() {
1669
- win.removeEventListener("pointermove", onPointerMove);
1670
- win.removeEventListener("pointerup", onPointerUp);
1671
- win.removeEventListener("pointercancel", onPointerUp);
1672
- }
1673
- };
1674
- }
1675
- //#endregion
1676
2300
  //#region src/ui/bar.ts
1677
- const PIN_ICON = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"3\" y=\"1.5\" width=\"10\" height=\"6.5\" rx=\"1\"/><path d=\"M8 8v6.5\"/></svg>";
1678
- const INBOX_ICON = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M1.8 8.5h3.4l1 2h3.6l1-2h3.4\"/><path d=\"M2.6 3.2h10.8l1.2 5.3v4a1 1 0 01-1 1H2.4a1 1 0 01-1-1v-4z\"/></svg>";
1679
- const THEME_ICON = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M8 2a4 4 0 0 0 6 6 6 6 0 1 1-6-6z\"/></svg>";
1680
- const COPY_ICON$1 = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1\"/><path d=\"M10.5 3.5v-1a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h1\"/></svg>";
1681
2301
  const IDENT_ICON = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"var(--pb-amber)\" stroke-width=\"1.4\"><rect x=\"2.5\" y=\"1.5\" width=\"11\" height=\"7\" rx=\"1\"/><path d=\"M8 8.5v6\"/><circle cx=\"8\" cy=\"14.6\" r=\".9\" fill=\"var(--pb-amber)\" stroke=\"none\"/></svg>";
1682
- const MIN_ICON = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M6.5 2.5v4h-4\"/><path d=\"M9.5 13.5v-4h4\"/></svg>";
2302
+ const GRIP_ICON = "<svg width=\"6\" height=\"14\" viewBox=\"0 0 6 14\" fill=\"currentColor\"><circle cx=\"1.5\" cy=\"2\" r=\"1.1\"/><circle cx=\"4.5\" cy=\"2\" r=\"1.1\"/><circle cx=\"1.5\" cy=\"7\" r=\"1.1\"/><circle cx=\"4.5\" cy=\"7\" r=\"1.1\"/><circle cx=\"1.5\" cy=\"12\" r=\"1.1\"/><circle cx=\"4.5\" cy=\"12\" r=\"1.1\"/></svg>";
1683
2303
  const CONNECTION_LABEL = {
1684
2304
  connecting: "PINBOX",
1685
2305
  live: "PINBOX",
1686
2306
  offline: "PINBOX · OFFLINE",
1687
2307
  incompatible: "PINBOX · UPDATE NEEDED"
1688
2308
  };
2309
+ /** `data-ref` per action: the element focuses "min" after a keyboard restore. */
2310
+ function refOf(a) {
2311
+ return a.id === "minimize" ? "min" : a.id;
2312
+ }
2313
+ function buttonHtml(a) {
2314
+ const bar = a.bar;
2315
+ const glyph = a.glyph === void 0 ? "" : icon(a.glyph, 14);
2316
+ const body = bar.count ? `${glyph}<span data-ref="count">0</span>` : `${glyph}${bar.text ?? ""}`;
2317
+ const square = bar.text === void 0 && !bar.count;
2318
+ const aria = bar.ariaLabel === void 0 ? "" : ` aria-label="${bar.ariaLabel}"`;
2319
+ return `<button type="button" class="pb-tb${square ? " sq" : ""}" data-ref="${refOf(a)}" title="${titleOf(a)}"${aria}>${a.glyph === void 0 ? a.key ?? "" : body}</button>`;
2320
+ }
1689
2321
  function createBar(doc, on) {
1690
2322
  const root = doc.createElement("div");
1691
2323
  root.className = "pb-bar";
1692
- root.innerHTML = `<div class="armed-ring"></div><div class="ident">${IDENT_ICON}<span class="bl" data-ref="label">PINBOX</span></div><div class="div"></div><button type="button" class="pb-tb" data-ref="pin" title="Pin (P)">${PIN_ICON}PIN</button><button type="button" class="pb-tb" data-ref="inbox" title="Inbox (I)">${INBOX_ICON}<span data-ref="count">0</span></button><div class="div" style="margin:0 3px"></div><button type="button" class="pb-tb sq" data-ref="copy" title="Copy open pins (C)">${COPY_ICON$1}</button><button type="button" class="pb-tb sq" data-ref="theme" title="Theme (D)">${THEME_ICON}</button><button type="button" class="pb-tb sq" data-ref="help" title="Shortcuts (?)">?</button><button type="button" class="pb-tb sq" data-ref="min" title="Minimize (M)" aria-label="Minimize toolbar">${MIN_ICON}</button>`;
2324
+ const wide = ACTIONS.filter((a) => a.bar !== void 0 && (a.bar.text !== void 0 || a.bar.count));
2325
+ const squares = ACTIONS.filter((a) => a.bar !== void 0 && !wide.includes(a));
2326
+ root.innerHTML = `<div class="armed-ring"></div><div class="grip" data-ref="grip" title="Drag to move · double-click to reset">${GRIP_ICON}</div><div class="ident">${IDENT_ICON}<span class="bl" data-ref="label">PINBOX</span></div><div class="div"></div>` + wide.map(buttonHtml).join("") + "<div class=\"div\" style=\"margin:0 3px\"></div>" + squares.map(buttonHtml).join("");
1693
2327
  const ref = (name) => root.querySelector(`[data-ref="${name}"]`);
1694
2328
  const label = ref("label");
1695
2329
  const pinBtn = ref("pin");
1696
2330
  const inboxBtn = ref("inbox");
2331
+ const hideBtn = ref("hide");
2332
+ const captureBtn = ref("capture");
1697
2333
  const count = ref("count");
1698
- pinBtn.addEventListener("click", on.onPin);
1699
- inboxBtn.addEventListener("click", on.onInbox);
1700
- ref("copy").addEventListener("click", on.onCopy);
1701
- ref("theme").addEventListener("click", on.onTheme);
1702
- ref("help").addEventListener("click", on.onHelp);
1703
- ref("min").addEventListener("click", (e) => on.onMinimize(e.detail === 0));
2334
+ for (const a of [...wide, ...squares]) ref(refOf(a)).addEventListener("click", (e) => on.onAction(a.id, e.detail === 0));
2335
+ /** Last-rendered hide state; the glyph is swapped only on change. */
2336
+ let hideShown = null;
2337
+ return {
2338
+ root,
2339
+ grip: ref("grip"),
2340
+ update(state) {
2341
+ const text = state.mode === "placing" ? "CLICK TO PIN" : CONNECTION_LABEL[state.connection];
2342
+ if (label.textContent !== text) label.textContent = text;
2343
+ pinBtn.classList.toggle("hot", state.mode === "placing");
2344
+ inboxBtn.classList.toggle("lit", state.inboxOpen);
2345
+ const open = String(openTaskCount(state.pins));
2346
+ if (count.textContent !== open) count.textContent = open;
2347
+ captureBtn.classList.toggle("lit", state.captureMode === "tab");
2348
+ captureBtn.title = state.captureMode === "tab" ? "Tab capture on — real pixels, Chrome asks once per page load (S)" : "Screenshots: DOM snapshot, no prompt — press for tab capture (S)";
2349
+ if (hideShown !== state.pinsHidden) {
2350
+ hideShown = state.pinsHidden;
2351
+ hideBtn.innerHTML = icon(state.pinsHidden ? EYE_GLYPH : EYE_OFF_GLYPH, 14);
2352
+ hideBtn.classList.toggle("lit", state.pinsHidden);
2353
+ hideBtn.title = state.pinsHidden ? "Show pins (H)" : "Hide pins (H)";
2354
+ }
2355
+ }
2356
+ };
2357
+ }
2358
+ //#endregion
2359
+ //#region src/ui/bar-drag.ts
2360
+ const MARGIN = 16;
2361
+ function createBarDrag(host) {
2362
+ const { win, bar, grip } = host;
2363
+ const key = `${host.storagePrefix}:bar`;
2364
+ let pos = readPoint(host.storage, key);
2365
+ /** Where the bar was when a press began, so a tap-sized wobble snaps back. */
2366
+ let before = null;
2367
+ function persist() {
2368
+ try {
2369
+ if (pos === null) host.storage?.removeItem(key);
2370
+ else host.storage?.setItem(key, JSON.stringify(pos));
2371
+ } catch {}
2372
+ }
2373
+ function box() {
2374
+ const r = bar.getBoundingClientRect();
2375
+ return {
2376
+ w: r.width,
2377
+ h: r.height
2378
+ };
2379
+ }
2380
+ function apply(p) {
2381
+ pos = p;
2382
+ bar.classList.toggle("free", p !== null);
2383
+ bar.style.left = p === null ? "" : `${p.x}px`;
2384
+ bar.style.top = p === null ? "" : `${p.y}px`;
2385
+ }
2386
+ const drag = attachDrag(grip, {
2387
+ origin: () => {
2388
+ if (bar.classList.contains("pb-ghost")) return null;
2389
+ const r = bar.getBoundingClientRect();
2390
+ return {
2391
+ x: r.left,
2392
+ y: r.top
2393
+ };
2394
+ },
2395
+ canStart: () => !bar.classList.contains("pb-ghost"),
2396
+ onStart() {
2397
+ before = pos;
2398
+ bar.classList.add("dragging");
2399
+ },
2400
+ onMove(next) {
2401
+ apply(clampToViewport(next, win, box(), MARGIN));
2402
+ },
2403
+ onEnd({ dragged, started }) {
2404
+ bar.classList.remove("dragging");
2405
+ if (dragged) persist();
2406
+ else if (started) apply(before);
2407
+ }
2408
+ });
2409
+ function reset() {
2410
+ apply(null);
2411
+ persist();
2412
+ }
2413
+ function onResize() {
2414
+ if (pos !== null) apply(clampToViewport(pos, win, box(), MARGIN));
2415
+ }
2416
+ grip.addEventListener("dblclick", reset);
2417
+ win.addEventListener("resize", onResize);
2418
+ if (pos !== null) apply(clampToViewport(pos, win, box(), MARGIN));
1704
2419
  return {
1705
- root,
1706
- update(state) {
1707
- const text = state.mode === "placing" ? "CLICK TO PIN" : CONNECTION_LABEL[state.connection];
1708
- if (label.textContent !== text) label.textContent = text;
1709
- pinBtn.classList.toggle("hot", state.mode === "placing");
1710
- inboxBtn.classList.toggle("lit", state.inboxOpen);
1711
- const open = String(state.pins.filter((p) => p.status !== "resolved").length);
1712
- if (count.textContent !== open) count.textContent = open;
2420
+ position: () => pos,
2421
+ reset,
2422
+ destroy() {
2423
+ drag.destroy();
2424
+ grip.removeEventListener("dblclick", reset);
2425
+ win.removeEventListener("resize", onResize);
1713
2426
  }
1714
2427
  };
1715
2428
  }
@@ -1743,6 +2456,168 @@ function pinNumber(n) {
1743
2456
  return String(n).padStart(2, "0");
1744
2457
  }
1745
2458
  //#endregion
2459
+ //#region src/ui/card-messages.ts
2460
+ /** The prototype's `_h` innerHTML memo, kept off the DOM node. */
2461
+ const nodeMemo = /* @__PURE__ */ new WeakMap();
2462
+ function timeOf(at) {
2463
+ const d = new Date(at);
2464
+ if (Number.isNaN(d.getTime())) return "";
2465
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
2466
+ }
2467
+ function isImage(att) {
2468
+ if (att.contentType?.startsWith("image/")) return true;
2469
+ return /\.(png|webp|jpe?g|gif)$/i.test(att.url ?? att.path ?? "");
2470
+ }
2471
+ function fileName(att) {
2472
+ const source = att.url ?? att.path ?? att.id;
2473
+ return source.split("/").pop() ?? source;
2474
+ }
2475
+ /** Thumbnail when the attachment is an image; the error listener degrades it to a chip. */
2476
+ function attachmentsHtml(m) {
2477
+ if (!m.attachments?.length) return "";
2478
+ return `<div class="atts">${m.attachments.map((att) => isImage(att) ? `<span class="pb-att"><img src="${esc(safeUrl(att.url ?? att.path ?? ""))}" alt="${esc(fileName(att))}" loading="lazy"></span>` : `<span class="pb-att-chip">${esc(fileName(att))}</span>`).join("")}</div>`;
2479
+ }
2480
+ /** "claude:lark-mac-agent" → "Claude · lark-mac-agent"; other shapes verbatim. */
2481
+ function agentName(origin) {
2482
+ const idx = origin.indexOf(":");
2483
+ if (idx <= 0) return origin;
2484
+ const agent = origin.slice(0, idx);
2485
+ return `${agent.charAt(0).toUpperCase()}${agent.slice(1)} · ${origin.slice(idx + 1)}`;
2486
+ }
2487
+ function messageHtml(m) {
2488
+ if (m.role === "agent") return `<div class="pb-msg"><div class="pb-av agent">AI</div><div class="col"><div class="line"><span class="who">${esc(m.origin === void 0 ? "Agent" : agentName(m.origin))}</span><span class="tm">${esc(timeOf(m.at))}</span></div><div class="txt">${esc(m.text)}</div>${attachmentsHtml(m)}</div></div>`;
2489
+ const mirror = m.role === "mirror";
2490
+ const origin = mirror ? m.origin ?? "mirror" : null;
2491
+ const who = origin ? origin.split(":")[1] ?? origin : "You";
2492
+ const initials = who.slice(0, 2).toUpperCase();
2493
+ const via = origin ? `<span class="via-tag"><span>${esc(origin)}</span></span>` : "";
2494
+ return `<div class="pb-msg you"><div class="pb-av${mirror ? " via" : ""}">${esc(initials)}</div><div class="col"><div class="line"><span class="who">${esc(who)}</span><span class="tm">${esc(timeOf(m.at))}</span>${via}</div><div class="txt">${esc(m.text)}</div>${attachmentsHtml(m)}</div></div>`;
2495
+ }
2496
+ /** The agent has the message and has not answered yet. Its own node, so patching never rebuilds. */
2497
+ const PENDING_HTML = {
2498
+ thinking: "<div class=\"pb-typing\"><div class=\"pb-av agent\">AI</div><div class=\"dots\"><i></i><i></i><i></i></div><div class=\"lbl\">THINKING</div></div>",
2499
+ waiting: "<div class=\"pb-typing quiet\"><div class=\"pb-av agent\">AI</div><div class=\"lbl\">WAITING FOR AGENT</div></div>"
2500
+ };
2501
+ /**
2502
+ * Show, restyle or hide the "working on it" row.
2503
+ *
2504
+ * Without it the card sits silent from the moment you comment until the answer lands, which reads
2505
+ * as nothing happening — the single most common report on the demo. With it forever, a pin nobody
2506
+ * answers "thinks" for two weeks (dogfood) — so the row has stages, and "stale"/"none" remove it
2507
+ * (the stale footer takes over, card-parts.ts).
2508
+ */
2509
+ function patchPending(threadEl, kind) {
2510
+ const existing = threadEl.querySelector("[data-iid=\"pb-typing\"]");
2511
+ if (kind === "none" || kind === "stale") {
2512
+ existing?.remove();
2513
+ return;
2514
+ }
2515
+ const html = PENDING_HTML[kind];
2516
+ if (existing) {
2517
+ if (nodeMemo.get(existing) !== html) {
2518
+ existing.innerHTML = html;
2519
+ nodeMemo.set(existing, html);
2520
+ }
2521
+ threadEl.appendChild(existing);
2522
+ return;
2523
+ }
2524
+ const node = threadEl.ownerDocument.createElement("div");
2525
+ node.className = "pb-msg-w";
2526
+ node.setAttribute("data-iid", "pb-typing");
2527
+ node.innerHTML = html;
2528
+ nodeMemo.set(node, html);
2529
+ threadEl.appendChild(node);
2530
+ threadEl.scrollTop = threadEl.scrollHeight;
2531
+ }
2532
+ /** Keyed thread patching: appends/patches [data-iid] nodes only, never rebuilds. */
2533
+ function patchThread(threadEl, messages) {
2534
+ let appended = false;
2535
+ for (const m of messages) {
2536
+ let node = [...threadEl.children].find((c) => c.getAttribute("data-iid") === m.id) ?? null;
2537
+ const html = messageHtml(m);
2538
+ if (!node) {
2539
+ node = threadEl.ownerDocument.createElement("div");
2540
+ node.className = "pb-msg-w";
2541
+ node.setAttribute("data-iid", m.id);
2542
+ node.innerHTML = html;
2543
+ nodeMemo.set(node, html);
2544
+ threadEl.appendChild(node);
2545
+ appended = true;
2546
+ } else if (nodeMemo.get(node) !== html) {
2547
+ node.innerHTML = html;
2548
+ nodeMemo.set(node, html);
2549
+ }
2550
+ }
2551
+ if (appended) threadEl.scrollTop = threadEl.scrollHeight;
2552
+ }
2553
+ //#endregion
2554
+ //#region src/ui/card-parts.ts
2555
+ const STATUS_LABEL = {
2556
+ open: "OPEN",
2557
+ waiting: "OPEN",
2558
+ replied: "REPLIED",
2559
+ resolved: "RESOLVED",
2560
+ verify: "VERIFY",
2561
+ note: "NOTE",
2562
+ stale: "NO RESPONSE"
2563
+ };
2564
+ const CHECK_ICON$1 = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M3 8.5l3.2 3.2L13 4.8\"/></svg>";
2565
+ const X_ICON$1 = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M4 4l8 8M12 4l-8 8\"/></svg>";
2566
+ const COPY_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1\"/><path d=\"M10.5 3.5v-1a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h1\"/></svg>";
2567
+ function hdHtml(n, targetLabel, status, resolvable, copyable) {
2568
+ return `<div class="meta"><span class="num">${pinNumber(n)}</span><span>${esc(targetLabel)}</span><span class="st">${esc(status)}</span></div><div style="display:flex;gap:2px">` + (copyable ? `<button type="button" class="pb-ico" data-action="copy" title="Copy this pin">${COPY_ICON}</button>` : "") + (resolvable ? `<button type="button" class="pb-ico ok" data-action="resolve" title="Resolve (R)">${CHECK_ICON$1}</button>` : "") + `<button type="button" class="pb-ico" data-action="close" title="Close (Esc)">${X_ICON$1}</button></div>`;
2569
+ }
2570
+ /** One name per locus: selector first, else anchor, else tag. */
2571
+ function locusName(t) {
2572
+ return t.selector ?? t.anchor ?? t.tag?.toUpperCase();
2573
+ }
2574
+ /** The extra loci of a multi-target pin — the anchor leads, extras follow. */
2575
+ function lociHtml(pin) {
2576
+ const target = pin?.target;
2577
+ const extras = target?.targets;
2578
+ if (target === void 0 || extras === void 0 || extras.length === 0) return "";
2579
+ const names = [target, ...extras].map((t) => esc(locusName(t) ?? "?"));
2580
+ return `<div class="pb-loci">${names.length} targets: ${names.join(" · ")}</div>`;
2581
+ }
2582
+ /** Link badge: pin.links[0] read-only — no picker, no unlink yet. */
2583
+ function linkHtml(pin) {
2584
+ const link = pin?.links?.[0];
2585
+ if (!link) return "";
2586
+ return `<div class="pb-linkbar"><span class="ch">${esc(link.connector)}</span><span class="mt">${esc(link.ref)}</span><span class="sp"></span><a class="pb-open" href="${esc(safeUrl(link.url))}" target="_blank" rel="noreferrer">OPEN</a></div>`;
2587
+ }
2588
+ /**
2589
+ * Who resolved the pin and what they said. The schema has carried `resolution.note` and
2590
+ * `.commit` since v1 (agents write them); the card never showed either, so a resolved pin
2591
+ * read as bare "RESOLVED" with the why one CLI call away.
2592
+ */
2593
+ function resolutionHtml(pin) {
2594
+ const r = pin?.resolution;
2595
+ if (pin === null || r === void 0 || pin.status !== "resolved") return "";
2596
+ return `<div class="pb-resnote">Resolved by ${r.by === "agent" ? "agent" : "you"}${r.note === void 0 ? "" : ` · ${esc(r.note)}`}${r.commit === void 0 ? "" : ` <span class="hh">${esc(r.commit.slice(0, 7))}</span>`}</div>`;
2597
+ }
2598
+ /**
2599
+ * The pin has waited too long. Nudge re-posts your last message so a watcher re-triggers;
2600
+ * Resolve clears it — the two things you can actually do about a silent agent.
2601
+ */
2602
+ function staleHtml(status) {
2603
+ if (status !== "stale") return "";
2604
+ return "<div class=\"pb-stale\"><span class=\"msg\">No agent has answered. It may not be running.</span><button type=\"button\" class=\"pb-bt-ghost\" data-action=\"nudge\" title=\"Re-send your last message\">Nudge</button><button type=\"button\" class=\"pb-bt-ok\" data-action=\"resolve\">Resolve</button></div>";
2605
+ }
2606
+ function verifyHtml(status) {
2607
+ if (status === "verify") return "<div class=\"pb-verify\"><button type=\"button\" class=\"pb-bt-ok\" data-action=\"verify-accept\">Looks good</button><button type=\"button\" class=\"pb-bt-ghost\" data-action=\"verify-reopen\">Reopen</button></div>";
2608
+ if (status === "resolved") return "<div class=\"pb-verify\"><button type=\"button\" class=\"pb-bt-ghost\" data-action=\"verify-reopen\">Unresolve</button></div>";
2609
+ return "";
2610
+ }
2611
+ /**
2612
+ * The composer row. A draft chooses what it is before it exists: "Ask agent" (the default —
2613
+ * a `note` pin an agent picks up) or "Note" (a `comment` pin, a remark for people that never
2614
+ * wakes an agent). A control on the draft, not a global toggle: a mode you set once and forget
2615
+ * makes the next pin silently the wrong kind.
2616
+ */
2617
+ function rowHtml(hasThread, isDraft, kind) {
2618
+ return `${isDraft ? `<div class="pb-seg" role="radiogroup" aria-label="Pin kind"><button type="button" role="radio" aria-checked="${kind === "note"}" class="${kind === "note" ? "on" : ""}" data-kind="note" title="An agent picks this up">Ask agent</button><button type="button" role="radio" aria-checked="${kind === "comment"}" class="${kind === "comment" ? "on" : ""}" data-kind="comment" title="A remark for people; no agent acts on it">Note</button></div>` : ""}<div class="pb-kbd">⌘ ↵</div><button type="button" class="pb-bt-solid" data-action="send">${hasThread ? "Reply" : kind === "comment" ? "Leave note" : "Comment"}</button>`;
2619
+ }
2620
+ //#endregion
1746
2621
  //#region src/ui/pins.ts
1747
2622
  /** The prototype's `_h` innerHTML memo, kept off the DOM node. */
1748
2623
  const chipMemo = /* @__PURE__ */ new WeakMap();
@@ -1764,39 +2639,89 @@ function sameView(win, url) {
1764
2639
  return true;
1765
2640
  }
1766
2641
  }
2642
+ /** A stored (document-space) rect or point, in today's viewport. */
2643
+ function toViewport(win, p) {
2644
+ return {
2645
+ ...p,
2646
+ x: p.x - win.scrollX,
2647
+ y: p.y - win.scrollY
2648
+ };
2649
+ }
1767
2650
  /**
1768
- * Where the pin's anchor is NOW (dogfood #26: markers lingered over unrelated
1769
- * views after SPA tab switches, because placement trusted the stored rect
1770
- * forever). Re-resolve the captured selector on every render:
1771
- * - it resolves with layout → snap to the LIVE rect (also fixes drift);
1772
- * - it resolves without layout (test DOMs, display:none) stored rect;
2651
+ * Where the pin's anchor is NOW, in VIEWPORT space (dogfood #26: markers lingered over
2652
+ * unrelated views after SPA tab switches, because placement trusted the stored rect forever;
2653
+ * dogfood v4: pins drifted on scroll, because the layer was document-space and only
2654
+ * re-rendered on DOM mutation). Re-resolve the captured selector on every render:
2655
+ * - it resolves with layout the LIVE client rect, which is right inside inner scroll
2656
+ * containers and on sticky/fixed anchors alike;
2657
+ * - it resolves without layout (test DOMs, display:none) → stored rect minus scroll;
1773
2658
  * - it does not resolve → no marker; the drawer stays the see-everything list.
1774
2659
  * A pin with no selector (terminal-adjacent) keeps its stored rect, as before.
1775
2660
  */
1776
- function anchorRect(layer, pin) {
1777
- const stored = pin.target?.rect;
2661
+ function anchorRect(doc, pin) {
2662
+ return targetRect(doc, pin.target);
2663
+ }
2664
+ /** The same resolution for any captured target — a pin's, or the draft's before it commits. */
2665
+ function targetRect(doc, target) {
2666
+ const stored = target?.rect;
1778
2667
  if (stored === void 0) return null;
1779
- const doc = layer.ownerDocument;
1780
2668
  const win = doc.defaultView;
1781
2669
  if (win === null) return stored;
1782
- if (!sameView(win, pin.target?.url)) return null;
1783
- const selector = pin.target?.selector;
1784
- if (selector === void 0) return stored;
2670
+ if (!sameView(win, target?.url)) return null;
2671
+ const selector = target?.selector;
2672
+ if (selector === void 0) return toViewport(win, stored);
1785
2673
  let el;
1786
2674
  try {
1787
2675
  el = doc.querySelector(selector);
1788
2676
  } catch {
1789
- return stored;
2677
+ return toViewport(win, stored);
1790
2678
  }
1791
2679
  if (el === null) return null;
1792
2680
  const r = el.getBoundingClientRect();
1793
- if (r.width <= 0 && r.height <= 0) return stored;
1794
- return {
1795
- x: r.left + win.scrollX,
1796
- y: r.top + win.scrollY,
2681
+ if (r.width <= 0 && r.height <= 0) return toViewport(win, stored);
2682
+ return clipToScrollAncestors(win, el, {
2683
+ x: r.left,
2684
+ y: r.top,
1797
2685
  width: r.width,
1798
2686
  height: r.height
1799
- };
2687
+ });
2688
+ }
2689
+ const CLIPPING = /* @__PURE__ */ new Set([
2690
+ "auto",
2691
+ "scroll",
2692
+ "hidden",
2693
+ "clip"
2694
+ ]);
2695
+ /**
2696
+ * The part of `rect` an ancestor scroll container actually shows. A row scrolled out of its
2697
+ * pane has a live client rect above or below the pane; drawing a marker there floats it over
2698
+ * unrelated content (dogfood: the draft on Record 12 sat on the heading once the pane scrolled).
2699
+ * Null when nothing of the element is visible; the drawer still lists the pin.
2700
+ */
2701
+ function clipToScrollAncestors(win, el, rect) {
2702
+ let out = rect;
2703
+ for (let p = el.parentElement; p !== null && p !== win.document.body; p = p.parentElement) {
2704
+ const cs = win.getComputedStyle(p);
2705
+ if (![
2706
+ cs.overflow,
2707
+ cs.overflowX,
2708
+ cs.overflowY
2709
+ ].some((v) => CLIPPING.has(v))) continue;
2710
+ const c = p.getBoundingClientRect();
2711
+ if (c.width <= 0 && c.height <= 0) continue;
2712
+ const x1 = Math.max(out.x, c.left);
2713
+ const y1 = Math.max(out.y, c.top);
2714
+ const x2 = Math.min(out.x + out.width, c.right);
2715
+ const y2 = Math.min(out.y + out.height, c.bottom);
2716
+ if (x2 <= x1 || y2 <= y1) return null;
2717
+ out = {
2718
+ x: x1,
2719
+ y: y1,
2720
+ width: x2 - x1,
2721
+ height: y2 - y1
2722
+ };
2723
+ }
2724
+ return out;
1800
2725
  }
1801
2726
  /**
1802
2727
  * Where the needle lands: the point inside the element that was actually clicked, when the pin
@@ -1813,13 +2738,25 @@ function pinPoint(r, spot) {
1813
2738
  y: r.y + r.height * fy
1814
2739
  };
1815
2740
  }
2741
+ /**
2742
+ * Where the draft marker sits: its captured element's LIVE rect at the clicked spot, exactly as a
2743
+ * committed pin would (a draft on a sticky header must ride the header while you type). Null when
2744
+ * the element is scrolled out of its container or gone — no marker, and the card docks
2745
+ * (card.ts) instead of floating over whatever now occupies the stale point.
2746
+ */
2747
+ function draftPoint(doc, draft) {
2748
+ const target = draft.target.target;
2749
+ const live = targetRect(doc, target);
2750
+ return live === null ? null : pinPoint(live, target.spot);
2751
+ }
1816
2752
  /** Chip contents (prototype chipBtnInner, lines 546–550): number + linked-channel tag,
1817
2753
  * plus the queued badge while the pin waits in the outbox for the reconnect flush. */
1818
- function chipInner(n, pin, queued = false) {
2754
+ function chipInner(n, pin, queued = false, stale = false) {
1819
2755
  const link = pin?.links?.[0];
1820
2756
  const badge = link ? `<span class="lk"><span>${esc(link.connector)}</span></span>` : "";
1821
- const qd = queued ? "<span class=\"qd\">QUEUED</span>" : "";
1822
- return `<span>${pinNumber(n)}</span>${badge}${qd}`;
2757
+ const qd = queued ? "<span class=\"qd\">QUEUED</span>" : stale ? "<span class=\"qd\">NO REPLY</span>" : "";
2758
+ const nt = pin?.kind === "comment" ? "<span class=\"nt\" title=\"Note — no agent acts on this\">N</span>" : "";
2759
+ return `<span>${pinNumber(n)}</span>${nt}${badge}${qd}`;
1823
2760
  }
1824
2761
  function ensureNode(layer, key, fresh) {
1825
2762
  let node = layer.querySelector(`[data-pin="${key}"]`);
@@ -1853,128 +2790,43 @@ function renderPins(layer, state) {
1853
2790
  const visible = state.pins.filter((p) => p.status !== "resolved" || p.id === state.activePinId);
1854
2791
  const placed = [];
1855
2792
  visible.forEach((pin, i) => {
1856
- const rect = anchorRect(layer, pin);
2793
+ const rect = anchorRect(layer.ownerDocument, pin);
1857
2794
  if (rect === null) return;
1858
2795
  const spot = pin.target?.spot;
1859
- const n = pin.n ?? i + 1;
1860
- placed.push(spot === void 0 ? {
1861
- pin,
1862
- n,
1863
- rect
1864
- } : {
1865
- pin,
1866
- n,
1867
- rect,
1868
- spot
1869
- });
1870
- });
1871
- const keys = new Set(placed.map((entry) => entry.pin.id));
1872
- if (state.draft) keys.add("draft");
1873
- for (const node of [...layer.children]) if (!keys.has(node.getAttribute("data-pin") ?? "")) node.remove();
1874
- for (const { pin, n, rect, spot } of placed) {
1875
- const node = ensureNode(layer, pin.id, false);
1876
- const hot = pin.id === state.activePinId;
1877
- const queued = state.queuedIds.has(pin.id);
1878
- node.classList.toggle("queued", queued);
1879
- patchNode(node, pinPoint(rect, spot), hot, chipInner(n, pin, queued));
1880
- }
1881
- if (state.draft) patchNode(ensureNode(layer, "draft", true), state.draft.placedAt, true, chipInner(nextOrdinal(state.pins), null));
1882
- }
1883
- //#endregion
1884
- //#region src/ui/card.ts
1885
- const STATUS_LABEL = {
1886
- open: "OPEN",
1887
- waiting: "OPEN",
1888
- replied: "REPLIED",
1889
- resolved: "RESOLVED",
1890
- verify: "VERIFY"
1891
- };
1892
- const CHECK_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M3 8.5l3.2 3.2L13 4.8\"/></svg>";
1893
- const X_ICON$1 = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M4 4l8 8M12 4l-8 8\"/></svg>";
1894
- const COPY_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1\"/><path d=\"M10.5 3.5v-1a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h1\"/></svg>";
1895
- const ctxByCard = /* @__PURE__ */ new WeakMap();
1896
- /** The prototype's `_h` innerHTML memo, kept off the DOM node. */
1897
- const nodeMemo = /* @__PURE__ */ new WeakMap();
1898
- function timeOf(at) {
1899
- const d = new Date(at);
1900
- if (Number.isNaN(d.getTime())) return "";
1901
- return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
1902
- }
1903
- function isImage(att) {
1904
- if (att.contentType?.startsWith("image/")) return true;
1905
- return /\.(png|webp|jpe?g|gif)$/i.test(att.url ?? att.path ?? "");
1906
- }
1907
- function fileName(att) {
1908
- const source = att.url ?? att.path ?? att.id;
1909
- return source.split("/").pop() ?? source;
1910
- }
1911
- /** Thumbnail when the attachment is an image; the error listener degrades it to a chip. */
1912
- function attachmentsHtml(m) {
1913
- if (!m.attachments?.length) return "";
1914
- return `<div class="atts">${m.attachments.map((att) => isImage(att) ? `<span class="pb-att"><img src="${esc(safeUrl(att.url ?? att.path ?? ""))}" alt="${esc(fileName(att))}" loading="lazy"></span>` : `<span class="pb-att-chip">${esc(fileName(att))}</span>`).join("")}</div>`;
1915
- }
1916
- /** "claude:lark-mac-agent" → "Claude · lark-mac-agent"; other shapes verbatim. */
1917
- function agentName(origin) {
1918
- const idx = origin.indexOf(":");
1919
- if (idx <= 0) return origin;
1920
- const agent = origin.slice(0, idx);
1921
- return `${agent.charAt(0).toUpperCase()}${agent.slice(1)} · ${origin.slice(idx + 1)}`;
1922
- }
1923
- function messageHtml(m) {
1924
- if (m.role === "agent") return `<div class="pb-msg"><div class="pb-av agent">AI</div><div class="col"><div class="line"><span class="who">${esc(m.origin === void 0 ? "Agent" : agentName(m.origin))}</span><span class="tm">${esc(timeOf(m.at))}</span></div><div class="txt">${esc(m.text)}</div>${attachmentsHtml(m)}</div></div>`;
1925
- const mirror = m.role === "mirror";
1926
- const origin = mirror ? m.origin ?? "mirror" : null;
1927
- const who = origin ? origin.split(":")[1] ?? origin : "You";
1928
- const initials = who.slice(0, 2).toUpperCase();
1929
- const via = origin ? `<span class="via-tag"><span>${esc(origin)}</span></span>` : "";
1930
- return `<div class="pb-msg you"><div class="pb-av${mirror ? " via" : ""}">${esc(initials)}</div><div class="col"><div class="line"><span class="who">${esc(who)}</span><span class="tm">${esc(timeOf(m.at))}</span>${via}</div><div class="txt">${esc(m.text)}</div>${attachmentsHtml(m)}</div></div>`;
1931
- }
1932
- /** The agent has the message and has not answered yet. Its own node, so patching never rebuilds. */
1933
- const TYPING_HTML = "<div class=\"pb-typing\"><div class=\"pb-av agent\">AI</div><div class=\"dots\"><i></i><i></i><i></i></div><div class=\"lbl\">THINKING</div></div>";
1934
- /**
1935
- * Show or hide the "working on it" row.
1936
- *
1937
- * Without it the card sits silent from the moment you comment until the answer lands, which reads
1938
- * as nothing happening — the single most common report on the demo.
1939
- */
1940
- function patchTyping(threadEl, pending) {
1941
- const existing = threadEl.querySelector("[data-iid=\"pb-typing\"]");
1942
- if (!pending) {
1943
- existing?.remove();
1944
- return;
1945
- }
1946
- if (existing) {
1947
- threadEl.appendChild(existing);
1948
- return;
1949
- }
1950
- const node = threadEl.ownerDocument.createElement("div");
1951
- node.className = "pb-msg-w";
1952
- node.setAttribute("data-iid", "pb-typing");
1953
- node.innerHTML = TYPING_HTML;
1954
- threadEl.appendChild(node);
1955
- threadEl.scrollTop = threadEl.scrollHeight;
1956
- }
1957
- /** Keyed thread patching: appends/patches [data-iid] nodes only, never rebuilds. */
1958
- function patchThread(threadEl, messages) {
1959
- let appended = false;
1960
- for (const m of messages) {
1961
- let node = threadEl.querySelector(`[data-iid="${m.id}"]`);
1962
- const html = messageHtml(m);
1963
- if (!node) {
1964
- node = threadEl.ownerDocument.createElement("div");
1965
- node.className = "pb-msg-w";
1966
- node.setAttribute("data-iid", m.id);
1967
- node.innerHTML = html;
1968
- nodeMemo.set(node, html);
1969
- threadEl.appendChild(node);
1970
- appended = true;
1971
- } else if (nodeMemo.get(node) !== html) {
1972
- node.innerHTML = html;
1973
- nodeMemo.set(node, html);
1974
- }
1975
- }
1976
- if (appended) threadEl.scrollTop = threadEl.scrollHeight;
2796
+ const n = pin.n ?? i + 1;
2797
+ placed.push(spot === void 0 ? {
2798
+ pin,
2799
+ n,
2800
+ rect
2801
+ } : {
2802
+ pin,
2803
+ n,
2804
+ rect,
2805
+ spot
2806
+ });
2807
+ });
2808
+ const keys = new Set(placed.map((entry) => entry.pin.id));
2809
+ if (state.draft) keys.add("draft");
2810
+ for (const node of [...layer.children]) if (!keys.has(node.getAttribute("data-pin") ?? "")) node.remove();
2811
+ for (const { pin, n, rect, spot } of placed) {
2812
+ const node = ensureNode(layer, pin.id, false);
2813
+ const hot = pin.id === state.activePinId;
2814
+ const queued = state.queuedIds.has(pin.id);
2815
+ node.classList.toggle("queued", queued);
2816
+ node.classList.toggle("note", pin.kind === "comment");
2817
+ const stale = deriveUiStatus(pin, state.threads.get(pin.id) ?? [], state) === "stale";
2818
+ node.classList.toggle("stale", stale);
2819
+ patchNode(node, pinPoint(rect, spot), hot, chipInner(n, pin, queued, stale));
2820
+ }
2821
+ const draftAt = state.draft ? draftPoint(layer.ownerDocument, state.draft) : null;
2822
+ if (draftAt === null) layer.querySelector("[data-pin=\"draft\"]")?.remove();
2823
+ if (state.draft && draftAt !== null) patchNode(ensureNode(layer, "draft", true), draftAt, true, chipInner(nextOrdinal(state.pins), null));
1977
2824
  }
2825
+ //#endregion
2826
+ //#region src/ui/card.ts
2827
+ const ctxByCard = /* @__PURE__ */ new WeakMap();
2828
+ /** .pb-card width (styles.ts). */
2829
+ const CARD_W = 344;
1978
2830
  function ensureShell(root) {
1979
2831
  let card = root.querySelector(".pb-card");
1980
2832
  if (!card) {
@@ -1987,7 +2839,8 @@ function ensureShell(root) {
1987
2839
  const ctx = {
1988
2840
  pid: null,
1989
2841
  parts: {},
1990
- actions: null
2842
+ actions: null,
2843
+ draftKind: "note"
1991
2844
  };
1992
2845
  ctxByCard.set(card, ctx);
1993
2846
  card.addEventListener("click", (e) => onCardClick(card, ctx, e));
@@ -1998,29 +2851,55 @@ function submit(card, ctx) {
1998
2851
  const ta = card.querySelector("textarea");
1999
2852
  const text = ta?.value.trim();
2000
2853
  if (!ta || !text || !ctx.pid) return;
2001
- ctx.actions.send(ctx.pid === "draft" ? "draft" : ctx.pid, text);
2854
+ ctx.actions.send(ctx.pid === "draft" ? "draft" : ctx.pid, text, ctx.draftKind);
2002
2855
  ta.value = "";
2003
2856
  }
2857
+ /** The draft's kind control: pick, redraw the row, keep typing. */
2858
+ function onKindPick(card, ctx, kind) {
2859
+ ctx.draftKind = kind;
2860
+ setPart(card, ctx, "row", rowHtml(false, true, kind));
2861
+ card.querySelector("textarea")?.focus();
2862
+ }
2863
+ /** A moment of green on the copy button is the whole receipt — there is no toast layer,
2864
+ * and the header part-memo never resets a class toggle. */
2865
+ function flashCopied(card, from) {
2866
+ const btn = from.closest?.("[data-action=\"copy\"]");
2867
+ if (!btn) return;
2868
+ btn.classList.add("ok");
2869
+ card.ownerDocument.defaultView?.setTimeout(() => btn.classList.remove("ok"), 900);
2870
+ }
2871
+ /** Actions that need a committed pin (a draft has no id to act on). */
2872
+ const PIN_ACTIONS = {
2873
+ resolve: (_card, ctx, pid) => ctx.actions.resolve(pid),
2874
+ nudge: (_card, ctx, pid) => ctx.actions.nudge(pid),
2875
+ copy: (card, ctx, pid, from) => {
2876
+ ctx.actions.copy(pid);
2877
+ flashCopied(card, from);
2878
+ },
2879
+ "verify-accept": (_card, ctx, pid) => ctx.actions.verify(pid, "accepted"),
2880
+ "verify-reopen": (card, ctx, pid) => {
2881
+ ctx.actions.verify(pid, "reopened");
2882
+ card.querySelector("textarea")?.focus();
2883
+ }
2884
+ };
2004
2885
  function onCardClick(card, ctx, e) {
2005
- const action = e.target.closest?.("[data-action]")?.getAttribute("data-action");
2886
+ const from = e.target;
2887
+ const kind = from.closest?.("[data-kind]")?.getAttribute("data-kind");
2888
+ if (kind === "note" || kind === "comment") {
2889
+ onKindPick(card, ctx, kind);
2890
+ return;
2891
+ }
2892
+ const action = from.closest?.("[data-action]")?.getAttribute("data-action");
2006
2893
  if (!action || !ctx.pid) return;
2007
- if (action === "send") submit(card, ctx);
2008
- else if (action === "close") ctx.actions.close();
2009
- else if (ctx.pid !== "draft") {
2010
- if (action === "resolve") ctx.actions.resolve(ctx.pid);
2011
- else if (action === "copy") {
2012
- ctx.actions.copy(ctx.pid);
2013
- const btn = e.target.closest?.("[data-action=\"copy\"]");
2014
- if (btn) {
2015
- btn.classList.add("ok");
2016
- card.ownerDocument.defaultView?.setTimeout(() => btn.classList.remove("ok"), 900);
2017
- }
2018
- } else if (action === "verify-accept") ctx.actions.verify(ctx.pid, "accepted");
2019
- else if (action === "verify-reopen") {
2020
- ctx.actions.verify(ctx.pid, "reopened");
2021
- card.querySelector("textarea")?.focus();
2022
- }
2894
+ if (action === "send") {
2895
+ submit(card, ctx);
2896
+ return;
2023
2897
  }
2898
+ if (action === "close") {
2899
+ ctx.actions.close();
2900
+ return;
2901
+ }
2902
+ if (ctx.pid !== "draft") PIN_ACTIONS[action]?.(card, ctx, ctx.pid, from);
2024
2903
  }
2025
2904
  function buildSkeleton(card, ctx, isDraft, hasThread) {
2026
2905
  card.innerHTML = "<div class=\"in\"><div class=\"pb-hd\" data-ref=\"hd\"></div><div data-ref=\"link\"></div><div data-ref=\"loci\"></div><div class=\"pb-thread\" data-ref=\"thread\"></div><div data-ref=\"verify\"></div><div class=\"pb-composer\"><textarea rows=\"2\"></textarea><div class=\"row\" data-ref=\"row\"></div></div></div>";
@@ -2039,52 +2918,23 @@ function buildSkeleton(card, ctx, isDraft, hasThread) {
2039
2918
  }, true);
2040
2919
  if (isDraft) ta.focus();
2041
2920
  }
2042
- function hdHtml(n, targetLabel, status, resolvable, copyable) {
2043
- return `<div class="meta"><span class="num">${pinNumber(n)}</span><span>${esc(targetLabel)}</span><span class="st">${esc(status)}</span></div><div style="display:flex;gap:2px">` + (copyable ? `<button type="button" class="pb-ico" data-action="copy" title="Copy this pin">${COPY_ICON}</button>` : "") + (resolvable ? `<button type="button" class="pb-ico ok" data-action="resolve" title="Resolve (R)">${CHECK_ICON}</button>` : "") + `<button type="button" class="pb-ico" data-action="close" title="Close (Esc)">${X_ICON$1}</button></div>`;
2044
- }
2045
- /** One name per locus: selector first, else anchor, else tag. */
2046
- function locusName(t) {
2047
- return t.selector ?? t.anchor ?? t.tag?.toUpperCase();
2048
- }
2049
- /** The extra loci of a multi-target pin — the anchor leads, extras follow. */
2050
- function lociHtml(pin) {
2051
- const target = pin?.target;
2052
- const extras = target?.targets;
2053
- if (target === void 0 || extras === void 0 || extras.length === 0) return "";
2054
- const names = [target, ...extras].map((t) => esc(locusName(t) ?? "?"));
2055
- return `<div class="pb-loci">${names.length} targets: ${names.join(" · ")}</div>`;
2056
- }
2057
- /** Link badge: pin.links[0] read-only — no picker, no unlink yet. */
2058
- function linkHtml(pin) {
2059
- const link = pin?.links?.[0];
2060
- if (!link) return "";
2061
- return `<div class="pb-linkbar"><span class="ch">${esc(link.connector)}</span><span class="mt">${esc(link.ref)}</span><span class="sp"></span><a class="pb-open" href="${esc(safeUrl(link.url))}" target="_blank" rel="noreferrer">OPEN</a></div>`;
2062
- }
2063
- function verifyHtml(status) {
2064
- if (status === "verify") return "<div class=\"pb-verify\"><button type=\"button\" class=\"pb-bt-ok\" data-action=\"verify-accept\">Looks good</button><button type=\"button\" class=\"pb-bt-ghost\" data-action=\"verify-reopen\">Reopen</button></div>";
2065
- if (status === "resolved") return "<div class=\"pb-verify\"><button type=\"button\" class=\"pb-bt-ghost\" data-action=\"verify-reopen\">Unresolve</button></div>";
2066
- return "";
2067
- }
2068
- function rowHtml(hasThread) {
2069
- return `<div class="pb-kbd">⌘ ↵</div><button type="button" class="pb-bt-solid" data-action="send">${hasThread ? "Reply" : "Comment"}</button>`;
2070
- }
2071
2921
  /**
2072
- * Viewport-aware placement, ported verbatim (prototype lines 660–668): measure
2073
- * the rendered card, flip left when it would overflow right, clamp between
2074
- * scrollY + margin and the command-bar clearance — never off-screen.
2922
+ * Viewport-aware placement, ported from the prototype (lines 660–668) into viewport space:
2923
+ * measure the rendered card, flip left when it would overflow right, clamp between the margin
2924
+ * and the command-bar clearance — never off-screen.
2075
2925
  */
2076
2926
  function position(card, at) {
2077
2927
  const win = card.ownerDocument.defaultView;
2078
2928
  if (!win) return;
2079
- const W = 344;
2929
+ const W = CARD_W;
2080
2930
  const m = 12;
2081
2931
  const barClear = 84;
2082
2932
  let left = at.x + 22;
2083
- if (left + W > win.scrollX + win.innerWidth - m) left = at.x - W - 22;
2084
- left = Math.max(win.scrollX + m, left);
2933
+ if (left + W > win.innerWidth - m) left = at.x - W - 22;
2934
+ left = Math.max(m, left);
2085
2935
  const h = card.querySelector(".in")?.offsetHeight ?? 0;
2086
- const minTop = win.scrollY + m;
2087
- const maxTop = win.scrollY + win.innerHeight - h - barClear;
2936
+ const minTop = m;
2937
+ const maxTop = win.innerHeight - h - barClear;
2088
2938
  card.style.left = `${left}px`;
2089
2939
  card.style.top = `${Math.max(minTop, Math.min(at.y - 60, maxTop))}px`;
2090
2940
  }
@@ -2106,15 +2956,35 @@ function ordinalOf(state, pin) {
2106
2956
  if (pin.n !== void 0) return pin.n;
2107
2957
  return state.pins.filter((p) => p.status !== "resolved" || p.id === state.activePinId).indexOf(pin) + 1;
2108
2958
  }
2109
- function anchorOf(pin, draft) {
2110
- const r = pin?.target?.rect;
2111
- if (!r) return draft?.placedAt ?? {
2959
+ /**
2960
+ * Where the card tethers, in viewport space. The LIVE anchor when the pin's element is on this
2961
+ * view; otherwise (other URL, selector gone, a terminal `pinbox pin`) the middle of the viewport
2962
+ * — dogfood: the stored rect of a pin whose view had moved on put the card off-screen, so a pin
2963
+ * listed in the drawer could be opened but never seen, let alone resolved.
2964
+ */
2965
+ function anchorOf(root, pin, draft) {
2966
+ const doc = root.ownerDocument;
2967
+ const win = doc.defaultView;
2968
+ let live = null;
2969
+ if (pin !== null) {
2970
+ const r = anchorRect(doc, pin);
2971
+ live = r === null ? null : {
2972
+ x: r.x + r.width / 2,
2973
+ y: r.y + r.height / 2
2974
+ };
2975
+ } else if (draft !== null) live = draftPoint(doc, draft);
2976
+ else return {
2977
+ x: 0,
2978
+ y: 0
2979
+ };
2980
+ if (live !== null) return live;
2981
+ if (win === null) return {
2112
2982
  x: 0,
2113
2983
  y: 0
2114
2984
  };
2115
2985
  return {
2116
- x: r.x + r.width / 2,
2117
- y: r.y + r.height / 2
2986
+ x: win.innerWidth / 2 - CARD_W / 2 - 22,
2987
+ y: win.innerHeight / 3 + 60
2118
2988
  };
2119
2989
  }
2120
2990
  /**
@@ -2124,7 +2994,7 @@ function anchorOf(pin, draft) {
2124
2994
  function labelOf(target) {
2125
2995
  return target?.anchor ?? target?.tag?.toUpperCase() ?? "PIN";
2126
2996
  }
2127
- function viewOf(state) {
2997
+ function viewOf(root, state) {
2128
2998
  const pin = activePin(state);
2129
2999
  const pid = pin?.id ?? (state.draft ? "draft" : null);
2130
3000
  if (!pid) return null;
@@ -2134,9 +3004,9 @@ function viewOf(state) {
2134
3004
  pin,
2135
3005
  thread,
2136
3006
  n: ordinalOf(state, pin),
2137
- status: pin ? deriveUiStatus(pin, thread) : null,
3007
+ status: pin ? deriveUiStatus(pin, thread, state) : null,
2138
3008
  label: labelOf(pin?.target ?? state.draft?.target.target),
2139
- at: anchorOf(pin, state.draft)
3009
+ at: anchorOf(root, pin, state.draft)
2140
3010
  };
2141
3011
  }
2142
3012
  /** Render the thread card for a state snapshot: the active pin, or the draft. */
@@ -2160,7 +3030,7 @@ function renderCard(root, state, actions) {
2160
3030
  const card = ensureShell(root);
2161
3031
  const ctx = ctxByCard.get(card);
2162
3032
  ctx.actions = actions;
2163
- const view = viewOf(state);
3033
+ const view = viewOf(root, state);
2164
3034
  if (!view) {
2165
3035
  card.hidden = true;
2166
3036
  ctx.pid = null;
@@ -2169,6 +3039,7 @@ function renderCard(root, state, actions) {
2169
3039
  if (ctx.pid !== view.pid) {
2170
3040
  ctx.pid = view.pid;
2171
3041
  ctx.parts = {};
3042
+ ctx.draftKind = "note";
2172
3043
  buildSkeleton(card, ctx, view.pid === "draft", view.pin !== null || view.thread.length > 0);
2173
3044
  }
2174
3045
  card.hidden = false;
@@ -2178,32 +3049,40 @@ function renderCard(root, state, actions) {
2178
3049
  setPart(card, ctx, "hd", hdHtml(view.n, view.label, statusLabel, resolvable, view.pin !== null));
2179
3050
  setPart(card, ctx, "link", linkHtml(view.pin));
2180
3051
  setPart(card, ctx, "loci", lociHtml(view.pin));
2181
- setPart(card, ctx, "verify", verifyHtml(view.status));
3052
+ setPart(card, ctx, "verify", resolutionHtml(view.pin) + staleHtml(view.status) + verifyHtml(view.status));
2182
3053
  const messages = view.pin === null ? view.thread : [pinAsMessage(view.pin), ...view.thread];
2183
- setPart(card, ctx, "row", rowHtml(messages.length > 0));
3054
+ setPart(card, ctx, "row", rowHtml(messages.length > 0, view.pid === "draft", ctx.draftKind));
2184
3055
  const threadEl = card.querySelector("[data-ref=\"thread\"]");
2185
3056
  if (threadEl) {
2186
3057
  patchThread(threadEl, messages);
2187
- patchTyping(threadEl, !queued && view.pin?.status === "open" && view.status === "waiting");
3058
+ patchPending(threadEl, queued || view.pin === null ? "none" : pendingKind(view.pin, view.thread, state));
2188
3059
  }
2189
3060
  position(card, view.at);
2190
3061
  }
2191
3062
  //#endregion
2192
3063
  //#region src/ui/drawer.ts
2193
3064
  const X_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M4 4l8 8M12 4l-8 8\"/></svg>";
3065
+ const CHECK_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M3 8.5l3.2 3.2L13 4.8\"/></svg>";
3066
+ const UNDO_ICON = "<svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M3.5 7.5h6a3 3 0 010 6H6\"/><path d=\"M6 4.5l-3 3 3 3\"/></svg>";
3067
+ /** How long a first click on Resolve-group waits for its confirming second click. */
3068
+ const CONFIRM_MS = 3e3;
2194
3069
  const STATUS_TEXT = {
2195
3070
  open: "OPEN",
2196
3071
  waiting: "OPEN",
2197
3072
  replied: "REPLIED",
2198
3073
  resolved: "RESOLVED",
2199
- verify: "VERIFY"
3074
+ verify: "VERIFY",
3075
+ note: "NOTE",
3076
+ stale: "NO RESPONSE"
2200
3077
  };
2201
3078
  const STATUS_DOT = {
2202
3079
  open: "var(--pb-fg4)",
2203
3080
  waiting: "var(--pb-fg4)",
2204
3081
  replied: "var(--pb-info)",
2205
3082
  resolved: "var(--pb-ok)",
2206
- verify: "var(--pb-amber)"
3083
+ verify: "var(--pb-amber)",
3084
+ note: "var(--pb-fg3)",
3085
+ stale: "var(--pb-amber)"
2207
3086
  };
2208
3087
  /**
2209
3088
  * The place a row names. A browser pin has a selector; a terminal `pinbox pin` has a
@@ -2212,44 +3091,138 @@ const STATUS_DOT = {
2212
3091
  function locusOf(pin) {
2213
3092
  return pin.target?.selector ?? pin.target?.source?.file ?? "";
2214
3093
  }
2215
- function itemHtml(pin, n, active, thread, queued) {
2216
- const status = deriveUiStatus(pin, thread);
3094
+ /** "github#58" the same label `pinbox link` prints. */
3095
+ function linkKey(pin) {
2217
3096
  const link = pin.links?.[0];
2218
- return `<button type="button" class="pb-item${active ? " on" : ""}" data-item="${esc(pin.id)}"><span class="nn">${pinNumber(n)}</span><span class="cc"><span class="tt">${esc(pin.text)}</span><span class="mm"><span class="sdot" style="background:${queued ? "var(--pb-amber)" : STATUS_DOT[status]}"></span><span>${queued ? "QUEUED" : STATUS_TEXT[status]}</span>` + (link ? `<span class="lk">${esc(link.connector)}</span>` : "") + `<span>${esc(locusOf(pin))}</span></span></span></button>`;
3097
+ return link === void 0 ? null : `${link.connector}#${link.ref}`;
3098
+ }
3099
+ function itemHtml(pin, n, active, thread, queued, view) {
3100
+ const status = deriveUiStatus(pin, thread, view);
3101
+ const link = pin.links?.[0];
3102
+ const act = pin.status === "resolved" ? `<button type="button" class="pb-ico" data-act="unresolve" title="Unresolve">${UNDO_ICON}</button>` : queued ? "" : `<button type="button" class="pb-ico ok" data-act="resolve" title="Resolve">${CHECK_ICON}</button>`;
3103
+ return `<div class="pb-item${active ? " on" : ""}" data-item="${esc(pin.id)}"><button type="button" class="pb-item-main" data-open="${esc(pin.id)}"><span class="nn">${pinNumber(n)}</span><span class="cc"><span class="tt">${esc(pin.text)}</span><span class="mm"><span class="sdot" style="background:${queued ? "var(--pb-amber)" : STATUS_DOT[status]}"></span><span>${queued ? "QUEUED" : STATUS_TEXT[status]}</span>` + (link ? `<span class="lk">${esc(link.connector)}</span>` : "") + `<span>${esc(locusOf(pin))}</span></span></span></button><span class="acts">${act}</span></div>`;
3104
+ }
3105
+ function groupHtml(key, pins, confirming) {
3106
+ const link = pins[0]?.links?.[0];
3107
+ const open = link ? `<a class="pb-open" href="${esc(safeUrl(link.url))}" target="_blank" rel="noreferrer">OPEN</a>` : "";
3108
+ const label = confirming ? "CONFIRM?" : `RESOLVE ${pins.length}`;
3109
+ return `<div class="pb-group"><span class="gk">${esc(link?.connector ?? "")}</span><span class="gr">#${esc(link?.ref ?? "")}</span><span class="sp"></span>${open}<button type="button" class="pb-gres${confirming ? " confirm" : ""}" data-group-resolve="${esc(key)}" title="Resolve every pin linked to ${esc(key)}">${label}</button></div>`;
3110
+ }
3111
+ /** Open pins split into the ungrouped list and one group per tracker item, in first-seen order. */
3112
+ function groupByLink(open) {
3113
+ const loose = [];
3114
+ const groups = /* @__PURE__ */ new Map();
3115
+ for (const pin of open) {
3116
+ const key = linkKey(pin);
3117
+ if (key === null) loose.push(pin);
3118
+ else groups.set(key, [...groups.get(key) ?? [], pin]);
3119
+ }
3120
+ return {
3121
+ loose,
3122
+ groups
3123
+ };
2219
3124
  }
2220
3125
  function createDrawer(doc, on) {
2221
3126
  const root = doc.createElement("div");
2222
3127
  root.className = "pb-drawer";
2223
3128
  root.hidden = true;
2224
- root.innerHTML = `<div class="dh"><span>INBOX</span><button type="button" class="pb-ico" data-ref="close" title="Close">${X_ICON}</button></div><div class="pb-tabs"><button type="button" class="pb-tab on" data-tab="open">OPEN · 0</button><button type="button" class="pb-tab" data-tab="resolved">RESOLVED · 0</button></div><div class="pb-items" data-ref="items"></div>`;
3129
+ root.innerHTML = `<div class="dh"><span>INBOX</span><button type="button" class="pb-ico" data-ref="close" title="Close">${X_ICON}</button></div><div class="pb-tabs"><button type="button" class="pb-tab on" data-tab="open">OPEN · 0</button><button type="button" class="pb-tab" data-tab="notes">NOTES · 0</button><button type="button" class="pb-tab" data-tab="resolved">RESOLVED · 0</button></div><div class="pb-items" data-ref="items"></div><div class="pb-dfoot" data-ref="foot" hidden></div>`;
2225
3130
  let tab = "open";
2226
3131
  let last = null;
2227
3132
  let itemsMemo = "";
3133
+ /** Group key awaiting its confirming click, if any. */
3134
+ let confirming = null;
3135
+ let confirmTimer = 0;
2228
3136
  const items = root.querySelector("[data-ref=\"items\"]");
3137
+ const foot = root.querySelector("[data-ref=\"foot\"]");
3138
+ let footMemo = "";
2229
3139
  const tabButtons = [...root.querySelectorAll("[data-tab]")];
3140
+ const win = doc.defaultView;
2230
3141
  root.querySelector("[data-ref=\"close\"]")?.addEventListener("click", on.onClose);
2231
3142
  for (const btn of tabButtons) btn.addEventListener("click", () => {
2232
3143
  tab = btn.getAttribute("data-tab");
2233
3144
  if (last) render(last);
2234
3145
  });
3146
+ function setConfirming(key) {
3147
+ confirming = key;
3148
+ win?.clearTimeout(confirmTimer);
3149
+ if (key !== null) confirmTimer = win?.setTimeout(() => setConfirming(null), CONFIRM_MS) ?? 0;
3150
+ if (last) render(last);
3151
+ }
3152
+ function resolveGroup(key) {
3153
+ if (confirming !== key) {
3154
+ setConfirming(key);
3155
+ return;
3156
+ }
3157
+ setConfirming(null);
3158
+ const pins = last?.pins.filter((p) => p.status === "open" && linkKey(p) === key) ?? [];
3159
+ for (const pin of pins) on.onResolve(pin.id, `shipped in ${key}`);
3160
+ }
3161
+ /** Every open pin the agent never answered (dogfood #6–10): one click clears the backlog. */
3162
+ function stalePins(state) {
3163
+ return state.pins.filter((p) => p.status === "open" && !state.queuedIds.has(p.id) && deriveUiStatus(p, state.threads.get(p.id) ?? [], state) === "stale");
3164
+ }
3165
+ function resolveStale() {
3166
+ if (confirming !== "stale") {
3167
+ setConfirming("stale");
3168
+ return;
3169
+ }
3170
+ setConfirming(null);
3171
+ for (const pin of last ? stalePins(last) : []) on.onResolve(pin.id, "no agent response");
3172
+ }
3173
+ foot.addEventListener("click", (e) => {
3174
+ if (e.target.closest?.("[data-bulk]")) resolveStale();
3175
+ });
2235
3176
  items.addEventListener("click", (e) => {
2236
- const id = e.target.closest?.("[data-item]")?.getAttribute("data-item");
3177
+ const target = e.target;
3178
+ const act = target.closest?.("[data-act]");
3179
+ if (act) {
3180
+ const id = act.closest("[data-item]")?.getAttribute("data-item");
3181
+ if (!id) return;
3182
+ if (act.getAttribute("data-act") === "resolve") on.onResolve(id);
3183
+ else on.onUnresolve(id);
3184
+ return;
3185
+ }
3186
+ const group = target.closest?.("[data-group-resolve]")?.getAttribute("data-group-resolve");
3187
+ if (group) {
3188
+ resolveGroup(group);
3189
+ return;
3190
+ }
3191
+ const id = target.closest?.("[data-open]")?.getAttribute("data-open");
2237
3192
  if (id) on.onActivate(id);
2238
3193
  });
3194
+ const rowOf = (state) => (p) => itemHtml(p, p.n ?? state.pins.indexOf(p) + 1, p.id === state.activePinId, state.threads.get(p.id) ?? [], state.queuedIds.has(p.id), state);
3195
+ function openHtml(state, open) {
3196
+ const row = rowOf(state);
3197
+ const { loose, groups } = groupByLink(open);
3198
+ let html = loose.map(row).join("");
3199
+ for (const [key, pins] of groups) html += groupHtml(key, pins, confirming === key) + pins.map(row).join("");
3200
+ return html;
3201
+ }
3202
+ /** The bulk footer: present on the OPEN tab exactly while some pin has had no response. */
3203
+ function renderFoot(state) {
3204
+ const stale = tab === "open" ? stalePins(state) : [];
3205
+ const html = stale.length === 0 ? "" : `<button type="button" class="pb-gres${confirming === "stale" ? " confirm" : ""}" data-bulk="stale">${confirming === "stale" ? "CONFIRM?" : `RESOLVE ${stale.length} WITH NO RESPONSE`}</button>`;
3206
+ if (footMemo === html) return;
3207
+ foot.innerHTML = html;
3208
+ foot.hidden = html === "";
3209
+ footMemo = html;
3210
+ }
2239
3211
  function render(state) {
2240
- const open = state.pins.filter((p) => p.status === "open");
2241
- const resolved = state.pins.filter((p) => p.status === "resolved");
2242
- const [openTab, doneTab] = tabButtons;
2243
- if (openTab) {
2244
- openTab.textContent = `OPEN · ${open.length}`;
2245
- openTab.classList.toggle("on", tab === "open");
2246
- }
2247
- if (doneTab) {
2248
- doneTab.textContent = `RESOLVED · ${resolved.length}`;
2249
- doneTab.classList.toggle("on", tab === "resolved");
3212
+ const open = state.pins.filter((p) => p.status === "open" && p.kind !== "comment");
3213
+ const counts = {
3214
+ open,
3215
+ notes: state.pins.filter((p) => p.status === "open" && p.kind === "comment"),
3216
+ resolved: state.pins.filter((p) => p.status === "resolved")
3217
+ };
3218
+ for (const btn of tabButtons) {
3219
+ const key = btn.getAttribute("data-tab");
3220
+ btn.textContent = `${key.toUpperCase()} · ${counts[key].length}`;
3221
+ btn.classList.toggle("on", tab === key);
2250
3222
  }
2251
- const list = tab === "open" ? open : resolved;
2252
- const html = list.length ? list.map((p) => itemHtml(p, p.n ?? state.pins.indexOf(p) + 1, p.id === state.activePinId, state.threads.get(p.id) ?? [], state.queuedIds.has(p.id))).join("") : "<div class=\"pb-empty\">Nothing here yet.</div>";
3223
+ renderFoot(state);
3224
+ const list = counts[tab];
3225
+ const html = list.length ? tab === "open" ? openHtml(state, open) : list.map(rowOf(state)).join("") : "<div class=\"pb-empty\">Nothing here yet.</div>";
2253
3226
  if (itemsMemo !== html) {
2254
3227
  items.innerHTML = html;
2255
3228
  itemsMemo = html;
@@ -2282,36 +3255,17 @@ function createDrawer(doc, on) {
2282
3255
  };
2283
3256
  }
2284
3257
  //#endregion
2285
- //#region src/ui/multimarks.ts
2286
- const MARK_CLASS = "pb-multi-mark";
2287
- /** Replace the mark set to mirror `targets`; entries with no rect draw nothing. */
2288
- function renderMultiMarks(layer, targets) {
2289
- for (const node of [...layer.querySelectorAll(`.${MARK_CLASS}`)]) node.remove();
2290
- targets.forEach((target, i) => {
2291
- const rect = target.rect;
2292
- if (rect === void 0) return;
2293
- const mark = layer.ownerDocument.createElement("div");
2294
- mark.className = MARK_CLASS;
2295
- mark.style.left = `${rect.x}px`;
2296
- mark.style.top = `${rect.y}px`;
2297
- mark.style.width = `${rect.width}px`;
2298
- mark.style.height = `${rect.height}px`;
2299
- mark.innerHTML = `<span>${i + 1}</span>`;
2300
- layer.appendChild(mark);
2301
- });
2302
- }
2303
- //#endregion
2304
3258
  //#region src/ui/puck.ts
2305
3259
  /** The bar's ident mark, sized up for the 48px puck face. */
2306
3260
  const PUCK_ICON = "<svg width=\"17\" height=\"17\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"2.5\" y=\"1.5\" width=\"11\" height=\"7\" rx=\"1\"/><path d=\"M8 8.5v6\"/><circle cx=\"8\" cy=\"14.6\" r=\".9\" fill=\"currentColor\" stroke=\"none\"/></svg>";
2307
- const FAN_PIN = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><rect x=\"3\" y=\"1.5\" width=\"10\" height=\"6.5\" rx=\"1\"/><path d=\"M8 8v6.5\"/></svg>";
2308
- const FAN_INBOX = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M1.8 8.5h3.4l1 2h3.6l1-2h3.4\"/><path d=\"M2.6 3.2h10.8l1.2 5.3v4a1 1 0 01-1 1H2.4a1 1 0 01-1-1v-4z\"/></svg>";
2309
- const FAN_THEME = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M8 2a4 4 0 0 0 6 6 6 6 0 1 1-6-6z\"/></svg>";
2310
- const FAN_EYE = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M1.6 8S4 3.8 8 3.8 14.4 8 14.4 8 12 12.2 8 12.2 1.6 8 1.6 8z\"/><circle cx=\"8\" cy=\"8\" r=\"1.8\"/></svg>";
2311
- const FAN_EYE_OFF = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M2.3 2.3l11.4 11.4\"/><path d=\"M4.9 4.9C2.7 6.2 1.6 8 1.6 8s2.4 4.2 6.4 4.2c1.2 0 2.3-.3 3.1-.8M6.7 4c.4-.1.9-.2 1.3-.2 4 0 6.4 4.2 6.4 4.2s-.8 1.4-2.2 2.5\"/></svg>";
2312
- const FAN_EXPAND = "<svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"><path d=\"M9.5 6.5v-4h4\"/><path d=\"M6.5 9.5v4h-4\"/></svg>";
2313
- function fanItem(act, index, icon, label, key) {
2314
- return `<button type="button" class="pb-fan-item" data-act="${act}" style="--i:${index}" aria-label="${label}">${icon}${act === "inbox" ? "<span class=\"badge\" data-ref=\"count\" hidden>0</span>" : ""}<span class="fl">${label.toUpperCase()}<i>${key}</i></span></button>`;
3261
+ /** Everything in the action table that asked for a fan item, in table order. */
3262
+ const FAN_ACTIONS = ACTIONS.filter((a) => a.fan !== void 0);
3263
+ function fanItem(a, index) {
3264
+ const act = a.fan?.act ?? a.id;
3265
+ const label = a.fan?.label ?? a.label;
3266
+ const glyph = act === "expand" ? EXPAND_GLYPH : a.glyph ?? "";
3267
+ const badge = a.id === "inbox" ? "<span class=\"badge\" data-ref=\"count\" hidden>0</span>" : "";
3268
+ return `<button type="button" class="pb-fan-item" data-act="${act}" style="--i:${index}" aria-label="${label}">${icon(glyph, 15)}${badge}<span class="fl">${label.toUpperCase()}<i>${keyLabelOf(a)}</i></span></button>`;
2315
3269
  }
2316
3270
  function createMinimizeUi(doc) {
2317
3271
  const puck = doc.createElement("button");
@@ -2324,7 +3278,7 @@ function createMinimizeUi(doc) {
2324
3278
  fan.className = "pb-fan";
2325
3279
  fan.hidden = true;
2326
3280
  fan.setAttribute("role", "menu");
2327
- fan.innerHTML = fanItem("pin", 0, FAN_PIN, "Drop a pin", "P") + fanItem("inbox", 1, FAN_INBOX, "Inbox", "I") + fanItem("theme", 2, FAN_THEME, "Theme", "D") + fanItem("hide", 3, FAN_EYE_OFF, "Hide pins", "H") + fanItem("expand", 4, FAN_EXPAND, "Expand", "M");
3281
+ fan.innerHTML = FAN_ACTIONS.map(fanItem).join("");
2328
3282
  const morphWrap = doc.createElement("div");
2329
3283
  morphWrap.className = "pb-morph-wrap";
2330
3284
  morphWrap.hidden = true;
@@ -2350,7 +3304,7 @@ function createMinimizeUi(doc) {
2350
3304
  surface,
2351
3305
  carrier,
2352
3306
  update(state) {
2353
- const open = String(state.pins.filter((p) => p.status !== "resolved").length);
3307
+ const open = String(openTaskCount(state.pins));
2354
3308
  for (const badge of badges) {
2355
3309
  if (badge.textContent !== open) badge.textContent = open;
2356
3310
  badge.hidden = open === "0";
@@ -2361,7 +3315,7 @@ function createMinimizeUi(doc) {
2361
3315
  if (hideShown !== state.pinsHidden) {
2362
3316
  hideShown = state.pinsHidden;
2363
3317
  const label = state.pinsHidden ? "Show pins" : "Hide pins";
2364
- hideItem.innerHTML = `${state.pinsHidden ? FAN_EYE : FAN_EYE_OFF}<span class="fl">${label.toUpperCase()}<i>H</i></span>`;
3318
+ hideItem.innerHTML = icon(state.pinsHidden ? EYE_GLYPH : EYE_OFF_GLYPH, 15) + `<span class="fl">${label.toUpperCase()}<i>H</i></span>`;
2365
3319
  hideItem.setAttribute("aria-label", label);
2366
3320
  hideItem.classList.toggle("lit", state.pinsHidden);
2367
3321
  }
@@ -2369,70 +3323,19 @@ function createMinimizeUi(doc) {
2369
3323
  };
2370
3324
  }
2371
3325
  //#endregion
2372
- //#region src/ui/reticle.ts
2373
- function createReticle(doc) {
2374
- const crosshair = doc.createElement("div");
2375
- crosshair.className = "pb-reticle";
2376
- crosshair.innerHTML = "<div class=\"h\"></div><div class=\"v\"></div><div class=\"box\"></div><div class=\"ro\"></div>";
2377
- const h = crosshair.querySelector(".h");
2378
- const v = crosshair.querySelector(".v");
2379
- const box = crosshair.querySelector(".box");
2380
- const readout = crosshair.querySelector(".ro");
2381
- const outline = doc.createElement("div");
2382
- outline.className = "pb-outline";
2383
- outline.innerHTML = "<span class=\"lab\"></span>";
2384
- const lab = outline.querySelector(".lab");
2385
- function setOutlineRect(rect, scroll) {
2386
- outline.style.left = `${rect.left + scroll.x - 5}px`;
2387
- outline.style.top = `${rect.top + scroll.y - 5}px`;
2388
- outline.style.width = `${rect.width + 10}px`;
2389
- outline.style.height = `${rect.height + 10}px`;
2390
- }
2391
- return {
2392
- crosshair,
2393
- outline,
2394
- move(pos) {
2395
- h.style.top = `${pos.clientY}px`;
2396
- v.style.left = `${pos.clientX}px`;
2397
- box.style.left = `${pos.clientX}px`;
2398
- box.style.top = `${pos.clientY}px`;
2399
- readout.style.left = `${pos.clientX}px`;
2400
- readout.style.top = `${pos.clientY}px`;
2401
- readout.textContent = `${Math.round(pos.pageX)} × ${Math.round(pos.pageY)}`;
2402
- },
2403
- snap(rect, label, scroll) {
2404
- if (!outline.classList.contains("on")) {
2405
- outline.style.transition = "none";
2406
- setOutlineRect(rect, scroll);
2407
- outline.offsetWidth;
2408
- outline.style.transition = "";
2409
- } else setOutlineRect(rect, scroll);
2410
- lab.textContent = label;
2411
- outline.classList.add("on");
2412
- },
2413
- release() {
2414
- outline.classList.remove("on");
2415
- }
2416
- };
2417
- }
2418
- //#endregion
2419
3326
  //#region src/ui/shortcuts.ts
3327
+ /** The action table's keyed entries, plus the composer chord the table cannot know about. */
2420
3328
  const ROWS = [
2421
- ["Drop a pin", "P"],
2422
- ["Open inbox", "I"],
2423
- ["Toggle theme", "D"],
3329
+ ...ACTIONS.filter((a) => a.key !== void 0 && a.help !== false).map((a) => [a.label, keyLabelOf(a)]),
2424
3330
  ["Send comment", "⌘ ↵"],
2425
- ["Mark pin resolved", "R"],
2426
- ["Copy open pins", "C"],
2427
- ["Hide / show pins", "H"],
2428
- ["Minimize toolbar", "M"],
2429
- ["Cancel", "ESC"]
3331
+ ["Move toolbar", "DRAG ⋮"],
3332
+ ["Reset toolbar position", "2× GRIP"]
2430
3333
  ];
2431
3334
  function createShortcutsModal(doc, onClose) {
2432
3335
  const root = doc.createElement("div");
2433
3336
  root.className = "pb-modal";
2434
3337
  root.hidden = true;
2435
- root.innerHTML = `<div class="mx"><div class="mh">SHORTCUTS</div><div style="padding:8px 20px 18px">${ROWS.map(([what, key]) => `<div class="mr"><span class="mw">${esc(what)}</span><span class="mk">${esc(key)}</span></div>`).join("")}</div></div>`;
3338
+ root.innerHTML = `<div class="mx"><div class="mh">SHORTCUTS</div><div style="padding:8px 20px 18px">${ROWS.map(([what, key]) => `<div class="mr"><span class="mw">${esc(what)}</span><span class="mk">${esc(key)}</span></div>`).join("")}</div><div class="mf">Shortcuts need the page focused. Inside an embedded frame, click the page first.</div></div>`;
2436
3339
  root.addEventListener("click", onClose);
2437
3340
  return {
2438
3341
  root,
@@ -2492,8 +3395,10 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2492
3395
  @keyframes pb-pulse { 0%,100% { opacity:.3 } 50% { opacity:1 } }
2493
3396
  @keyframes pb-resolve { to { opacity:0; transform:translateY(-10px) } }
2494
3397
 
2495
- /* overlay layer at the document origin */
2496
- .pb-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 0; }
3398
+ /* overlay layer in VIEWPORT space: fixed, re-laid out on every scroll/resize frame (element.ts).
3399
+ Document-space it drifted inner scroll containers, sticky anchors and any transformed
3400
+ ancestor of the host all broke the "page scrolls on window from the origin" assumption. */
3401
+ .pb-overlay { position: fixed; inset: 0; pointer-events: none; }
2497
3402
 
2498
3403
  .pb-outline { position: absolute; z-index: 30; pointer-events: none; border: 1px solid var(--pb-amber); border-radius: 2px; background: var(--pb-amber-soft); opacity: 0;
2499
3404
  transition: left 220ms var(--pb-ease), top 220ms var(--pb-ease), width 220ms var(--pb-ease), height 220ms var(--pb-ease), opacity 150ms linear; }
@@ -2527,7 +3432,7 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2527
3432
  .pb-aim .bar .cancel { flex: none; padding: 0 18px; border: 1px solid var(--pb-line-2); background: transparent; color: var(--pb-fg2); }
2528
3433
  .pb-aim .bar .ok { flex: none; padding: 0 20px; border: none; background: var(--pb-amber); color: var(--pb-amber-ink); }
2529
3434
 
2530
- .pb-pin { position: absolute; }
3435
+ .pb-pin { position: absolute; pointer-events: auto; }
2531
3436
  .pb-pin.resolving { animation: pb-resolve 380ms var(--pb-ease) forwards; }
2532
3437
  .pb-pin .ring { position: absolute; left: 0; top: 0; width: 26px; height: 26px; border: 1px solid var(--pb-amber); border-radius: 999px; animation: pb-ring 900ms var(--pb-ease) forwards; pointer-events: none; }
2533
3438
  .pb-pin .dot { position: absolute; left: -3px; top: -3px; width: 7px; height: 7px; border-radius: 999px; background: var(--pb-amber); box-shadow: 0 0 0 2px var(--pb-canvas); }
@@ -2539,11 +3444,19 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2539
3444
  .pb-chipBtn .lk { display: flex; align-items: center; gap: 5px; padding-left: 6px; margin-left: 1px; border-left: 1px solid var(--pb-line-2); font-size: 9.5px; letter-spacing: .02em; opacity: .85; }
2540
3445
  .pb-pin.hot .pb-chipBtn .lk { border-left-color: color-mix(in srgb, var(--pb-amber-ink) 28%, transparent); }
2541
3446
  .pb-pin.queued .pb-chipBtn { border-style: dashed; }
3447
+ .pb-pin.stale:not(.hot) .pb-chipBtn { border-color: var(--pb-amber); }
3448
+ .pb-pin.stale:not(.hot) .pb-chipBtn .qd { color: var(--pb-amber); }
3449
+ /* comment pins: muted, an N glyph; hot state stays amber so the active one is unmistakable */
3450
+ .pb-pin.note .dot { background: var(--pb-fg3); }
3451
+ .pb-pin.note .needle { background: linear-gradient(to top, var(--pb-fg3), color-mix(in srgb, var(--pb-fg3) 35%, transparent)); }
3452
+ .pb-pin.note:not(.hot) .pb-chipBtn { color: var(--pb-fg2); border-color: var(--pb-line); }
3453
+ .pb-chipBtn .nt { display: flex; align-items: center; justify-content: center; width: 14px; height: 14px; border-radius: 2px; background: var(--pb-fg3); color: var(--pb-canvas); font-size: 8.5px; letter-spacing: 0; }
3454
+ .pb-pin.hot .pb-chipBtn .nt { background: var(--pb-amber-ink); color: var(--pb-amber); }
2542
3455
  .pb-chipBtn .qd { padding-left: 6px; margin-left: 1px; border-left: 1px solid var(--pb-line-2); font-size: 9px; letter-spacing: .12em; color: var(--pb-amber); }
2543
3456
  .pb-pin.hot .pb-chipBtn .qd { color: var(--pb-amber-ink); border-left-color: color-mix(in srgb, var(--pb-amber-ink) 28%, transparent); }
2544
3457
 
2545
3458
  /* thread card (ui/card.ts) — prototype lines 121–190 */
2546
- .pb-card { position: absolute; z-index: 80; width: 344px; }
3459
+ .pb-card { position: absolute; z-index: 80; width: 344px; pointer-events: auto; }
2547
3460
  .pb-card .in { animation: pb-in 260ms var(--pb-ease) both; background: var(--pb-elev); border: 1px solid var(--pb-line-2); border-radius: 4px; box-shadow: var(--pb-shadow); overflow: hidden; }
2548
3461
  .pb-hd { display: flex; align-items: center; justify-content: space-between; padding: 10px 12px; border-bottom: 1px solid var(--pb-line); background: var(--pb-surface); }
2549
3462
  .pb-hd .meta { display: flex; align-items: center; gap: 9px; font-family: var(--pb-font-mono); font-size: 10px; letter-spacing: .18em; color: var(--pb-fg3); }
@@ -2592,6 +3505,17 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2592
3505
  .pb-change .ft { display: flex; align-items: center; gap: 8px; padding: 9px 10px; background: var(--pb-surface); border-top: 1px solid var(--pb-line); }
2593
3506
  .pb-change .applied { font-family: var(--pb-font-mono); font-size: 9.5px; letter-spacing: .16em; color: var(--pb-ok); display: flex; align-items: center; gap: 8px; }
2594
3507
  .pb-change .applied .hh { color: var(--pb-fg4); }
3508
+ .pb-stale { display: flex; align-items: center; gap: 8px; padding: 9px 12px; background: color-mix(in srgb, var(--pb-amber) 8%, var(--pb-surface)); border-top: 1px solid var(--pb-line); font-size: 11.5px; color: var(--pb-fg2); }
3509
+ .pb-stale .msg { flex: 1; min-width: 0; }
3510
+ .pb-typing.quiet .lbl { color: var(--pb-fg3); }
3511
+ .pb-dfoot { padding: 10px 16px; border-top: 1px solid var(--pb-line); display: flex; justify-content: flex-end; }
3512
+ .pb-resnote { padding: 8px 12px; font-size: 11.5px; line-height: 1.45; color: var(--pb-fg2); border-top: 1px solid var(--pb-line); }
3513
+ .pb-resnote .hh { font-family: var(--pb-font-mono); font-size: 10px; color: var(--pb-fg3); }
3514
+ .pb-seg { display: flex; margin-right: auto; border: 1px solid var(--pb-line-2); border-radius: 2px; overflow: hidden; }
3515
+ .pb-seg button { height: 24px; padding: 0 9px; font-size: 10.5px; color: var(--pb-fg3); transition: background 120ms linear, color 120ms linear; }
3516
+ .pb-seg button + button { border-left: 1px solid var(--pb-line-2); }
3517
+ .pb-seg button:hover { color: var(--pb-fg1); }
3518
+ .pb-seg button.on { background: var(--pb-hover); color: var(--pb-fg1); }
2595
3519
  .pb-verify { display: flex; align-items: center; gap: 8px; padding: 9px 12px; background: var(--pb-surface); border-top: 1px solid var(--pb-line); }
2596
3520
  .pb-bt-solid { height: 26px; padding: 0 13px; border-radius: 2px; background: var(--pb-invert-bg); color: var(--pb-invert-fg); font-size: 11.5px; }
2597
3521
  .pb-bt-solid:hover { opacity: .9; }
@@ -2607,6 +3531,11 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2607
3531
 
2608
3532
  /* command bar */
2609
3533
  .pb-bar { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); z-index: 90; display: flex; align-items: center; height: 46px; padding: 0 6px; gap: 3px; background: var(--pb-bar); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); border: 1px solid var(--pb-line-2); border-radius: 4px; box-shadow: var(--pb-shadow); }
3534
+ /* Dragged once: explicit left/top (inline) replace the bottom-centre default. */
3535
+ .pb-bar.free { bottom: auto; transform: none; }
3536
+ .pb-bar .grip { display: flex; align-items: center; justify-content: center; width: 14px; height: 32px; margin-left: 2px; color: var(--pb-fg4); cursor: grab; touch-action: none; border-radius: 2px; }
3537
+ .pb-bar .grip:hover { color: var(--pb-fg2); background: var(--pb-hover); }
3538
+ .pb-bar.dragging .grip { cursor: grabbing; }
2610
3539
  .pb-bar .armed-ring { position: absolute; inset: -1px; border: 1px solid var(--pb-amber); border-radius: 4px; box-shadow: 0 0 32px var(--pb-amber-soft); pointer-events: none; animation: pb-fade 200ms ease-out both; display: none; }
2611
3540
  :host([data-placing]) .pb-bar .armed-ring { display: block; }
2612
3541
  .pb-bar .ident { display: flex; align-items: center; gap: 9px; padding: 0 12px 0 10px; min-width: 150px; }
@@ -2626,8 +3555,18 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2626
3555
  .pb-tab { padding: 0 0 10px; white-space: nowrap; font-family: var(--pb-font-mono); font-size: 10px; letter-spacing: .18em; color: var(--pb-fg3); border-bottom: 1px solid transparent; }
2627
3556
  .pb-tab.on { color: var(--pb-fg1); border-bottom-color: var(--pb-amber); }
2628
3557
  .pb-items { flex: 1; overflow: auto; }
2629
- .pb-item { width: 100%; text-align: left; display: flex; gap: 11px; padding: 14px 16px; border-bottom: 1px solid var(--pb-line); }
3558
+ .pb-item { display: flex; align-items: flex-start; border-bottom: 1px solid var(--pb-line); }
2630
3559
  .pb-item:hover { background: var(--pb-hover); }
3560
+ .pb-item-main { flex: 1; min-width: 0; text-align: left; display: flex; gap: 11px; padding: 14px 0 14px 16px; }
3561
+ /* Row actions show on hover/focus; always on touch, where there is no hover. */
3562
+ .pb-item .acts { display: flex; flex-direction: column; gap: 2px; padding: 12px 10px 0 6px; opacity: 0; transition: opacity 120ms linear; }
3563
+ .pb-item:hover .acts, .pb-item:focus-within .acts { opacity: 1; }
3564
+ @media (hover: none) { .pb-item .acts { opacity: 1; } }
3565
+ .pb-group { display: flex; align-items: center; gap: 8px; padding: 8px 16px; background: color-mix(in srgb, var(--pb-info) 7%, var(--pb-surface)); border-bottom: 1px solid var(--pb-line); font-family: var(--pb-font-mono); font-size: 9.5px; letter-spacing: .14em; color: var(--pb-fg2); }
3566
+ .pb-group .gr { color: var(--pb-fg1); }
3567
+ .pb-group .sp { flex: 1; }
3568
+ .pb-gres { height: 22px; padding: 0 8px; border: 1px solid var(--pb-line-2); border-radius: 2px; font-family: var(--pb-font-mono); font-size: 9px; letter-spacing: .14em; color: var(--pb-fg1); transition: color 120ms linear, border-color 120ms linear; }
3569
+ .pb-gres:hover, .pb-gres.confirm { border-color: var(--pb-ok); color: var(--pb-ok); }
2631
3570
  .pb-item .nn { flex: none; display: flex; align-items: center; justify-content: center; min-width: 24px; height: 20px; border-radius: 2px; border: 1px solid var(--pb-line-2); color: var(--pb-fg2); font-family: var(--pb-font-mono); font-size: 10px; letter-spacing: .06em; }
2632
3571
  .pb-item.on .nn { background: var(--pb-amber); color: var(--pb-amber-ink); border-color: var(--pb-amber); }
2633
3572
  .pb-item .cc { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
@@ -2685,6 +3624,7 @@ button { font: inherit; color: inherit; background: none; border: 0; cursor: poi
2685
3624
  .pb-modal .mh { padding: 18px 20px 14px; border-bottom: 1px solid var(--pb-line); font-family: var(--pb-font-mono); font-size: 10px; letter-spacing: .24em; }
2686
3625
  .pb-modal .mr { display: flex; align-items: center; justify-content: space-between; padding: 9px 0; border-bottom: 1px solid var(--pb-line); }
2687
3626
  .pb-modal .mw { font-size: 13px; letter-spacing: -.005em; color: var(--pb-fg2); }
3627
+ .pb-modal .mf { padding: 0 20px 16px; font-size: 10.5px; color: var(--pb-fg2); }
2688
3628
  .pb-modal .mk { display: flex; align-items: center; justify-content: center; min-width: 26px; height: 22px; padding: 0 7px; border: 1px solid var(--pb-line-2); border-radius: 2px; background: var(--pb-sunken); font-family: var(--pb-font-mono); font-size: 10.5px; }
2689
3629
 
2690
3630
  [hidden] { display: none !important; }
@@ -2699,13 +3639,9 @@ const PAGE_PLACING_CLASS = "pinbox-placing";
2699
3639
  const PAGE_CSS = `body.${PAGE_PLACING_CLASS}, body.${PAGE_PLACING_CLASS} * { cursor: none !important; }`;
2700
3640
  //#endregion
2701
3641
  //#region src/element.ts
3642
+ /** How long a pin commit waits for its picture before shipping without one. */
3643
+ const CAPTURE_TIMEOUT_MS = 4e3;
2702
3644
  const BaseElement = globalThis.HTMLElement ?? class {};
2703
- /** Keystrokes are ignored while a text control has focus (prototype line 702–703). */
2704
- function isTextEntry(target) {
2705
- const el = target;
2706
- const tag = el?.tagName ?? "";
2707
- return tag === "TEXTAREA" || tag === "INPUT" || el?.isContentEditable === true;
2708
- }
2709
3645
  var PinboxToolbarElement = class extends BaseElement {
2710
3646
  static tagName = "pinbox-toolbar";
2711
3647
  /** Watched so a config that arrives after insertion can still start the transport. */
@@ -2727,28 +3663,31 @@ var PinboxToolbarElement = class extends BaseElement {
2727
3663
  #token = "";
2728
3664
  #built = false;
2729
3665
  #bar = null;
2730
- #reticle = null;
2731
3666
  #pinsLayer = null;
2732
3667
  #drawer = null;
2733
- #aim = null;
2734
- /** Pending viewport-refresh frame, 0 when none is queued. */
2735
- #viewportFrame = 0;
3668
+ /** Reticle, drag-aim and multi-target capture — see placement.ts. */
3669
+ #placement = null;
2736
3670
  #modal = null;
2737
3671
  #minUi = null;
2738
3672
  #min = null;
3673
+ /** The bar's grip drag; same lifetime as the minimize controller. */
3674
+ #barDrag = null;
2739
3675
  /** SPA view watcher: DOM/history changes re-run the anchor-gated render. */
2740
3676
  #anchors = null;
2741
3677
  #helpOpen = false;
3678
+ /** The 30 s wall-clock tick that ages pending pins into WAITING / NO RESPONSE. 0 when idle. */
3679
+ #clockTimer = 0;
3680
+ /** Pending viewport re-layout frame, 0 when none is queued. */
3681
+ #layoutFrame = 0;
3682
+ #resizeObserver = null;
2742
3683
  #pageStyle = null;
2743
3684
  #unsubscribe = null;
2744
- #hover = null;
2745
- /** Shift+click accumulation while placing — extra loci for ONE pending pin. */
2746
- #extraTargets = [];
2747
3685
  /** Card → element: send/verify/resolve forward to the transport seam; close dismisses. */
2748
3686
  #cardActions = {
2749
- send: (pinId, text) => this.actions.send?.(pinId, text),
3687
+ send: (pinId, text, kind) => this.actions.send?.(pinId, text, kind),
2750
3688
  verify: (pinId, outcome) => this.actions.verify?.(pinId, outcome),
2751
3689
  resolve: (pinId) => this.actions.resolve?.(pinId),
3690
+ nudge: (pinId) => this.#nudge(pinId),
2752
3691
  copy: (pinId) => this.#copyPin(pinId),
2753
3692
  close: () => this.#dismiss()
2754
3693
  };
@@ -2772,6 +3711,32 @@ var PinboxToolbarElement = class extends BaseElement {
2772
3711
  this.#built = true;
2773
3712
  this.#build();
2774
3713
  }
3714
+ this.#applyPageDefaults();
3715
+ if (this.shadowRoot) this.#placement?.connect(this.shadowRoot);
3716
+ if (this.#min === null) this.#mountMinimize();
3717
+ if (this.#barDrag === null) this.#mountBarDrag();
3718
+ this.#anchors = watchAnchors(window, () => this.#render(this.store.get()));
3719
+ this.#listen();
3720
+ this.#unsubscribe = this.store.subscribe((s) => this.#render(s));
3721
+ this.#render(this.store.get());
3722
+ this.#startClock();
3723
+ this.store.update({ captureMode: this.#loadCaptureMode() });
3724
+ this.#queueStart();
3725
+ }
3726
+ /** Persisted per endpoint beside the puck dock; PinboxConfig.capture is the first-run default. */
3727
+ #loadCaptureMode() {
3728
+ const key = captureKey(`pinbox:${this.config?.endpoint ?? ""}`);
3729
+ return loadCaptureMode(globalThis.localStorage, key, this.config?.capture ?? "dom");
3730
+ }
3731
+ #toggleCapture() {
3732
+ const next = this.store.get().captureMode === "tab" ? "dom" : "tab";
3733
+ this.store.update({ captureMode: next });
3734
+ if (next === "dom") releaseCapture();
3735
+ saveCaptureMode(globalThis.localStorage, captureKey(`pinbox:${this.config?.endpoint ?? ""}`), next);
3736
+ return true;
3737
+ }
3738
+ /** Theme from the OS when the host set none; the page-level CSS (placing cursor) into <head>. */
3739
+ #applyPageDefaults() {
2775
3740
  if (!this.hasAttribute("data-pb")) {
2776
3741
  const dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
2777
3742
  this.setAttribute("data-pb", dark ? "dark" : "light");
@@ -2780,17 +3745,37 @@ var PinboxToolbarElement = class extends BaseElement {
2780
3745
  style.textContent = PAGE_CSS;
2781
3746
  document.head.appendChild(style);
2782
3747
  this.#pageStyle = style;
2783
- if (this.#aim === null) this.#mountAim();
2784
- if (this.#min === null) this.#mountMinimize();
2785
- this.#anchors = watchAnchors(window, () => this.#render(this.store.get()));
2786
- document.addEventListener("mousemove", this.#onMouseMove);
2787
- window.addEventListener("scroll", this.#onViewportChange, { passive: true });
2788
- window.addEventListener("resize", this.#onViewportChange);
3748
+ }
3749
+ #mountBarDrag() {
3750
+ if (this.#bar === null) return;
3751
+ this.#barDrag = createBarDrag({
3752
+ win: window,
3753
+ bar: this.#bar.root,
3754
+ grip: this.#bar.grip,
3755
+ storage: globalThis.localStorage ?? null,
3756
+ storagePrefix: `pinbox:${this.config?.endpoint ?? ""}`
3757
+ });
3758
+ }
3759
+ /** The page-level listeners of one connected lifetime; disconnectedCallback removes them. */
3760
+ #listen() {
2789
3761
  document.addEventListener("click", this.#onClickCapture, true);
2790
- document.addEventListener("keydown", this.#onKeyDown);
2791
- this.#unsubscribe = this.store.subscribe((s) => this.#render(s));
2792
- this.#render(this.store.get());
2793
- this.#queueStart();
3762
+ window.addEventListener("keydown", this.#onKeyDown, true);
3763
+ document.addEventListener("scroll", this.#onLayoutChange, {
3764
+ capture: true,
3765
+ passive: true
3766
+ });
3767
+ window.addEventListener("resize", this.#onLayoutChange);
3768
+ const RO = globalThis.ResizeObserver;
3769
+ if (typeof RO === "function") {
3770
+ this.#resizeObserver = new RO(this.#onLayoutChange);
3771
+ this.#resizeObserver.observe(document.body);
3772
+ }
3773
+ }
3774
+ /** Age is state (state.ts `clock`), so a tick is a render and stale pins flip without a hub event. */
3775
+ #startClock() {
3776
+ const tick = () => this.store.update({ clock: Date.now() });
3777
+ tick();
3778
+ this.#clockTimer = window.setInterval(tick, 3e4);
2794
3779
  }
2795
3780
  /**
2796
3781
  * Late-config rescue: an element inserted BEFORE its hub/token attributes were
@@ -2819,45 +3804,30 @@ var PinboxToolbarElement = class extends BaseElement {
2819
3804
  this.#lifetime += 1;
2820
3805
  this.#transport?.close();
2821
3806
  this.#transport = null;
2822
- document.removeEventListener("mousemove", this.#onMouseMove);
2823
- window.removeEventListener("scroll", this.#onViewportChange);
2824
- window.removeEventListener("resize", this.#onViewportChange);
2825
3807
  document.removeEventListener("click", this.#onClickCapture, true);
2826
- document.removeEventListener("keydown", this.#onKeyDown);
2827
- if (this.#viewportFrame !== 0) cancelAnimationFrame(this.#viewportFrame);
2828
- this.#viewportFrame = 0;
2829
- this.#aim?.destroy();
2830
- this.#aim = null;
3808
+ window.removeEventListener("keydown", this.#onKeyDown, true);
3809
+ document.removeEventListener("scroll", this.#onLayoutChange, { capture: true });
3810
+ window.removeEventListener("resize", this.#onLayoutChange);
3811
+ this.#resizeObserver?.disconnect();
3812
+ this.#resizeObserver = null;
3813
+ if (this.#layoutFrame !== 0) cancelAnimationFrame(this.#layoutFrame);
3814
+ this.#layoutFrame = 0;
3815
+ this.#placement?.disconnect();
2831
3816
  this.#min?.destroy();
2832
3817
  this.#min = null;
3818
+ this.#barDrag?.destroy();
3819
+ this.#barDrag = null;
2833
3820
  releaseCapture();
2834
3821
  this.#anchors?.destroy();
2835
3822
  this.#anchors = null;
2836
3823
  this.#unsubscribe?.();
2837
3824
  this.#unsubscribe = null;
3825
+ window.clearInterval(this.#clockTimer);
3826
+ this.#clockTimer = 0;
2838
3827
  this.#pageStyle?.remove();
2839
3828
  this.#pageStyle = null;
2840
3829
  document.body.classList.remove(PAGE_PLACING_CLASS);
2841
3830
  }
2842
- /**
2843
- * Create the aim controller and put its layer in the shadow root.
2844
- *
2845
- * Separate from `#build` because the two have different lifetimes: `#build` runs once, but
2846
- * `disconnectedCallback` tears this controller's window listeners down. A re-parented element
2847
- * would otherwise come back with no controller and its markup still in place — a grip that
2848
- * renders and does nothing, with no error to explain it.
2849
- */
2850
- #mountAim() {
2851
- const shadow = this.shadowRoot;
2852
- if (!shadow) return;
2853
- shadow.querySelector(".pb-aim")?.remove();
2854
- this.#aim = createAim(document, {
2855
- onAim: (x, y) => this.#probe(x, y),
2856
- onConfirm: () => this.#confirmAim(),
2857
- onCancel: () => this.#dismiss()
2858
- });
2859
- shadow.appendChild(this.#aim.root);
2860
- }
2861
3831
  #build() {
2862
3832
  const shadow = this.attachShadow({ mode: "open" });
2863
3833
  try {
@@ -2873,22 +3843,21 @@ var PinboxToolbarElement = class extends BaseElement {
2873
3843
  overlay.className = "pb-overlay";
2874
3844
  this.#pinsLayer = document.createElement("div");
2875
3845
  overlay.appendChild(this.#pinsLayer);
2876
- this.#reticle = createReticle(document);
2877
- overlay.appendChild(this.#reticle.outline);
3846
+ this.#placement = createPlacement({
3847
+ win: window,
3848
+ host: this,
3849
+ store: this.store,
3850
+ pinsLayer: this.#pinsLayer,
3851
+ onCancel: () => this.#dismiss()
3852
+ });
3853
+ overlay.appendChild(this.#placement.outline);
2878
3854
  const card = document.createElement("div");
2879
3855
  card.className = "pb-card";
2880
3856
  card.hidden = true;
2881
3857
  overlay.appendChild(card);
2882
3858
  shadow.appendChild(overlay);
2883
- shadow.appendChild(this.#reticle.crosshair);
2884
- this.#bar = createBar(document, {
2885
- onPin: () => this.#togglePlacing(),
2886
- onInbox: () => this.store.update({ inboxOpen: !this.store.get().inboxOpen }),
2887
- onTheme: () => this.#toggleTheme(),
2888
- onHelp: () => this.#toggleHelp(),
2889
- onCopy: () => this.#copyOpenPins(),
2890
- onMinimize: (keyboard) => this.minimize(keyboard)
2891
- });
3859
+ shadow.appendChild(this.#placement.crosshair);
3860
+ this.#bar = createBar(document, { onAction: (id, keyboard) => this.#runAction(id, keyboard) });
2892
3861
  shadow.appendChild(this.#bar.root);
2893
3862
  this.#minUi = createMinimizeUi(document);
2894
3863
  shadow.appendChild(this.#minUi.morphWrap);
@@ -2896,10 +3865,11 @@ var PinboxToolbarElement = class extends BaseElement {
2896
3865
  shadow.appendChild(this.#minUi.fan);
2897
3866
  this.#drawer = createDrawer(document, {
2898
3867
  onActivate: (pinId) => this.#activateFromInbox(pinId),
2899
- onClose: () => this.store.update({ inboxOpen: false })
3868
+ onClose: () => this.store.update({ inboxOpen: false }),
3869
+ onResolve: (pinId, note) => this.actions.resolve?.(pinId, note),
3870
+ onUnresolve: (pinId) => this.actions.verify?.(pinId, "reopened")
2900
3871
  });
2901
3872
  shadow.appendChild(this.#drawer.root);
2902
- this.#mountAim();
2903
3873
  this.#modal = createShortcutsModal(document, () => this.#setHelp(false));
2904
3874
  shadow.appendChild(this.#modal.root);
2905
3875
  this.#pinsLayer.addEventListener("click", (e) => this.#onChipClick(e));
@@ -2919,12 +3889,7 @@ var PinboxToolbarElement = class extends BaseElement {
2919
3889
  reduced: window.matchMedia("(prefers-reduced-motion: reduce)").matches,
2920
3890
  initialMinimized: this.config?.minimized === true,
2921
3891
  onSettled: (minimized, keyboard) => this.#onMinimizeSettled(minimized, keyboard),
2922
- onFanAction: (action) => {
2923
- if (action === "pin") this.#togglePlacing();
2924
- else if (action === "inbox") this.#toggleInbox();
2925
- else if (action === "hide") this.#togglePinsHidden();
2926
- else this.#toggleTheme();
2927
- }
3892
+ onFanAction: (action) => this.#runAction(action, false)
2928
3893
  });
2929
3894
  this.#min.applyInitial();
2930
3895
  }
@@ -2970,6 +3935,7 @@ var PinboxToolbarElement = class extends BaseElement {
2970
3935
  onEvent: (e) => applyHubEvent(this.store, e),
2971
3936
  onConnection: (connection) => this.store.update({ connection }),
2972
3937
  onPins: (pins) => this.store.update({ pins }),
3938
+ onSessions: (sessions) => this.store.update({ agentLive: agentIsLive(sessions, Date.now()) }),
2973
3939
  onOutbox: (ids) => this.store.update({ queuedIds: new Set(ids) })
2974
3940
  });
2975
3941
  this.#transport = transport;
@@ -2977,8 +3943,8 @@ var PinboxToolbarElement = class extends BaseElement {
2977
3943
  const seed = [...transport.mirrorPins(), ...queued];
2978
3944
  if (seed.length > 0 && this.store.get().pins.length === 0) this.store.update({ pins: seed });
2979
3945
  if (queued.length > 0) this.store.update({ queuedIds: new Set(queued.map((p) => p.id)) });
2980
- this.actions.send = (pinId, text) => void this.#send(transport, pinId, text);
2981
- this.actions.resolve = (pinId) => void transport.resolve(pinId).then((pin) => upsertPin(this.store, pin)).catch(() => {});
3946
+ this.actions.send = (pinId, text, kind) => void this.#send(transport, pinId, text, kind);
3947
+ this.actions.resolve = (pinId, note) => void transport.resolve(pinId, note).then((pin) => upsertPin(this.store, pin)).catch(() => {});
2982
3948
  this.actions.verify = (pinId, outcome) => void transport.verify(pinId, outcome).then((pin) => {
2983
3949
  upsertPin(this.store, pin);
2984
3950
  if (outcome === "accepted") this.#dismiss();
@@ -2986,14 +3952,14 @@ var PinboxToolbarElement = class extends BaseElement {
2986
3952
  transport.connect();
2987
3953
  }
2988
3954
  /** draft ⇒ compose PinInput (+ best-effort screenshot) and createPin; else thread reply. */
2989
- async #send(transport, pinId, text) {
3955
+ async #send(transport, pinId, text, kind) {
2990
3956
  try {
2991
3957
  if (pinId === "draft") {
2992
3958
  const draft = this.store.get().draft;
2993
3959
  if (draft === null) return;
2994
3960
  const input = {
2995
3961
  text,
2996
- kind: "note",
3962
+ kind,
2997
3963
  target: draft.target.target,
2998
3964
  env: draft.target.env,
2999
3965
  author: { userId: transport.consumerId }
@@ -3004,7 +3970,11 @@ var PinboxToolbarElement = class extends BaseElement {
3004
3970
  } else appendThreadMessage(this.store, await transport.reply(pinId, text));
3005
3971
  } catch {}
3006
3972
  }
3007
- /** Best-effort element screenshot: draft submit → captureElement → uploadAttachment. */
3973
+ /**
3974
+ * Best-effort element screenshot: draft submit → capture → uploadAttachment. The capture is
3975
+ * bounded — a slow rasterize or a prompt left hanging must not hold the pin hostage, so past
3976
+ * CAPTURE_TIMEOUT_MS the pin ships without pixels (structured capture still carries it).
3977
+ */
3008
3978
  async #screenshot(selector) {
3009
3979
  const cfg = this.config;
3010
3980
  if (cfg === null) return null;
@@ -3012,7 +3982,9 @@ var PinboxToolbarElement = class extends BaseElement {
3012
3982
  try {
3013
3983
  const el = document.querySelector(selector);
3014
3984
  if (el === null) return null;
3015
- const img = await captureElement(el);
3985
+ const capture = this.store.get().captureMode === "tab" ? captureElement(el) : captureElementDom(el);
3986
+ const timeout = new Promise((resolve) => window.setTimeout(() => resolve(null), CAPTURE_TIMEOUT_MS));
3987
+ const img = await Promise.race([capture, timeout]);
3016
3988
  if (img === null) return null;
3017
3989
  return await uploadAttachment(cfg.endpoint, this.#token, img);
3018
3990
  } catch {
@@ -3034,21 +4006,33 @@ var PinboxToolbarElement = class extends BaseElement {
3034
4006
  const pin = this.store.get().pins.find((p) => p.id === pinId);
3035
4007
  this.#ensureThread(pinId);
3036
4008
  this.store.update({ activePinId: pinId });
3037
- const rect = pin?.target?.rect;
4009
+ const rect = pin === void 0 ? null : anchorRect(document, pin);
3038
4010
  if (rect) {
3039
- const y = rect.y + rect.height / 2;
4011
+ const y = window.scrollY + rect.y + rect.height / 2;
3040
4012
  window.scrollTo({
3041
4013
  top: Math.max(0, y - window.innerHeight / 2),
3042
4014
  behavior: "smooth"
3043
4015
  });
3044
4016
  }
3045
4017
  }
4018
+ /**
4019
+ * Nudge a stale pin: re-post the last human message as a new thread message. A watcher that
4020
+ * missed the original (crashed, restarted, registered late) gets a fresh event to wake on.
4021
+ */
4022
+ #nudge(pinId) {
4023
+ const state = this.store.get();
4024
+ const pin = state.pins.find((p) => p.id === pinId);
4025
+ if (pin === void 0) return;
4026
+ const last = [...state.threads.get(pinId) ?? []].reverse().find((m) => m.role === "human");
4027
+ this.actions.send?.(pinId, last?.text ?? pin.text, "note");
4028
+ }
3046
4029
  /** The markdown offline fallback: copy every open pin's block to the clipboard. */
3047
4030
  #copyOpenPins() {
3048
4031
  const state = this.store.get();
3049
4032
  try {
3050
4033
  navigator.clipboard.writeText(pinsToMarkdown(state.pins, state.threads));
3051
4034
  } catch {}
4035
+ return true;
3052
4036
  }
3053
4037
  /** The card's copy: exactly the pin you are looking at, thread included. */
3054
4038
  #copyPin(pinId) {
@@ -3061,6 +4045,7 @@ var PinboxToolbarElement = class extends BaseElement {
3061
4045
  }
3062
4046
  #togglePinsHidden() {
3063
4047
  this.store.update({ pinsHidden: !this.store.get().pinsHidden });
4048
+ return true;
3064
4049
  }
3065
4050
  #setHelp(open) {
3066
4051
  this.#helpOpen = open;
@@ -3068,6 +4053,7 @@ var PinboxToolbarElement = class extends BaseElement {
3068
4053
  }
3069
4054
  #toggleHelp() {
3070
4055
  this.#setHelp(!this.#helpOpen);
4056
+ return true;
3071
4057
  }
3072
4058
  /** Chip click toggles the pin active (prototype data-open delegation, line 675). */
3073
4059
  #onChipClick(e) {
@@ -3087,175 +4073,99 @@ var PinboxToolbarElement = class extends BaseElement {
3087
4073
  activePinId: null,
3088
4074
  pinsHidden: false
3089
4075
  });
4076
+ return true;
3090
4077
  }
3091
4078
  #toggleInbox() {
3092
4079
  this.store.update({ inboxOpen: !this.store.get().inboxOpen });
3093
- }
3094
- #resolveActive() {
3095
- const active = this.store.get().activePinId;
3096
- if (active) this.actions.resolve?.(active);
4080
+ return true;
3097
4081
  }
3098
4082
  #toggleTheme() {
3099
4083
  const next = this.getAttribute("data-pb") === "dark" ? "light" : "dark";
3100
4084
  this.setAttribute("data-pb", next);
4085
+ return true;
3101
4086
  }
3102
4087
  /** esc / click-away: leave placing, discard the draft (client-only), deactivate. */
3103
4088
  #dismiss() {
3104
4089
  this.#setHelp(false);
3105
- this.#clearExtraTargets();
3106
4090
  this.store.update({
3107
4091
  mode: "idle",
3108
4092
  activePinId: null
3109
4093
  });
3110
4094
  if (this.store.get().draft) this.store.discardDraft();
3111
4095
  }
3112
- /**
3113
- * Work out what sits under a viewport point and highlight it.
3114
- *
3115
- * Shared by both ways of aiming — following a mouse, and dragging the reticle — so the two can
3116
- * never disagree about what is under the crosshair.
3117
- */
3118
- #probe(clientX, clientY) {
3119
- const el = hitTest(document, clientX, clientY, (hit) => hit === this);
3120
- this.#hover = el;
3121
- if (el) this.#reticle?.snap(el.getBoundingClientRect(), targetLabel(el), {
3122
- x: window.scrollX,
3123
- y: window.scrollY
3124
- });
3125
- else this.#reticle?.release();
3126
- this.#aim?.setLabel(el ? targetLabel(el) : "NOTHING UNDER THE PIN");
3127
- }
3128
- /**
3129
- * Keep the drag-aim reticle honest while the viewport moves under it.
3130
- *
3131
- * Scrolling changes what is beneath a fixed reticle, and resizing (a phone rotating, a window
3132
- * dragged narrow) can both strand it off-screen and flip which way of aiming applies.
3133
- */
3134
- #onViewportChange = () => {
3135
- if (this.store.get().mode !== "placing" || this.#viewportFrame !== 0) return;
3136
- this.#viewportFrame = requestAnimationFrame(() => {
3137
- this.#viewportFrame = 0;
3138
- if (this.store.get().mode !== "placing") return;
3139
- this.#syncAim(true);
3140
- const aim = this.#aim;
3141
- if (aim?.root.classList.contains("on") === true) this.#probe(aim.point.x, aim.point.y);
3142
- });
3143
- };
3144
- #onMouseMove = (e) => {
3145
- if (this.store.get().mode !== "placing" || !this.#reticle) return;
3146
- this.#reticle.move(e);
3147
- this.#probe(e.clientX, e.clientY);
3148
- };
3149
- /** Commit the pin the drag-aim reticle is sitting on. */
3150
- #confirmAim() {
3151
- const aim = this.#aim;
3152
- if (!aim) return;
3153
- this.#probe(aim.point.x, aim.point.y);
3154
- const el = this.#hover ?? document.body;
3155
- this.store.place({
3156
- target: captureTarget(el, { at: {
3157
- x: aim.point.x + window.scrollX,
3158
- y: aim.point.y + window.scrollY
3159
- } }),
3160
- placedAt: {
3161
- x: aim.point.x + window.scrollX,
3162
- y: aim.point.y + window.scrollY
3163
- }
3164
- });
3165
- this.#reticle?.release();
3166
- }
3167
- /** Placement click: capture the hovered target (or body) into a client-only draft. */
3168
- #placeDraft(e) {
3169
- e.preventDefault();
3170
- e.stopPropagation();
3171
- const capture = captureTarget(this.#hover ?? document.body, { at: {
3172
- x: e.pageX,
3173
- y: e.pageY
3174
- } });
3175
- if (this.#extraTargets.length > 0) capture.target.targets = this.#extraTargets;
3176
- this.#clearExtraTargets();
3177
- this.store.place({
3178
- target: capture,
3179
- placedAt: {
3180
- x: e.pageX,
3181
- y: e.pageY
3182
- }
3183
- });
3184
- this.#reticle?.release();
3185
- }
3186
- /** Shift+click while placing: capture WITHOUT committing; a numbered dashed
3187
- * outline is the receipt. Plain click still commits (with these attached). */
3188
- #accumulateTarget(e) {
3189
- e.preventDefault();
3190
- e.stopPropagation();
3191
- const el = this.#hover ?? document.body;
3192
- this.#extraTargets = [...this.#extraTargets, captureTarget(el).target];
3193
- if (this.#pinsLayer) renderMultiMarks(this.#pinsLayer, this.#extraTargets);
3194
- }
3195
- #clearExtraTargets() {
3196
- if (this.#extraTargets.length === 0) return;
3197
- this.#extraTargets = [];
3198
- if (this.#pinsLayer) renderMultiMarks(this.#pinsLayer, []);
3199
- }
3200
4096
  #onClickCapture = (e) => {
3201
4097
  if (e.composedPath().includes(this)) return;
3202
4098
  const state = this.store.get();
3203
4099
  if (state.mode === "placing") {
3204
- if (needsDragAim(window)) return;
3205
- if (e.shiftKey) this.#accumulateTarget(e);
3206
- else this.#placeDraft(e);
4100
+ this.#placement?.handleClick(e);
3207
4101
  return;
3208
4102
  }
3209
4103
  if (state.inboxOpen) this.store.update({ inboxOpen: false });
3210
4104
  if (state.activePinId || state.draft) this.#dismiss();
3211
4105
  };
3212
- /** Prototype keyboard map (v2-command-bar.html lines 701–712) + M (v3 minimize). */
3213
- #shortcuts = {
4106
+ /**
4107
+ * One handler per action, for every surface: bar buttons, fan items and keys all name an
4108
+ * action from the table (ui/actions.ts). A handler returns false when nothing was there to act
4109
+ * on, so the key path can let the host have the keystroke (an Esc with nothing open is the
4110
+ * page's Esc; R with no active pin is the page's R).
4111
+ */
4112
+ #handlers = {
3214
4113
  escape: () => {
3215
- if (this.#min?.closeFan() === true) return;
4114
+ if (this.#min?.closeFan() === true) return true;
4115
+ const s = this.store.get();
4116
+ const open = s.mode === "placing" || s.activePinId !== null || s.draft !== null || this.#helpOpen;
3216
4117
  this.#dismiss();
4118
+ return open;
4119
+ },
4120
+ pin: () => this.#togglePlacing(),
4121
+ inbox: () => this.#toggleInbox(),
4122
+ theme: () => this.#toggleTheme(),
4123
+ copy: () => this.#copyOpenPins(),
4124
+ hide: () => this.#togglePinsHidden(),
4125
+ capture: () => this.#toggleCapture(),
4126
+ help: () => this.#toggleHelp(),
4127
+ resolve: () => {
4128
+ const active = this.store.get().activePinId;
4129
+ if (active === null) return false;
4130
+ this.actions.resolve?.(active);
4131
+ return true;
3217
4132
  },
3218
- p: () => this.#togglePlacing(),
3219
- i: () => this.#toggleInbox(),
3220
- d: () => this.#toggleTheme(),
3221
- r: () => this.#resolveActive(),
3222
- c: () => this.#copyOpenPins(),
3223
- h: () => this.#togglePinsHidden(),
3224
- m: () => this.#min?.minimized() === true ? this.restore(true) : this.minimize(true),
3225
- "?": () => this.#toggleHelp()
4133
+ minimize: (keyboard) => {
4134
+ if (this.#min?.minimized() === true) this.restore(keyboard);
4135
+ else this.minimize(keyboard);
4136
+ return true;
4137
+ }
3226
4138
  };
4139
+ #runAction(id, keyboard) {
4140
+ return this.#handlers[id](keyboard);
4141
+ }
3227
4142
  #onKeyDown = (e) => {
3228
- if (isTextEntry(e.composedPath()[0])) return;
3229
- this.#shortcuts[e.key === "?" ? "?" : e.key.toLowerCase()]?.();
4143
+ const id = shortcutFor(e, this.config?.shortcuts ?? "all");
4144
+ if (id === null) return;
4145
+ if (!this.#runAction(id, true)) return;
4146
+ e.preventDefault();
4147
+ e.stopPropagation();
3230
4148
  };
3231
4149
  /**
3232
- * Bring the drag-aim reticle up with placing mode, seeded mid-screen and already showing what it
3233
- * is over — so the first thing you see is a live target, not an empty crosshair waiting for a
3234
- * mouse that is never coming.
4150
+ * The viewport moved under the overlay (scroll, resize, layout shift): re-place what is
4151
+ * anchored to the page pins, the card, multi-target marks once per frame. Not a store
4152
+ * update: nothing about the pins changed, only where their anchors are on screen.
3235
4153
  */
3236
- #syncAim(placing) {
3237
- const aim = this.#aim;
3238
- if (!aim) return;
3239
- if (!placing || !needsDragAim(window)) {
3240
- aim.hide();
3241
- return;
3242
- }
3243
- if (aim.root.classList.contains("on")) {
3244
- if (aim.point.x <= window.innerWidth && aim.point.y <= window.innerHeight) return;
3245
- aim.show(Math.min(aim.point.x, window.innerWidth), Math.min(aim.point.y, window.innerHeight));
3246
- return;
3247
- }
3248
- const { x, y } = startPoint(window);
3249
- aim.show(x, y);
3250
- this.#probe(x, y);
3251
- }
4154
+ #onLayoutChange = () => {
4155
+ if (this.#layoutFrame !== 0) return;
4156
+ this.#layoutFrame = requestAnimationFrame(() => {
4157
+ this.#layoutFrame = 0;
4158
+ const state = this.store.get();
4159
+ if (this.#pinsLayer) renderPins(this.#pinsLayer, state);
4160
+ if (this.shadowRoot) renderCard(this.shadowRoot, state, this.#cardActions);
4161
+ this.#placement?.render(state.mode === "placing");
4162
+ });
4163
+ };
3252
4164
  #render(state) {
3253
4165
  const placing = state.mode === "placing";
3254
4166
  this.toggleAttribute("data-placing", placing);
3255
4167
  document.body.classList.toggle(PAGE_PLACING_CLASS, placing);
3256
- if (!placing) this.#clearExtraTargets();
3257
- if (!placing) this.#reticle?.release();
3258
- this.#syncAim(placing);
4168
+ this.#placement?.render(placing);
3259
4169
  if (this.#pinsLayer) renderPins(this.#pinsLayer, state);
3260
4170
  if (this.shadowRoot) renderCard(this.shadowRoot, state, this.#cardActions);
3261
4171
  this.#drawer?.update(state);