deictic 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/API.md +150 -37
  2. package/README.md +4 -3
  3. package/dist/annotations/client.d.ts +1 -1
  4. package/dist/annotations/client.d.ts.map +1 -1
  5. package/dist/annotations/client.js +161 -176
  6. package/dist/annotations/client.js.map +1 -1
  7. package/dist/annotations/index.d.ts +2 -11
  8. package/dist/client/index.d.ts +7 -6
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +1007 -192
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/index.d.ts +2 -2
  13. package/dist/recommended/index.d.ts +2 -2
  14. package/dist/recordings/client.d.ts.map +1 -1
  15. package/dist/recordings/client.js +82 -153
  16. package/dist/recordings/client.js.map +1 -1
  17. package/dist/screenshots/client.d.ts.map +1 -1
  18. package/dist/shared/annotations.js +3 -4
  19. package/dist/shared/annotations.js.map +1 -1
  20. package/dist/shared/board.js +1 -1
  21. package/dist/shared/client.js +45 -2
  22. package/dist/shared/client.js.map +1 -1
  23. package/dist/shared/component.js +62 -0
  24. package/dist/shared/component.js.map +1 -0
  25. package/dist/shared/dom.js +79 -0
  26. package/dist/shared/dom.js.map +1 -0
  27. package/dist/shared/drawer.js +217 -0
  28. package/dist/shared/drawer.js.map +1 -0
  29. package/dist/shared/endpoints.js +34 -8
  30. package/dist/shared/endpoints.js.map +1 -1
  31. package/dist/shared/find.js +2 -1
  32. package/dist/shared/find.js.map +1 -1
  33. package/dist/shared/index.d.ts +124 -11
  34. package/dist/shared/index.d.ts.map +1 -1
  35. package/dist/shared/index2.d.ts +9 -19
  36. package/dist/shared/index2.d.ts.map +1 -1
  37. package/dist/shared/index7.d.ts +105 -26
  38. package/dist/shared/index7.d.ts.map +1 -1
  39. package/dist/shared/index9.d.ts +1 -1
  40. package/dist/shared/init.js +12 -10
  41. package/dist/shared/init.js.map +1 -1
  42. package/dist/shared/integration.d.ts +1 -1
  43. package/dist/shared/packages.js +1 -1
  44. package/dist/shared/recording.js +31 -3
  45. package/dist/shared/recording.js.map +1 -1
  46. package/dist/shared/src.js.map +1 -1
  47. package/dist/shared/task.js +72 -21
  48. package/dist/shared/task.js.map +1 -1
  49. package/dist/shared/tasks.js +330 -166
  50. package/dist/shared/tasks.js.map +1 -1
  51. package/dist/shared/vb.js +1 -1
  52. package/dist/shared/voice2.js +6 -4
  53. package/dist/shared/voice2.js.map +1 -1
  54. package/dist/shared/watch.js +14 -14
  55. package/dist/shared/watch.js.map +1 -1
  56. package/dist/tailwind/index.js +6 -2
  57. package/dist/tailwind/index.js.map +1 -1
  58. package/dist/tasks/client.d.ts +2 -2
  59. package/dist/tasks/client.d.ts.map +1 -1
  60. package/dist/tasks/client.js +1829 -742
  61. package/dist/tasks/client.js.map +1 -1
  62. package/dist/tasks/index.d.ts +2 -2
  63. package/dist/voice/client.d.ts.map +1 -1
  64. package/dist/voice/client.js +154 -57
  65. package/dist/voice/client.js.map +1 -1
  66. package/package.json +1 -1
  67. package/skills/deictic/SKILL.md +22 -28
  68. package/src/cli/find.ts +3 -1
  69. package/src/cli/init.ts +13 -11
  70. package/src/cli/recording.ts +34 -3
  71. package/src/cli/task.ts +94 -23
  72. package/src/cli/voice.ts +9 -4
  73. package/src/cli/watch.ts +14 -13
  74. package/src/client/away.ts +3 -1
  75. package/src/client/component.ts +98 -0
  76. package/src/client/dom.ts +70 -0
  77. package/src/client/drawer.ts +258 -0
  78. package/src/client/index.ts +220 -128
  79. package/src/client/lightbox.ts +8 -8
  80. package/src/client/lighting.ts +279 -0
  81. package/src/client/style.ts +263 -44
  82. package/src/client/tools.ts +279 -0
  83. package/src/client/tooltip.ts +25 -5
  84. package/src/client/tray.ts +48 -0
  85. package/src/index.ts +121 -10
  86. package/src/plugins/annotations/client.ts +103 -129
  87. package/src/plugins/annotations/draw.ts +68 -72
  88. package/src/plugins/annotations/index.ts +12 -19
  89. package/src/plugins/recordings/client.ts +89 -167
  90. package/src/plugins/screenshots/client.ts +53 -2
  91. package/src/plugins/tailwind/index.ts +6 -2
  92. package/src/plugins/tasks/client.ts +219 -749
  93. package/src/plugins/tasks/composer.ts +797 -0
  94. package/src/plugins/tasks/drawer.ts +516 -0
  95. package/src/plugins/tasks/index.ts +459 -192
  96. package/src/plugins/tasks/pins.ts +275 -0
  97. package/src/plugins/tasks/store.ts +132 -0
  98. package/src/plugins/voice/client.ts +96 -5
  99. package/src/tools/endpoints.ts +18 -7
  100. package/src/tools/source.ts +25 -5
  101. package/skills/deictic/references/recordings.md +0 -13
  102. package/skills/deictic/references/tasks.md +0 -21
  103. package/skills/deictic/references/watch.md +0 -17
@@ -2,8 +2,7 @@
2
2
  * `deictic/tasks`: open its tab on an element to add a task about it to a Vercel Board
3
3
  * (`@vercel/board`). The task says what to change, in the words typed, and where: the element's file,
4
4
  * line and tag, the page and the project, all as labels beside the short facts (viewport, how many, where
5
- * it is in the shot), and after the words what a label can't hold: the chain of source it rendered through, from
6
- * its own line out to the files that use its component. Its HTML as it rendered is a file attached, `element.html`, for whoever
5
+ * it is in the shot) and the chain of source it rendered through, out to the files that use its component. Its HTML as it rendered is a file attached, `element.html`, for whoever
7
6
  * wants more than the task says: a task stays short. Whatever works the board's tasks (a person, or an agent of theirs claiming them) takes it
8
7
  * from there; deictic only adds them.
9
8
  *
@@ -18,7 +17,7 @@ import { join, relative } from 'node:path';
18
17
 
19
18
  import type { Board } from '@vercel/board';
20
19
 
21
- import { definePlugin, Refusal, type ServerContext, type Shortcut, type Source, type Target } from '#src/index.ts';
20
+ import { definePlugin, type Point, Refusal, type ServerContext, type Shortcut, type Source, type Target } from '#src/index.ts';
22
21
  // For `use('screenshots')`'s type: the plugin may not be loaded, and nothing of it runs here.
23
22
  import type { Recordings } from '#src/plugins/recordings/index.ts';
24
23
  import type { Box } from '#src/plugins/screenshots/index.ts';
@@ -30,7 +29,7 @@ import { watchersOf } from './watchers.ts';
30
29
  export { local, type LocalBoard, type LocalOptions } from './local.ts';
31
30
 
32
31
  /** What the plugin uses of a board: `board()` from `@vercel/board` is one. */
33
- export type TaskBoard = Pick<Board, 'tasks' | 'thread' | 'discovery' | 'upload' | 'edit' | 'actors'>;
32
+ export type TaskBoard = Pick<Board, 'tasks' | 'thread' | 'threads' | 'reply' | 'discovery' | 'upload' | 'download' | 'edit' | 'actors'>;
34
33
 
35
34
  export interface TasksOptions {
36
35
  /**
@@ -81,9 +80,12 @@ export interface Task {
81
80
  open: boolean;
82
81
  /** Its page on the board, when there's one to link to. */
83
82
  link?: string;
83
+ /** What was attached to it but not kept by the time it was sent, so it went without: `a screenshot`. */
84
+ dropped?: string;
85
+ /** The spot in the element it's about, where it's about one: CSS pixels from the element's top left. */
86
+ point?: Point;
84
87
  /**
85
- * Where it was added, where that isn't the element's place: for one of `tasks`, where the element was before
86
- * it moved; for one of `elsewhere`, the element it's about.
88
+ * Where it was added, where that isn't the element's place: where the element was before it moved.
87
89
  */
88
90
  at?: Place;
89
91
  }
@@ -95,14 +97,76 @@ export interface Place {
95
97
  tag: string;
96
98
  }
97
99
 
100
+ /** A task as the drawer lists it: with its place, where it has one, and how its thread stands. */
101
+ export interface Listed extends Task {
102
+ /** `file:line:column`, as the element's mark: none for a task about the page. */
103
+ place?: string;
104
+ /** The tag there, as the task saw it. */
105
+ tag?: string;
106
+ /** The page it was added on, as its path: `/pricing`. */
107
+ page?: string;
108
+ /** How many replies its thread has, and the newest's ID: what the page tells the unread by. */
109
+ replies: number;
110
+ last?: string;
111
+ /** What the board says of where it stands: why it's blocked, what it came to, why it failed. */
112
+ said?: string;
113
+ }
114
+
115
+ /** A task with a place, as its mark has it: what the page pins to the element there. */
116
+ export type Placed = Listed & { place: string };
117
+
118
+ /** A file attached to a task or to a reply in its thread, as the board keeps it. */
119
+ export interface Attached {
120
+ /** The board's ID for it. */
121
+ id: string;
122
+ name: string;
123
+ /** Its MIME type: `image/png`, `audio/webm`, `application/json` for a recording, `text/html` for an element's HTML. */
124
+ type: string;
125
+ /** In bytes. */
126
+ size: number;
127
+ /**
128
+ * Where the page gets it: by default the plugin's `file/<task>/<id>` route, which serves an image or a sound as it
129
+ * is and anything else as text. A `standalone` server answers its own.
130
+ */
131
+ url?: string;
132
+ /** Where a recording plays back, as the message says. */
133
+ replay?: string;
134
+ }
135
+
136
+ /** A message in a task's thread, oldest first. */
137
+ export interface Reply {
138
+ id: string;
139
+ /** Who wrote it, by name. */
140
+ by: string;
141
+ /** `person`, or what else wrote it: an agent's `profile`, a deployment, a workflow. */
142
+ kind: string;
143
+ text: string;
144
+ /** When, as an ISO date. */
145
+ at: string;
146
+ /** What it has attached. */
147
+ files: Attached[];
148
+ }
149
+
150
+ /** A task with its thread, as the drawer opens it. */
151
+ export interface Thread {
152
+ task: Listed;
153
+ /** What the task has attached: its shots, recordings, voice notes and elements' HTML. */
154
+ files: Attached[];
155
+ replies: Reply[];
156
+ }
157
+
158
+ /**
159
+ * A reply, as the drawer's composer sends it to the `reply/<id>` route: its words, and what's attached, as a task
160
+ * attaches it. A reply with nothing typed says what's attached instead.
161
+ */
162
+ export type Answer = Pick<Op, 'text' | 'screenshots' | 'recordings' | 'voice' | 'annotations'>;
163
+
98
164
  export interface Model {
99
165
  channel: string;
100
166
  /** The channel's page, when there's one to link to. */
101
167
  link?: string;
102
168
  /** Tasks about this element, oldest first, canceled ones left out: also those added before it moved. */
103
169
  tasks: Task[];
104
- /** Tasks about the file's other elements, by line, canceled ones left out: each with its `at`. */
105
- elsewhere: Task[];
106
170
  /**
107
171
  * Who watches the channel, by name (`claude`): the agents whose watch (`deictic watch`) is running in
108
172
  * this project, as a board can't say, and those holding a claim on one of the channel's tasks, which it can.
@@ -112,18 +176,17 @@ export interface Model {
112
176
  watching?: string[];
113
177
  }
114
178
 
115
- /**
116
- * What the Task tab asks for: a new task (an `Op`), other words for one it lists (`edit` is its ID), or
117
- * that one deleted (`remove` is its ID), which cancels it on the board.
118
- */
119
- export type Change = Op | { edit: string; text: string } | { remove: string };
120
-
121
179
  /** A new task: what the page knows and the source doesn't. */
122
180
  export interface Op {
123
181
  text: string;
124
182
  /** The page's URL. */
125
183
  page: string;
126
184
  viewport: { width: number; height: number };
185
+ /**
186
+ * The spot it's about, where it was added on one (the tool panel's task tool) and not on the element as a whole:
187
+ * CSS pixels from the element's top left, and outside its box where the element is only the nearest to the spot.
188
+ */
189
+ point?: Point;
127
190
  /**
128
191
  * What was under the pointer inside the element, where nothing marked it (a dependency's markup, or a
129
192
  * shadow root's): its path from the element, and its HTML, cut short.
@@ -131,6 +194,16 @@ export interface Op {
131
194
  pointed?: { path: string; html: string };
132
195
  /** How many elements on the page come from the same place in the source. */
133
196
  count: number;
197
+ /**
198
+ * The other elements it's about, after the one it's sent on, in the order they were attached: each one's place,
199
+ * its tag, and its HTML as it rendered, where that's attached.
200
+ */
201
+ also?: { at: string; tag: string; html?: string }[];
202
+ /**
203
+ * No element is attached: it's about the page, and the element it's sent on is only where the popup was. It has
204
+ * no place then, so no element's tab lists it and nothing pins it.
205
+ */
206
+ detached?: boolean;
134
207
  /**
135
208
  * The source it rendered through, after its own place, nearest first: where the one before it is used. With
136
209
  * React in development, the components that wrote it, `Field (src/Field.tsx:20)` or a name alone; without, the
@@ -141,11 +214,12 @@ export interface Op {
141
214
  /** The element's HTML as it rendered, to attach: cut short, and masked where the screenshots plugin is loaded. */
142
215
  html?: string;
143
216
  /**
144
- * Shots the screenshots plugin took of it, to attach, where that plugin is loaded: each with where the
145
- * element is in it, whether it's `outlined` there (dashes drawn around it, in the PNG), and the marks drawn
146
- * on it in the panel, where there are any.
217
+ * Shots the screenshots plugin took, to attach, where that plugin is loaded: each with where the element is in
218
+ * it (`box`, for one taken of the element; one taken of the window from the tool panel has none), whether
219
+ * it's `outlined` there (dashes drawn around it, or around the spot, in the PNG), and the marks drawn on it in
220
+ * the Task tab, where there are any.
147
221
  */
148
- screenshots?: { id: string; box: Box; outlined?: boolean; marks?: Marks }[];
222
+ screenshots?: { id: string; box?: Box; outlined?: boolean; marks?: Marks }[];
149
223
  /**
150
224
  * Recordings the recordings plugin made, to attach, where that plugin is loaded: how long each ran,
151
225
  * where it plays back, and the voice plugin's clips of the mic in it, attached too.
@@ -173,6 +247,11 @@ export interface TaskAdded {
173
247
  page: string;
174
248
  /** How many of each were attached; `marks` counts those drawn on shots and on the page. */
175
249
  attached: { screenshots: number; recordings: number; voice: number; marks: number };
250
+ /**
251
+ * Where each attached shot is, as it was sent (outlined, or as it was drawn on), for the page to show: the
252
+ * screenshots plugin's `shot` route, or what a `standalone` server answered.
253
+ */
254
+ screenshots: string[];
176
255
  }
177
256
 
178
257
  /** Marks, as a task tells of them: how many, and what the notes among them say. */
@@ -190,7 +269,7 @@ export interface Added {
190
269
  attachments?: string[];
191
270
  }
192
271
 
193
- /** A task's words changed: its message's whole text before and after. */
272
+ /** A task's words changed in the tab, as an earlier version let it: its message's whole text before and after. */
194
273
  export interface Edited {
195
274
  kind: 'edited';
196
275
  id: string;
@@ -199,20 +278,36 @@ export interface Edited {
199
278
  }
200
279
 
201
280
  /**
202
- * A task deleted in the panel: canceled on the board, for good, as a board has it. So it's kept whole, and
203
- * an undo adds it again, as a new task whose ID the record then has.
281
+ * A task deleted in the tab, as an earlier version let it: canceled on the board, for good, as a board has it. So
282
+ * it's kept whole, and an undo adds it again, as a new task whose ID the record then has.
204
283
  */
205
284
  export interface Removed extends Added {
206
285
  kind: 'removed';
207
286
  }
208
287
 
209
- /** What the history keeps of a change: a task added has no `kind`, as it had none before there were others. */
288
+ /**
289
+ * What the history keeps of a change: a task added has no `kind`, as it had none before there were others. The others
290
+ * are no longer made (a task is changed in the drawer, by the plugin's routes), and still undone where a history has them.
291
+ */
210
292
  export type Kept = Added | Edited | Removed;
211
293
 
294
+ /** A task as a board lists it: its root message. */
295
+ type Message = Awaited<ReturnType<TaskBoard['thread']>>['message'];
296
+ /** A task's thread at a glance, as a board lists tasks. */
297
+ type Summary = Awaited<ReturnType<TaskBoard['tasks']['list']>>['tasks'][number];
298
+ /** How many of the latest finished tasks the drawer lists: what an agent said as it ended one is there to read. */
299
+ const OVER = 10;
300
+
301
+ /** How many tasks a page is asked about at most: past that it has more pins than anyone reads. */
302
+ const PINNED = 500;
212
303
  const AT = 'deictic.at';
213
304
  const FILE = 'deictic.file';
305
+ /** `x,y`: the spot in the element a task is about, in CSS pixels from the element's top left. */
306
+ const POINT = 'deictic.point';
214
307
  /** What parts what was typed from the rest of a task's text. */
215
308
  const REST = '\n---\n';
309
+ /** A file for the board, as the plugins that keep them read it. */
310
+ type Upload = { data: Uint8Array<ArrayBuffer>; name: string; type: string };
216
311
  const OPEN = new Set(['waiting', 'ready', 'blocked']);
217
312
 
218
313
  export function tasks(options: TasksOptions = {}) {
@@ -267,9 +362,11 @@ export function tasks(options: TasksOptions = {}) {
267
362
  * One of this channel's tasks about an element, while it's still open: the page names it by ID, so
268
363
  * nothing else on the board is its to change, nor a task someone has taken up.
269
364
  */
365
+ /** One of deictic's: it has a place, or the page it's about where no element was attached. */
366
+ const ours = (message: Message) => message.labels[AT] !== undefined || message.labels['deictic.page'] !== undefined;
270
367
  const openTask = async (team: TaskBoard, id: string, verb: string) => {
271
368
  const { message } = await team.thread(id);
272
- if (message.channel !== channel || message.labels[AT] === undefined)
369
+ if (message.channel !== channel || !ours(message))
273
370
  throw new Refusal(`#${id} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);
274
371
 
275
372
  const { task } = message;
@@ -306,39 +403,188 @@ export function tasks(options: TasksOptions = {}) {
306
403
  return { ...record, id: task.id };
307
404
  };
308
405
 
309
- // Kept from `setup`, to `use` another plugin when an op asks for it.
406
+ /** A board's task as the panel lists it: its words, its state, who has it, and its page there. */
407
+ const taskOf = (message: Message, actors: Awaited<ReturnType<typeof actorsOf>>, page: string | undefined): Task => {
408
+ const state = message.task?.state ?? 'ready';
409
+ const by = actors.get(message.task?.claim?.actor ?? '')?.name;
410
+ const text = message.text.split(REST, 1)[0]!;
411
+ const to = taskLink(page, message.id);
412
+ const missing = Object.entries(message.labels).flatMap(([key, value]) => (/^deictic\.dropped\.\d+$/.test(key) ? [value] : []));
413
+ const dropped = missing.length === 0 ? undefined : listOf(missing);
414
+ const [, x, y] = /^(-?\d+),(-?\d+)$/.exec(message.labels[POINT] ?? '') ?? [];
415
+ const point = x === undefined || y === undefined ? undefined : { x: Number(x), y: Number(y) };
416
+ return {
417
+ id: message.id,
418
+ title: text.split('\n', 1)[0]!,
419
+ text,
420
+ state,
421
+ ...(by === undefined ? {} : { by }),
422
+ open: OPEN.has(state),
423
+ ...(to === undefined ? {} : { link: to }),
424
+ ...(dropped === undefined ? {} : { dropped }),
425
+ ...(point === undefined ? {} : { point }),
426
+ };
427
+ };
428
+ const listedOf = (
429
+ { message, replies, last }: Summary,
430
+ actors: Awaited<ReturnType<typeof actorsOf>>,
431
+ page: string | undefined,
432
+ ): Listed => {
433
+ const { task, labels } = message;
434
+ const said = task?.blocked?.reason ?? task?.result ?? task?.reason ?? undefined;
435
+ return {
436
+ ...taskOf(message, actors, page),
437
+ ...(labels[AT] === undefined ? {} : { place: labels[AT] }),
438
+ ...(labels['deictic.tag'] === undefined ? {} : { tag: labels['deictic.tag'] }),
439
+ ...(labels['deictic.page'] === undefined ? {} : { page: labels['deictic.page'] }),
440
+ replies,
441
+ ...(last === null ? {} : { last: last.id }),
442
+ ...(said === undefined || said === '' ? {} : { said: clip(said, 2000) }),
443
+ };
444
+ };
445
+ /**
446
+ * The channel's tasks, for the page: those still to do, oldest first, a page of the board's at a time and no more
447
+ * than `PINNED`, then the `OVER` that last ended, the latest first.
448
+ */
449
+ const listed = async (): Promise<Listed[]> => {
450
+ const team = await boardOf();
451
+ const open: Summary[] = [];
452
+ for (let after: string | undefined; open.length < PINNED;) {
453
+ const { tasks, cursor } = await team.tasks.list({ channel, ...(after === undefined ? {} : { after }) });
454
+ open.push(...tasks);
455
+ if (tasks.length === 0 || cursor === after) break;
456
+ after = cursor;
457
+ }
458
+ // By their latest activity, which is how a board answers threads: the newest of each end, then of both.
459
+ const ended = await Promise.all(
460
+ ['completed', 'failed'].map((state) => team.threads({ channel, label: { 'board.task': state }, limit: OVER })),
461
+ );
462
+ const when = ({ message, last }: Summary) => (last ?? message).createdAt;
463
+ const over = ended
464
+ .flatMap(({ threads }) => threads)
465
+ .sort((a, b) => when(b).localeCompare(when(a)))
466
+ .slice(0, OVER);
467
+ const about = [...open, ...over].filter(({ message }) => ours(message));
468
+ const [actors, page] = await Promise.all([
469
+ actorsOf(
470
+ team,
471
+ about.flatMap(({ message }) => message.task?.claim?.actor ?? []),
472
+ ),
473
+ linkOf(),
474
+ ]);
475
+ return about.map((summary) => listedOf(summary, actors, page));
476
+ };
477
+ const replyOf = (message: Message): Reply => ({
478
+ id: message.id,
479
+ by: message.author?.name ?? message.by.actor,
480
+ kind: message.author?.kind ?? 'unknown',
481
+ text: message.text,
482
+ at: message.createdAt,
483
+ files: filesOf(message),
484
+ });
485
+ /** A task of ours with its thread, the newest replies a board answers at once. */
486
+ const threadOf = async (id: string): Promise<Thread> => {
487
+ const team = await boardOf();
488
+ const { message, replies } = await team.thread(id);
489
+ if (message.channel !== channel || !ours(message))
490
+ throw new Refusal(`#${id} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);
491
+ const said = replies.filter((reply) => !reply.deleted);
492
+ const [actors, page] = await Promise.all([actorsOf(team, message.task?.claim ? [message.task.claim.actor] : []), linkOf()]);
493
+ return {
494
+ task: listedOf({ message, replies: said.length, last: said.at(-1) ?? null }, actors, page),
495
+ files: filesOf(message),
496
+ replies: said.map(replyOf),
497
+ };
498
+ };
499
+ /** The task a route's request names, as its last segment, and what it sent. */
500
+ const named = async (req: Request) => {
501
+ const id = decodeURIComponent(new URL(req.url).pathname.split('/').at(-1) ?? '');
502
+ const sent: unknown = req.method === 'POST' ? await req.json().catch(() => ({})) : {};
503
+ const body = (typeof sent === 'object' && sent !== null ? sent : {}) as Partial<Answer>;
504
+ return { id, text: typeof body.text === 'string' ? body.text : '', body };
505
+ };
506
+ /**
507
+ * A file of a task's, `file/<task>/<file>`: one attached to the task or to a reply in its thread, and to nothing
508
+ * else on the board. An image or a sound is served as it is; anything else as its text, escaped, in a page of the
509
+ * lightbox's dark colours, so an element's HTML is read there, never run, on the dev server's origin.
510
+ */
511
+ const fileOf = async (req: Request): Promise<Response> => {
512
+ const [task = '', file = ''] = (new URL(req.url).pathname.split('/file/')[1] ?? '').split('/').map(decodeURIComponent);
513
+ const team = await boardOf();
514
+ const { message, replies } = await team.thread(task);
515
+ if (message.channel !== channel || !ours(message))
516
+ throw new Refusal(`#${task} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);
517
+ const found = [message, ...replies].flatMap((m) => m.attachments).find((a) => a.id === file);
518
+ if (found === undefined) throw new Refusal(`task ${task} has no file ${file}: reload the page for what it has`);
519
+ const res = await team.download(found.id);
520
+ const media = /^(image|audio|video)\//.test(found.type);
521
+ const body = media ? res.body : textPage(found.name, await res.text());
522
+ return new Response(body, {
523
+ headers: {
524
+ 'content-type': media ? found.type : 'text/html; charset=utf-8',
525
+ 'content-disposition': `inline; filename="${found.name.replaceAll('"', '')}"`,
526
+ 'x-content-type-options': 'nosniff',
527
+ // Its own style and nothing else: no script, no request anywhere.
528
+ 'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src 'self' blob:; media-src 'self' blob:",
529
+ // A board's file never changes under its ID.
530
+ 'cache-control': 'private, max-age=86400, immutable',
531
+ },
532
+ });
533
+ };
534
+
535
+ // Kept from `setup`, to `use` another plugin when an op asks for it. // Kept from `setup`, to `use` another plugin when an op asks for it.
310
536
  let context: ServerContext | undefined;
311
537
  let project = options.project;
312
- /** The screenshots, recordings and the element's HTML to attach, uploaded to the board, or nothing when there are none. */
313
- const attach = async (op: Op): Promise<string[] | undefined> => {
314
- // All read first, so one no longer kept uploads none.
315
- const files = [
316
- ...(op.screenshots ?? []).map(({ id }) => {
317
- const shot = context?.use('screenshots')?.read(id);
318
- if (shot === undefined) throw new Refusal(`screenshot ${id} isn't kept any more: take it again`);
319
- return shot;
320
- }),
321
- ...(op.recordings ?? []).map(({ id }) => {
322
- const recording: ReturnType<Recordings['read']> = context?.use('recordings')?.read(id);
323
- if (recording === undefined) throw new Refusal(`recording ${id} isn't kept any more: record it again`);
324
- return recording;
325
- }),
326
- ...[...(op.recordings ?? []).flatMap((r) => r.voice ?? []), ...(op.voice ?? []).map((v) => v.id)].map((id) => {
327
- const clip: ReturnType<Clips['read']> = context?.use('voice')?.read(id);
328
- if (clip === undefined) throw new Refusal(`voice clip ${id} isn't kept any more: record it again`);
329
- return clip;
330
- }),
331
- // Last, and a file, not the task's words: it's there to look into, and most tasks are done without it.
332
- ...(typeof op.html !== 'string' || op.html === ''
333
- ? []
334
- : [{ data: new TextEncoder().encode(op.html.slice(0, HTML)), name: 'element.html', type: 'text/html' }]),
335
- ];
538
+ /**
539
+ * The op with only the screenshots, recordings and voice clips still kept, their files, and what's left out: a file
540
+ * goes once newer ones pass its plugin's `keep`, or `deictic clean` takes it, and that's no reason to lose the task.
541
+ */
542
+ const keptOf = <T extends Attaching>(op: T) => {
543
+ const clipOf = (id: string): ReturnType<Clips['read']> => context?.use('voice')?.read(id);
544
+ // In the op's order, each kind's: the Nth PNG is `deictic.screenshot.N`'s, the Nth recording `deictic.recording.N`'s.
545
+ const files: Upload[] = [];
546
+ const dropped: Kind[] = [];
547
+ const take = (file: Upload | undefined, missing: Kind) => {
548
+ if (file === undefined) dropped.push(missing);
549
+ else files.push(file);
550
+ return file !== undefined;
551
+ };
552
+ const screenshots = (op.screenshots ?? []).filter(({ id }) => take(context?.use('screenshots')?.read(id), 'screenshot'));
553
+ const recordings = (op.recordings ?? []).flatMap((recording) => {
554
+ const found: ReturnType<Recordings['read']> = context?.use('recordings')?.read(recording.id);
555
+ if (!take(found, 'recording')) return [];
556
+ if (recording.voice === undefined) return [recording];
557
+ const clipped = (id: string) => take(clipOf(id), 'voice clip');
558
+ return [{ ...recording, voice: recording.voice.filter(clipped) }];
559
+ });
560
+ const voice = (op.voice ?? []).filter(({ id }) => take(clipOf(id), 'voice note'));
561
+ // Last, and files, not the task's words: there to look into, and most tasks are done without them. What was
562
+ // pointed at is in the element's HTML, and a file of its own only where that isn't attached.
563
+ const html = typeof op.html === 'string' && op.html !== '' ? op.html : undefined;
564
+ if (html !== undefined) files.push({ data: new TextEncoder().encode(html.slice(0, HTML)), name: 'element.html', type: 'text/html' });
565
+ else if (op.pointed !== undefined)
566
+ files.push({ data: new TextEncoder().encode(op.pointed.html.slice(0, HTML)), name: 'pointed.html', type: 'text/html' });
567
+ // The others': the Nth element's is `element.N.html`, the first being the one it's sent on.
568
+ for (const [i, other] of (op.also ?? []).entries()) {
569
+ if (typeof other.html !== 'string' || other.html === '') continue;
570
+ files.push({ data: new TextEncoder().encode(other.html.slice(0, HTML)), name: `element.${i + 2}.html`, type: 'text/html' });
571
+ }
572
+ const kept: T = {
573
+ ...op,
574
+ ...(op.screenshots === undefined ? {} : { screenshots }),
575
+ ...(op.recordings === undefined ? {} : { recordings }),
576
+ ...(op.voice === undefined ? {} : { voice }),
577
+ };
578
+ return { op: kept, files, dropped };
579
+ };
580
+ /** The files uploaded to the board, or nothing when there are none. */
581
+ const upload = async (files: Upload[]): Promise<string[] | undefined> => {
336
582
  if (files.length === 0) return undefined;
337
583
  const team = await boardOf();
338
584
  return Promise.all(files.map(async (file) => (await team.upload(file)).id));
339
585
  };
340
586
 
341
- return definePlugin<Model, Change, Kept>({
587
+ return definePlugin<Model, Op, Kept>({
342
588
  name: 'tasks',
343
589
  client: 'deictic/tasks/client',
344
590
  packages: ['@vercel/board'],
@@ -353,6 +599,64 @@ export function tasks(options: TasksOptions = {}) {
353
599
  // Not waited for: a failure is the first request's to tell.
354
600
  void boardOf().catch(() => {});
355
601
  },
602
+ routes: {
603
+ // The channel's tasks, for the page: the drawer lists them, and those with a place are pinned where their
604
+ // elements are.
605
+ page: async () => {
606
+ const [tasks, link] = await Promise.all([asked(listed), linkOf()]);
607
+ return Response.json({ channel, ...(link === undefined ? {} : { link }), tasks });
608
+ },
609
+ // A task and its thread, `thread/<id>`: what the drawer opens.
610
+ thread: async (req) => Response.json(await asked(async () => threadOf((await named(req)).id))),
611
+ // What the drawer does to a task: a reply in its thread, other words for it, or its end, which cancels it
612
+ // on the board. Each answers the thread as it is after.
613
+ // What a task has attached, or a reply in its thread, for the drawer to show.
614
+ file: (req) => asked(() => fileOf(req)),
615
+ reply: (req) =>
616
+ asked(async () => {
617
+ const { id, text, body } = await named(req);
618
+ const answer: Answer = {
619
+ text,
620
+ ...(Array.isArray(body.screenshots) ? { screenshots: body.screenshots } : {}),
621
+ ...(Array.isArray(body.recordings) ? { recordings: body.recordings } : {}),
622
+ ...(Array.isArray(body.voice) ? { voice: body.voice } : {}),
623
+ ...(body.annotations === undefined ? {} : { annotations: body.annotations }),
624
+ };
625
+ if (wordsOf(answer) === '') throw new Refusal('say something first');
626
+ await threadOf(id);
627
+ const { op: kept, files, dropped } = keptOf(answer);
628
+ const verb = dropped.length === 1 ? "isn't" : "aren't";
629
+ if (wordsOf(kept) === '') throw new Refusal(`${listOf(dropped)} ${verb} kept any more: attach again, or say something`);
630
+ // What the files don't say, as a task has it: where each recording replays, the notes drawn.
631
+ const labels = attachedLabels(kept, dropped);
632
+ const attachments = await upload(files);
633
+ await (
634
+ await boardOf()
635
+ ).reply(id, {
636
+ text: clip(wordsOf(kept), 10_000),
637
+ ...(Object.keys(labels).length === 0 ? {} : { labels }),
638
+ ...(attachments === undefined ? {} : { attachments }),
639
+ });
640
+ return Response.json(await threadOf(id));
641
+ }),
642
+ edit: (req) =>
643
+ asked(async () => {
644
+ const { id, text } = await named(req);
645
+ // A task's words are never changed to none.
646
+ if (text.trim() === '') throw new Refusal('say what should change first');
647
+ const before = (await openTask(await boardOf(), id, 'edit')).text;
648
+ // What follows the words in a task added before they were labels (what's attached, what was pointed at) stays.
649
+ const rest = before.includes(REST) ? before.slice(before.indexOf(REST)) : '';
650
+ await rewrite(id, before, clip(text.trim(), 10_000 - rest.length) + rest);
651
+ return Response.json(await threadOf(id));
652
+ }),
653
+ remove: (req) =>
654
+ asked(async () => {
655
+ const { id } = await named(req);
656
+ await cancel(id, 'deleted in deictic');
657
+ return Response.json({});
658
+ }),
659
+ },
356
660
  read: (source, target) =>
357
661
  asked(async () => {
358
662
  const team = await boardOf();
@@ -365,35 +669,20 @@ export function tasks(options: TasksOptions = {}) {
365
669
  team.tasks.list({ channel, state: 'claimed' }),
366
670
  ]);
367
671
  const listed = new Set(inFile.tasks.map(({ message }) => message.id));
368
- const line = lineOf(source);
369
- // A line the file has twice says nothing of which element a task was about.
370
- const once = source.code.split(line).length === 2;
672
+ // Nothing to tell a moved task by where the file has no such element.
673
+ const line = source instanceof Refusal ? undefined : onceIn(source);
371
674
  const tasks: Task[] = [];
372
- const elsewhere: (Task & { at: Place })[] = [];
373
675
  const about = [...here.tasks.filter((t) => !listed.has(t.message.id)), ...inFile.tasks];
374
676
  // Who has each, and who holds any claim on the channel: asked of the board at once.
375
677
  const actorOf = ({ task }: (typeof about)[number]['message']) => task?.claim?.actor;
376
678
  const claims = held.tasks.flatMap(({ message }) => message.task?.claim ?? []);
377
679
  const actors = await actorsOf(team, [...about.flatMap(({ message }) => actorOf(message) ?? []), ...claims.map((c) => c.actor)]);
378
680
  for (const { message } of about) {
379
- const state = message.task?.state ?? 'ready';
380
- if (state === 'canceled') continue;
381
- const by = actors.get(actorOf(message) ?? '')?.name;
382
- const text = message.text.split(REST, 1)[0]!;
383
- const to = taskLink(page, message.id);
384
- const task = {
385
- id: message.id,
386
- title: text.split('\n', 1)[0]!,
387
- text,
388
- state,
389
- ...(by === undefined ? {} : { by }),
390
- open: OPEN.has(state),
391
- ...(to === undefined ? {} : { link: to }),
392
- };
681
+ if (message.task?.state === 'canceled') continue;
682
+ const task = taskOf(message, actors, page);
393
683
  const at = placeIn(message.labels);
394
684
  if (at === undefined || message.labels[AT] === atOf(target)) tasks.push(task);
395
- else if (once && at.tag === target.tag && message.labels['deictic.line'] === clip(line, LABEL)) tasks.push({ ...task, at });
396
- else elsewhere.push({ ...task, at });
685
+ else if (line !== undefined && at.tag === target.tag && message.labels['deictic.line'] === line) tasks.push({ ...task, at });
397
686
  }
398
687
  // An agent at work on a task is here too, though its watch may be over until the task is (`deictic watch --once`).
399
688
  const working = agentsOf(actors, claims);
@@ -405,43 +694,24 @@ export function tasks(options: TasksOptions = {}) {
405
694
  ...(page === undefined ? {} : { link: page }),
406
695
  ...(watching.length > 0 || ours ? { watching } : {}),
407
696
  tasks,
408
- // The board's order (oldest first) among those of one place.
409
- elsewhere: elsewhere.sort((a, b) => (a.at.line === b.at.line ? a.at.column - b.at.column : a.at.line - b.at.line)),
410
697
  };
411
698
  }),
412
699
  apply: (source, target, op) => {
413
- if ('remove' in op) {
414
- return asked(async () => {
415
- const message = await cancel(op.remove, 'deleted in deictic');
416
- // The board's own labels (`board.task`) are its to set on the task an undo adds.
417
- const labels = Object.fromEntries(Object.entries(message.labels).filter(([key]) => !key.startsWith('board.')));
418
- const attachments = message.attachments.map((a) => a.id);
419
- const kept = { channel, id: op.remove, text: message.text, labels, ...(attachments.length === 0 ? {} : { attachments }) };
420
- return { done: { kind: 'removed' as const, ...kept } };
421
- });
422
- }
423
- // A new task may go without words where something attached says it; a task's words are never changed to none.
424
- if (op.text.trim() === '' && ('edit' in op || shown(op) === undefined)) throw new Refusal('say what should change first');
425
- if ('edit' in op) {
426
- return asked(async () => {
427
- const before = (await openTask(await boardOf(), op.edit, 'edit')).text;
428
- // What follows the words (what's attached, what was pointed at) stays as it was.
429
- const rest = before.includes(REST) ? before.slice(before.indexOf(REST)) : '';
430
- const after = clip(op.text.trim(), 10_000 - rest.length) + rest;
431
- await rewrite(op.edit, before, after);
432
- return { done: { kind: 'edited' as const, id: op.edit, before, after } };
433
- });
434
- }
700
+ // A task may go without words where something attached says it.
701
+ if (op.text.trim() === '' && shown(op) === undefined) throw new Refusal('say what should change first');
702
+ const { op: kept, files, dropped } = keptOf(op);
703
+ const verb = dropped.length === 1 ? "isn't" : "aren't";
704
+ if (wordsOf(kept) === '') throw new Refusal(`${listOf(dropped)} ${verb} kept any more: attach again, or say what should change`);
435
705
  const labels = {
436
706
  ...options.labels,
437
707
  ...(project === undefined ? {} : { 'deictic.project': clip(project, LABEL) }),
438
- ...labelsOf(source, target, op),
708
+ ...labelsOf(source, target, kept),
709
+ ...attachedLabels(kept, dropped),
439
710
  };
440
711
  return asked(async () => {
441
- const attachments = await attach(op);
442
- return {
443
- done: await create({ channel, text: textOf(op, target), labels, ...(attachments === undefined ? {} : { attachments }) }),
444
- };
712
+ const attachments = await upload(files);
713
+ const text = clip(wordsOf(kept), 10_000);
714
+ return { done: await create({ channel, text, labels, ...(attachments === undefined ? {} : { attachments }) }) };
445
715
  });
446
716
  },
447
717
  undo: (record) =>
@@ -470,12 +740,7 @@ export function tasks(options: TasksOptions = {}) {
470
740
  await cancel(record.id, 'deleted in deictic');
471
741
  return record;
472
742
  }),
473
- describe: (op, before) => {
474
- const named = (id: string) => `task "${clip(before.tasks.find((t) => t.id === id)?.title ?? `#${id}`, 60)}"`;
475
- if ('remove' in op) return `delete ${named(op.remove)}`;
476
- if ('edit' in op) return `edit ${named(op.edit)}`;
477
- return `task "${clip(wordsOf(op).split('\n', 1)[0]!, 60)}"`;
478
- },
743
+ describe: (op) => `task "${clip(wordsOf(op).split('\n', 1)[0]!, 60)}"`,
479
744
  });
480
745
  }
481
746
 
@@ -489,72 +754,80 @@ async function localPage(team: TaskBoard, channel: string): Promise<string | und
489
754
  return `${url.origin}${url.pathname.slice(0, -'/api/board'.length)}/c/${channel.split('/').map(encodeURIComponent).join('/')}`;
490
755
  }
491
756
 
492
- const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
493
- const said = (notes: string[]) => (notes.length === 0 ? '' : `; the notes say: ${notes.map((n) => JSON.stringify(n)).join(', ')}`);
494
-
495
- /** What was marked on the page: how many marks, and what the notes say. */
496
- function annotated({ count, notes }: Marks, shots: number, recordings: number): string {
497
- const where = [
498
- ...(shots === 0 ? [] : [shots === 1 ? 'the screenshot' : 'the screenshots']),
499
- ...(recordings === 0 ? [] : [recordings === 1 ? 'the recording' : 'the recordings']),
500
- ];
501
- const drawn = where.length === 0 ? '' : `, drawn in ${where.join(' and ')}`;
502
- return `${plural(count, 'mark')} on the page${drawn}${said(notes)}`;
757
+ /**
758
+ * A file's text as a page to read it in: escaped, so nothing in it runs or loads, in the lightbox's colours, as the
759
+ * browser's own text page is black on nothing and the lightbox is dark under it.
760
+ */
761
+ function textPage(name: string, text: string): string {
762
+ const escape = (raw: string) => raw.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
763
+ const style =
764
+ ':root{color-scheme:dark}body{margin:0;padding:16px;font:12px/1.5 ui-monospace,monospace;color:#e4e4e7;background:#18181b;white-space:pre-wrap;overflow-wrap:anywhere}';
765
+ return `<!doctype html><meta charset="utf-8"><title>${escape(name)}</title><style>${style}</style><body>${escape(text)}`;
503
766
  }
504
767
 
505
- /** How long each recording ran, and where it plays back, while the dev server keeps it. */
506
- function recordingsOf(recordings: NonNullable<Op['recordings']>): string[] {
507
- return recordings.map(({ duration, replay, voice }, i) => {
508
- const name = recordings.length === 1 ? 'A recording' : `Recording ${i + 1}`;
509
- const spoken = voice === undefined || voice.length === 0 ? '' : `, with the voice (${voice.map((id) => `voice-${id}`).join(', ')})`;
510
- return `${name}, ${clock(duration)} long, attached as rrweb events${spoken}; it replays at ${replay}`;
511
- });
512
- }
768
+ /** What may be left out of a task as no longer kept, as `deictic.dropped.N` names it. */
769
+ type Kind = 'screenshot' | 'recording' | 'voice clip' | 'voice note';
770
+
771
+ /** What a task or a reply attaches: files, and what the labels say of them. */
772
+ type Attaching = Partial<Pick<Op, 'screenshots' | 'recordings' | 'voice' | 'annotations' | 'html' | 'pointed' | 'also'>>;
513
773
 
514
- /** How long each voice note runs, and the attachment it's in. */
515
- function voicesOf(voice: NonNullable<Op['voice']>): string[] {
516
- return voice.map(({ id, duration }, i) => {
517
- const name = voice.length === 1 ? 'A voice note' : `Voice note ${i + 1}`;
518
- return `${name}, ${clock(duration)} long, attached as voice-${id}`;
774
+ /**
775
+ * A message's files, as the drawer shows them: each recording with where it replays, which its
776
+ * `deictic.recording.N.replay` label says, the Nth being the Nth recording attached.
777
+ */
778
+ function filesOf({ attachments, labels }: Message): Attached[] {
779
+ const recordings = attachments.filter((a) => a.name.startsWith('recording-'));
780
+ return attachments.map(({ id, name, type, size }) => {
781
+ const n = recordings.findIndex((r) => r.id === id);
782
+ const replay = n === -1 ? undefined : labels[`deictic.recording.${n + 1}.replay`];
783
+ return { id, name, type, size, ...(replay === undefined ? {} : { replay }) };
519
784
  });
520
785
  }
521
786
 
522
- const clock = (ms: number) => {
523
- const s = Math.round(ms / 1000);
524
- return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
525
- };
526
-
527
787
  /**
528
- * What's drawn on each shot (the element's outline, the person's marks), and with several, where the element is
529
- * in each. One shot's place is the `deictic.position` and `deictic.size` labels, so a shot with nothing drawn
530
- * on it has no line.
788
+ * What the attached files don't say, as labels numbered from 1, so each value is short and none is read out of the
789
+ * text. `deictic.screenshot.N` is the Nth PNG attached: its `.position` and `.size` where the element is in it (CSS
790
+ * pixels from its top left), for one taken of the element, `.note.M` a note drawn on it. `deictic.recording.N.replay` is where the Nth recording
791
+ * plays back; `deictic.note.M` a note drawn on the page; `deictic.dropped.N` what wasn't kept any more;
792
+ * `deictic.pointed` the path to what was pointed at inside the element. A note past a label is cut.
531
793
  */
532
- function shotsOf(shots: NonNullable<Op['screenshots']>): string[] {
533
- const [only] = shots;
534
- if (shots.length === 1 && only !== undefined) {
535
- const { marks, outlined } = only;
536
- const has = [
537
- ...(outlined === true ? ['the element outlined in dashes'] : []),
538
- ...(marks === undefined || marks.count === 0 ? [] : [`${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`]),
539
- ];
540
- return has.length === 0 ? [] : [`The screenshot has ${has.join(' and ')}`];
541
- }
542
- return shots.map(({ box, marks, outlined }, i) => {
543
- const drawn = marks === undefined || marks.count === 0 ? '' : `, with ${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`;
794
+ function attachedLabels(op: Attaching, dropped: Kind[]): Record<string, string> {
795
+ const labels: Record<string, string> = {};
796
+ // A board takes no control characters in a label: a note's lines go on one.
797
+ const set = (key: string, value: string) => {
798
+ labels[`deictic.${key}`] = clip(value.replace(/\p{Cc}+/gu, ' '), LABEL);
799
+ };
800
+ for (const [i, { box, marks }] of (op.screenshots ?? []).entries()) {
801
+ const n = `screenshot.${i + 1}`;
802
+ for (const [j, note] of (marks?.notes ?? []).entries()) set(`${n}.note.${j + 1}`, note);
803
+ // One of the window, from the tool panel, says nothing of the element: it may not be in it.
804
+ if (box === undefined) continue;
544
805
  const [x, y, width, height] = boxOf(box);
545
- return `In screenshot ${i + 1} at x ${x}, y ${y}, ${width}×${height}${outlined === true ? ', outlined in dashes' : ''}${drawn}`;
546
- });
806
+ set(`${n}.position`, `${x},${y}`);
807
+ set(`${n}.size`, `${width}x${height}`);
808
+ }
809
+ for (const [j, note] of (op.annotations?.notes ?? []).entries()) set(`note.${j + 1}`, note);
810
+ for (const [i, { at, tag }] of (op.also ?? []).entries()) set(`also.${i + 1}`, `${at} <${tag}>`);
811
+ // Not cut: half a URL leads nowhere.
812
+ for (const [i, { replay }] of (op.recordings ?? []).entries()) if (replay.length <= LABEL) set(`recording.${i + 1}.replay`, replay);
813
+ for (const [i, kind] of dropped.entries()) set(`dropped.${i + 1}`, kind);
814
+ if (op.pointed !== undefined) set('pointed', op.pointed.path);
815
+ return labels;
547
816
  }
548
817
 
549
818
  /**
550
- * `Source: src/ui/label.tsx:6 ← Field (src/Field.tsx:20) ← Panel`: from the element's line out, as the page said
551
- * it: the components that use it, where the page knows them, or the files around it.
819
+ * `deictic.source`, `Field (src/Field.tsx:20) ← Panel`: what the element rendered through, out from its own place
820
+ * (`deictic.at`), as the page said it: the components that use it, where the page knows them, or the files around
821
+ * it. As many as a label holds, the farthest left out first.
552
822
  */
553
- function chainOf({ loc }: Target, chain: NonNullable<Op['chain']>): string[] {
554
- const places = chain.slice(0, CHAIN).map((place) => clip(String(place), LABEL));
555
- return places.length === 0 ? [] : [`Source: ${[`${loc.file}:${loc.line}`, ...places].join(' ← ')}`];
823
+ function sourceOf(chain: NonNullable<Op['chain']>): Record<string, string> {
824
+ let places = chain.slice(0, CHAIN).map(String);
825
+ while (places.length > 1 && places.join(THROUGH).length > LABEL) places = places.slice(0, -1);
826
+ return places.length === 0 ? {} : { 'deictic.source': clip(places.join(THROUGH), LABEL) };
556
827
  }
557
828
 
829
+ const THROUGH = ' ← ';
830
+
558
831
  /** How many places a chain names after the element's own: the first few say which use of a component it is. */
559
832
  const CHAIN = 3;
560
833
 
@@ -580,29 +853,29 @@ function nameOf(root: string): string | undefined {
580
853
  /**
581
854
  * The facts about the element, as labels: short values a script reads without parsing the text, and a watch
582
855
  * filters by. `deictic.line` is the opening tag's first line as the task saw it, to tell later that it moved.
583
- * `deictic.url` is the page's whole URL, where a label holds it: `textOf` says a longer one.
856
+ * `deictic.url` is the page's whole URL, where a label holds it; `deictic.page` is its path.
584
857
  */
585
- function labelsOf({ code, element }: Source, target: Target, op: Op): Record<string, string> {
586
- const [shot] = op.screenshots ?? [];
858
+ function labelsOf(source: Source | Refusal, target: Target, op: Op): Record<string, string> {
859
+ const page = {
860
+ 'deictic.page': clip(new URL(op.page).pathname, LABEL),
861
+ ...(op.page.length <= LABEL ? { 'deictic.url': op.page } : {}),
862
+ 'deictic.viewport': `${op.viewport.width}x${op.viewport.height}`,
863
+ };
864
+ // With no element attached it's the page's alone: nothing of the one the popup happened to be on.
865
+ if (op.detached === true) return page;
587
866
  return {
588
867
  [AT]: atOf(target),
589
868
  [FILE]: clip(target.loc.file, LABEL),
590
869
  'deictic.tag': target.tag,
591
- 'deictic.line': clip(lineOf({ code, element }), LABEL),
592
- 'deictic.page': clip(new URL(op.page).pathname, LABEL),
593
- ...(op.page.length <= LABEL ? { 'deictic.url': op.page } : {}),
594
- 'deictic.viewport': `${op.viewport.width}x${op.viewport.height}`,
870
+ // Not where the file has no such element: the task is the page's, and goes without.
871
+ ...(source instanceof Refusal ? {} : { 'deictic.line': clip(lineOf(source), LABEL) }),
872
+ ...page,
595
873
  'deictic.count': String(op.count),
596
- ...(op.screenshots?.length === 1 && shot !== undefined ? placeOf(shot.box) : {}),
874
+ ...(op.point === undefined ? {} : { [POINT]: `${Math.round(op.point.x)},${Math.round(op.point.y)}` }),
875
+ ...sourceOf(op.chain ?? []),
597
876
  };
598
877
  }
599
878
 
600
- /** Where the element is in the one shot, from its top left, and how big: `87,387` and `138x32`, as the viewport is written. */
601
- function placeOf(box: Box): Record<string, string> {
602
- const [x, y, width, height] = boxOf(box);
603
- return { 'deictic.position': `${x},${y}`, 'deictic.size': `${width}x${height}` };
604
- }
605
-
606
879
  /**
607
880
  * The actors these IDs name, by ID. An actor's ID isn't read for its name (each board writes them its own way), so
608
881
  * the board is asked who they are, and only when there's one to ask about.
@@ -631,6 +904,12 @@ const atOf = ({ loc }: Target) => `${loc.file}:${loc.line}:${loc.column}`;
631
904
  /** The opening tag's first line, as written. */
632
905
  const lineOf = ({ code, element }: Pick<Source, 'code' | 'element'>) => code.slice(element.start, element.end).split('\n', 1)[0]!.trim();
633
906
 
907
+ /** The element's line as a label has it, where the file has it once: a line it has twice says nothing of which element a task was about. */
908
+ function onceIn(source: Source): string | undefined {
909
+ const line = lineOf(source);
910
+ return source.code.split(line).length === 2 ? clip(line, LABEL) : undefined;
911
+ }
912
+
634
913
  /** Where a task says its element is, from its labels. */
635
914
  function placeIn(labels: Record<string, string>): Place | undefined {
636
915
  const [, line, column] = /:(\d+):(\d+)$/.exec(labels[AT] ?? '') ?? [];
@@ -638,30 +917,11 @@ function placeIn(labels: Record<string, string>): Place | undefined {
638
917
  return { line: Number(line), column: Number(column), tag: labels['deictic.tag'] ?? '' };
639
918
  }
640
919
 
641
- /**
642
- * The task's text: what was typed, and after a `---` only what no label holds: what's attached and drawn, the
643
- * source it rendered through, what was pointed at inside it, and a URL too long for a label.
644
- * A board holds 10,000 characters.
645
- */
646
- function textOf(op: Op, target: Target): string {
647
- const more = [
648
- ...(op.page.length <= LABEL ? [] : [op.page]),
649
- ...shotsOf(op.screenshots ?? []),
650
- ...recordingsOf(op.recordings ?? []),
651
- ...voicesOf(op.voice ?? []),
652
- ...(op.annotations === undefined ? [] : [annotated(op.annotations, op.screenshots?.length ?? 0, op.recordings?.length ?? 0)]),
653
- ...chainOf(target, op.chain ?? []),
654
- ...(op.pointed === undefined ? [] : [`Pointed at, inside it: \`${op.pointed.path}\``, fence(op.pointed.html, 'html')]),
655
- ];
656
- const tail = more.length === 0 ? '' : REST + more.join('\n');
657
- return clip(wordsOf(op), 10_000 - tail.length) + tail;
658
- }
659
-
660
920
  /** The task's words: what was typed, or where nothing was, a line that sends the reader to what's attached. */
661
- const wordsOf = (op: Op) => (op.text.trim() === '' ? (shown(op) ?? '') : op.text.trim());
921
+ const wordsOf = (op: Attaching & Pick<Op, 'text'>) => (op.text.trim() === '' ? (shown(op) ?? '') : op.text.trim());
662
922
 
663
923
  /** `See the recording and the voice note`: what stands for the words of a task sent with none, where something is attached. */
664
- function shown(op: Op): string | undefined {
924
+ function shown(op: Attaching): string | undefined {
665
925
  const named = (count: number | undefined, word: string) =>
666
926
  count === undefined || count === 0 ? [] : [`the ${word}${count === 1 ? '' : 's'}`];
667
927
  const attached = [
@@ -669,10 +929,17 @@ function shown(op: Op): string | undefined {
669
929
  ...named(op.recordings?.length, 'recording'),
670
930
  ...named(op.voice?.length, 'voice note'),
671
931
  ];
672
- return attached.length === 0 ? undefined : `See ${new Intl.ListFormat('en', { type: 'conjunction' }).format(attached)}`;
932
+ return attached.length === 0 ? undefined : `See ${conjunction(attached)}`;
933
+ }
934
+
935
+ /** `a screenshot and 2 voice notes`, of `deictic.dropped.N`'s values. */
936
+ function listOf(kinds: string[]): string {
937
+ return conjunction(
938
+ [...Map.groupBy(kinds, (kind) => kind)].map(([kind, all]) => (all.length === 1 ? `a ${kind}` : `${all.length} ${kind}s`)),
939
+ );
673
940
  }
674
941
 
675
- const fence = (text: string, lang: string) => `\`\`\`\`${lang}\n${clip(text, 1500)}\n\`\`\`\``;
942
+ const conjunction = (things: string[]) => new Intl.ListFormat('en', { type: 'conjunction' }).format(things);
676
943
 
677
944
  const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
678
945