deictic 0.6.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 (90) hide show
  1. package/API.md +136 -30
  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/index.d.ts +116 -7
  30. package/dist/shared/index.d.ts.map +1 -1
  31. package/dist/shared/index2.d.ts +9 -19
  32. package/dist/shared/index2.d.ts.map +1 -1
  33. package/dist/shared/index7.d.ts +103 -26
  34. package/dist/shared/index7.d.ts.map +1 -1
  35. package/dist/shared/index9.d.ts +1 -1
  36. package/dist/shared/integration.d.ts +1 -1
  37. package/dist/shared/packages.js +1 -1
  38. package/dist/shared/recording.js +31 -3
  39. package/dist/shared/recording.js.map +1 -1
  40. package/dist/shared/src.js.map +1 -1
  41. package/dist/shared/task.js +44 -29
  42. package/dist/shared/task.js.map +1 -1
  43. package/dist/shared/tasks.js +232 -62
  44. package/dist/shared/tasks.js.map +1 -1
  45. package/dist/shared/vb.js +1 -1
  46. package/dist/shared/voice2.js +6 -4
  47. package/dist/shared/voice2.js.map +1 -1
  48. package/dist/shared/watch.js +14 -14
  49. package/dist/shared/watch.js.map +1 -1
  50. package/dist/tasks/client.d.ts +2 -2
  51. package/dist/tasks/client.d.ts.map +1 -1
  52. package/dist/tasks/client.js +1829 -741
  53. package/dist/tasks/client.js.map +1 -1
  54. package/dist/tasks/index.d.ts +2 -2
  55. package/dist/voice/client.d.ts.map +1 -1
  56. package/dist/voice/client.js +154 -57
  57. package/dist/voice/client.js.map +1 -1
  58. package/package.json +1 -1
  59. package/skills/deictic/SKILL.md +22 -28
  60. package/src/cli/recording.ts +34 -3
  61. package/src/cli/task.ts +59 -30
  62. package/src/cli/voice.ts +9 -4
  63. package/src/cli/watch.ts +14 -13
  64. package/src/client/away.ts +3 -1
  65. package/src/client/component.ts +98 -0
  66. package/src/client/dom.ts +70 -0
  67. package/src/client/drawer.ts +258 -0
  68. package/src/client/index.ts +220 -128
  69. package/src/client/lightbox.ts +8 -8
  70. package/src/client/lighting.ts +279 -0
  71. package/src/client/style.ts +263 -44
  72. package/src/client/tools.ts +279 -0
  73. package/src/client/tooltip.ts +25 -5
  74. package/src/client/tray.ts +48 -0
  75. package/src/index.ts +113 -6
  76. package/src/plugins/annotations/client.ts +103 -129
  77. package/src/plugins/annotations/draw.ts +68 -72
  78. package/src/plugins/annotations/index.ts +12 -19
  79. package/src/plugins/recordings/client.ts +89 -167
  80. package/src/plugins/screenshots/client.ts +53 -2
  81. package/src/plugins/tasks/client.ts +219 -748
  82. package/src/plugins/tasks/composer.ts +797 -0
  83. package/src/plugins/tasks/drawer.ts +516 -0
  84. package/src/plugins/tasks/index.ts +360 -82
  85. package/src/plugins/tasks/pins.ts +275 -0
  86. package/src/plugins/tasks/store.ts +132 -0
  87. package/src/plugins/voice/client.ts +96 -5
  88. package/skills/deictic/references/recordings.md +0 -13
  89. package/skills/deictic/references/tasks.md +0 -22
  90. package/skills/deictic/references/watch.md +0 -17
@@ -17,7 +17,7 @@ import { join, relative } from 'node:path';
17
17
 
18
18
  import type { Board } from '@vercel/board';
19
19
 
20
- 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';
21
21
  // For `use('screenshots')`'s type: the plugin may not be loaded, and nothing of it runs here.
22
22
  import type { Recordings } from '#src/plugins/recordings/index.ts';
23
23
  import type { Box } from '#src/plugins/screenshots/index.ts';
@@ -29,7 +29,7 @@ import { watchersOf } from './watchers.ts';
29
29
  export { local, type LocalBoard, type LocalOptions } from './local.ts';
30
30
 
31
31
  /** What the plugin uses of a board: `board()` from `@vercel/board` is one. */
32
- 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'>;
33
33
 
34
34
  export interface TasksOptions {
35
35
  /**
@@ -82,9 +82,10 @@ export interface Task {
82
82
  link?: string;
83
83
  /** What was attached to it but not kept by the time it was sent, so it went without: `a screenshot`. */
84
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;
85
87
  /**
86
- * Where it was added, where that isn't the element's place: for one of `tasks`, where the element was before
87
- * 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.
88
89
  */
89
90
  at?: Place;
90
91
  }
@@ -96,14 +97,76 @@ export interface Place {
96
97
  tag: string;
97
98
  }
98
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
+
99
164
  export interface Model {
100
165
  channel: string;
101
166
  /** The channel's page, when there's one to link to. */
102
167
  link?: string;
103
168
  /** Tasks about this element, oldest first, canceled ones left out: also those added before it moved. */
104
169
  tasks: Task[];
105
- /** Tasks about the file's other elements, by line, canceled ones left out: each with its `at`. */
106
- elsewhere: Task[];
107
170
  /**
108
171
  * Who watches the channel, by name (`claude`): the agents whose watch (`deictic watch`) is running in
109
172
  * this project, as a board can't say, and those holding a claim on one of the channel's tasks, which it can.
@@ -113,18 +176,17 @@ export interface Model {
113
176
  watching?: string[];
114
177
  }
115
178
 
116
- /**
117
- * What the Task tab asks for: a new task (an `Op`), other words for one it lists (`edit` is its ID), or
118
- * that one deleted (`remove` is its ID), which cancels it on the board.
119
- */
120
- export type Change = Op | { edit: string; text: string } | { remove: string };
121
-
122
179
  /** A new task: what the page knows and the source doesn't. */
123
180
  export interface Op {
124
181
  text: string;
125
182
  /** The page's URL. */
126
183
  page: string;
127
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;
128
190
  /**
129
191
  * What was under the pointer inside the element, where nothing marked it (a dependency's markup, or a
130
192
  * shadow root's): its path from the element, and its HTML, cut short.
@@ -132,6 +194,16 @@ export interface Op {
132
194
  pointed?: { path: string; html: string };
133
195
  /** How many elements on the page come from the same place in the source. */
134
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;
135
207
  /**
136
208
  * The source it rendered through, after its own place, nearest first: where the one before it is used. With
137
209
  * React in development, the components that wrote it, `Field (src/Field.tsx:20)` or a name alone; without, the
@@ -142,11 +214,12 @@ export interface Op {
142
214
  /** The element's HTML as it rendered, to attach: cut short, and masked where the screenshots plugin is loaded. */
143
215
  html?: string;
144
216
  /**
145
- * Shots the screenshots plugin took of it, to attach, where that plugin is loaded: each with where the
146
- * element is in it, whether it's `outlined` there (dashes drawn around it, in the PNG), and the marks drawn
147
- * 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.
148
221
  */
149
- screenshots?: { id: string; box: Box; outlined?: boolean; marks?: Marks }[];
222
+ screenshots?: { id: string; box?: Box; outlined?: boolean; marks?: Marks }[];
150
223
  /**
151
224
  * Recordings the recordings plugin made, to attach, where that plugin is loaded: how long each ran,
152
225
  * where it plays back, and the voice plugin's clips of the mic in it, attached too.
@@ -174,6 +247,11 @@ export interface TaskAdded {
174
247
  page: string;
175
248
  /** How many of each were attached; `marks` counts those drawn on shots and on the page. */
176
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[];
177
255
  }
178
256
 
179
257
  /** Marks, as a task tells of them: how many, and what the notes among them say. */
@@ -191,7 +269,7 @@ export interface Added {
191
269
  attachments?: string[];
192
270
  }
193
271
 
194
- /** 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. */
195
273
  export interface Edited {
196
274
  kind: 'edited';
197
275
  id: string;
@@ -200,18 +278,32 @@ export interface Edited {
200
278
  }
201
279
 
202
280
  /**
203
- * A task deleted in the panel: canceled on the board, for good, as a board has it. So it's kept whole, and
204
- * 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.
205
283
  */
206
284
  export interface Removed extends Added {
207
285
  kind: 'removed';
208
286
  }
209
287
 
210
- /** 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
+ */
211
292
  export type Kept = Added | Edited | Removed;
212
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;
213
303
  const AT = 'deictic.at';
214
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';
215
307
  /** What parts what was typed from the rest of a task's text. */
216
308
  const REST = '\n---\n';
217
309
  /** A file for the board, as the plugins that keep them read it. */
@@ -270,9 +362,11 @@ export function tasks(options: TasksOptions = {}) {
270
362
  * One of this channel's tasks about an element, while it's still open: the page names it by ID, so
271
363
  * nothing else on the board is its to change, nor a task someone has taken up.
272
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;
273
367
  const openTask = async (team: TaskBoard, id: string, verb: string) => {
274
368
  const { message } = await team.thread(id);
275
- if (message.channel !== channel || message.labels[AT] === undefined)
369
+ if (message.channel !== channel || !ours(message))
276
370
  throw new Refusal(`#${id} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);
277
371
 
278
372
  const { task } = message;
@@ -309,14 +403,143 @@ export function tasks(options: TasksOptions = {}) {
309
403
  return { ...record, id: task.id };
310
404
  };
311
405
 
312
- // 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.
313
536
  let context: ServerContext | undefined;
314
537
  let project = options.project;
315
538
  /**
316
539
  * The op with only the screenshots, recordings and voice clips still kept, their files, and what's left out: a file
317
540
  * goes once newer ones pass its plugin's `keep`, or `deictic clean` takes it, and that's no reason to lose the task.
318
541
  */
319
- const keptOf = (op: Op) => {
542
+ const keptOf = <T extends Attaching>(op: T) => {
320
543
  const clipOf = (id: string): ReturnType<Clips['read']> => context?.use('voice')?.read(id);
321
544
  // In the op's order, each kind's: the Nth PNG is `deictic.screenshot.N`'s, the Nth recording `deictic.recording.N`'s.
322
545
  const files: Upload[] = [];
@@ -341,7 +564,12 @@ export function tasks(options: TasksOptions = {}) {
341
564
  if (html !== undefined) files.push({ data: new TextEncoder().encode(html.slice(0, HTML)), name: 'element.html', type: 'text/html' });
342
565
  else if (op.pointed !== undefined)
343
566
  files.push({ data: new TextEncoder().encode(op.pointed.html.slice(0, HTML)), name: 'pointed.html', type: 'text/html' });
344
- const kept: Op = {
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 = {
345
573
  ...op,
346
574
  ...(op.screenshots === undefined ? {} : { screenshots }),
347
575
  ...(op.recordings === undefined ? {} : { recordings }),
@@ -356,7 +584,7 @@ export function tasks(options: TasksOptions = {}) {
356
584
  return Promise.all(files.map(async (file) => (await team.upload(file)).id));
357
585
  };
358
586
 
359
- return definePlugin<Model, Change, Kept>({
587
+ return definePlugin<Model, Op, Kept>({
360
588
  name: 'tasks',
361
589
  client: 'deictic/tasks/client',
362
590
  packages: ['@vercel/board'],
@@ -371,6 +599,64 @@ export function tasks(options: TasksOptions = {}) {
371
599
  // Not waited for: a failure is the first request's to tell.
372
600
  void boardOf().catch(() => {});
373
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
+ },
374
660
  read: (source, target) =>
375
661
  asked(async () => {
376
662
  const team = await boardOf();
@@ -386,34 +672,17 @@ export function tasks(options: TasksOptions = {}) {
386
672
  // Nothing to tell a moved task by where the file has no such element.
387
673
  const line = source instanceof Refusal ? undefined : onceIn(source);
388
674
  const tasks: Task[] = [];
389
- const elsewhere: (Task & { at: Place })[] = [];
390
675
  const about = [...here.tasks.filter((t) => !listed.has(t.message.id)), ...inFile.tasks];
391
676
  // Who has each, and who holds any claim on the channel: asked of the board at once.
392
677
  const actorOf = ({ task }: (typeof about)[number]['message']) => task?.claim?.actor;
393
678
  const claims = held.tasks.flatMap(({ message }) => message.task?.claim ?? []);
394
679
  const actors = await actorsOf(team, [...about.flatMap(({ message }) => actorOf(message) ?? []), ...claims.map((c) => c.actor)]);
395
680
  for (const { message } of about) {
396
- const state = message.task?.state ?? 'ready';
397
- if (state === 'canceled') continue;
398
- const by = actors.get(actorOf(message) ?? '')?.name;
399
- const text = message.text.split(REST, 1)[0]!;
400
- const to = taskLink(page, message.id);
401
- const missing = Object.entries(message.labels).flatMap(([key, value]) => (/^deictic\.dropped\.\d+$/.test(key) ? [value] : []));
402
- const dropped = missing.length === 0 ? undefined : listOf(missing);
403
- const task = {
404
- id: message.id,
405
- title: text.split('\n', 1)[0]!,
406
- text,
407
- state,
408
- ...(by === undefined ? {} : { by }),
409
- open: OPEN.has(state),
410
- ...(to === undefined ? {} : { link: to }),
411
- ...(dropped === undefined ? {} : { dropped }),
412
- };
681
+ if (message.task?.state === 'canceled') continue;
682
+ const task = taskOf(message, actors, page);
413
683
  const at = placeIn(message.labels);
414
684
  if (at === undefined || message.labels[AT] === atOf(target)) tasks.push(task);
415
685
  else if (line !== undefined && at.tag === target.tag && message.labels['deictic.line'] === line) tasks.push({ ...task, at });
416
- else elsewhere.push({ ...task, at });
417
686
  }
418
687
  // An agent at work on a task is here too, though its watch may be over until the task is (`deictic watch --once`).
419
688
  const working = agentsOf(actors, claims);
@@ -425,33 +694,11 @@ export function tasks(options: TasksOptions = {}) {
425
694
  ...(page === undefined ? {} : { link: page }),
426
695
  ...(watching.length > 0 || ours ? { watching } : {}),
427
696
  tasks,
428
- // The board's order (oldest first) among those of one place.
429
- elsewhere: elsewhere.sort((a, b) => (a.at.line === b.at.line ? a.at.column - b.at.column : a.at.line - b.at.line)),
430
697
  };
431
698
  }),
432
699
  apply: (source, target, op) => {
433
- if ('remove' in op) {
434
- return asked(async () => {
435
- const message = await cancel(op.remove, 'deleted in deictic');
436
- // The board's own labels (`board.task`) are its to set on the task an undo adds.
437
- const labels = Object.fromEntries(Object.entries(message.labels).filter(([key]) => !key.startsWith('board.')));
438
- const attachments = message.attachments.map((a) => a.id);
439
- const kept = { channel, id: op.remove, text: message.text, labels, ...(attachments.length === 0 ? {} : { attachments }) };
440
- return { done: { kind: 'removed' as const, ...kept } };
441
- });
442
- }
443
- // A new task may go without words where something attached says it; a task's words are never changed to none.
444
- if (op.text.trim() === '' && ('edit' in op || shown(op) === undefined)) throw new Refusal('say what should change first');
445
- if ('edit' in op) {
446
- return asked(async () => {
447
- const before = (await openTask(await boardOf(), op.edit, 'edit')).text;
448
- // What follows the words in a task added before they were labels (what's attached, what was pointed at) stays.
449
- const rest = before.includes(REST) ? before.slice(before.indexOf(REST)) : '';
450
- const after = clip(op.text.trim(), 10_000 - rest.length) + rest;
451
- await rewrite(op.edit, before, after);
452
- return { done: { kind: 'edited' as const, id: op.edit, before, after } };
453
- });
454
- }
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');
455
702
  const { op: kept, files, dropped } = keptOf(op);
456
703
  const verb = dropped.length === 1 ? "isn't" : "aren't";
457
704
  if (wordsOf(kept) === '') throw new Refusal(`${listOf(dropped)} ${verb} kept any more: attach again, or say what should change`);
@@ -493,12 +740,7 @@ export function tasks(options: TasksOptions = {}) {
493
740
  await cancel(record.id, 'deleted in deictic');
494
741
  return record;
495
742
  }),
496
- describe: (op, before) => {
497
- const named = (id: string) => `task "${clip(before.tasks.find((t) => t.id === id)?.title ?? `#${id}`, 60)}"`;
498
- if ('remove' in op) return `delete ${named(op.remove)}`;
499
- if ('edit' in op) return `edit ${named(op.edit)}`;
500
- return `task "${clip(wordsOf(op).split('\n', 1)[0]!, 60)}"`;
501
- },
743
+ describe: (op) => `task "${clip(wordsOf(op).split('\n', 1)[0]!, 60)}"`,
502
744
  });
503
745
  }
504
746
 
@@ -512,17 +754,44 @@ async function localPage(team: TaskBoard, channel: string): Promise<string | und
512
754
  return `${url.origin}${url.pathname.slice(0, -'/api/board'.length)}/c/${channel.split('/').map(encodeURIComponent).join('/')}`;
513
755
  }
514
756
 
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)}`;
766
+ }
767
+
515
768
  /** What may be left out of a task as no longer kept, as `deictic.dropped.N` names it. */
516
769
  type Kind = 'screenshot' | 'recording' | 'voice clip' | 'voice note';
517
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'>>;
773
+
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 }) };
784
+ });
785
+ }
786
+
518
787
  /**
519
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
520
789
  * text. `deictic.screenshot.N` is the Nth PNG attached: its `.position` and `.size` where the element is in it (CSS
521
- * pixels from its top left), `.note.M` a note drawn on it. `deictic.recording.N.replay` is where the Nth recording
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
522
791
  * plays back; `deictic.note.M` a note drawn on the page; `deictic.dropped.N` what wasn't kept any more;
523
792
  * `deictic.pointed` the path to what was pointed at inside the element. A note past a label is cut.
524
793
  */
525
- function attachedLabels(op: Op, dropped: Kind[]): Record<string, string> {
794
+ function attachedLabels(op: Attaching, dropped: Kind[]): Record<string, string> {
526
795
  const labels: Record<string, string> = {};
527
796
  // A board takes no control characters in a label: a note's lines go on one.
528
797
  const set = (key: string, value: string) => {
@@ -530,12 +799,15 @@ function attachedLabels(op: Op, dropped: Kind[]): Record<string, string> {
530
799
  };
531
800
  for (const [i, { box, marks }] of (op.screenshots ?? []).entries()) {
532
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;
533
805
  const [x, y, width, height] = boxOf(box);
534
806
  set(`${n}.position`, `${x},${y}`);
535
807
  set(`${n}.size`, `${width}x${height}`);
536
- for (const [j, note] of (marks?.notes ?? []).entries()) set(`${n}.note.${j + 1}`, note);
537
808
  }
538
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}>`);
539
811
  // Not cut: half a URL leads nowhere.
540
812
  for (const [i, { replay }] of (op.recordings ?? []).entries()) if (replay.length <= LABEL) set(`recording.${i + 1}.replay`, replay);
541
813
  for (const [i, kind] of dropped.entries()) set(`dropped.${i + 1}`, kind);
@@ -584,16 +856,22 @@ function nameOf(root: string): string | undefined {
584
856
  * `deictic.url` is the page's whole URL, where a label holds it; `deictic.page` is its path.
585
857
  */
586
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
870
  // Not where the file has no such element: the task is the page's, and goes without.
592
871
  ...(source instanceof Refusal ? {} : { 'deictic.line': clip(lineOf(source), LABEL) }),
593
- 'deictic.page': clip(new URL(op.page).pathname, LABEL),
594
- ...(op.page.length <= LABEL ? { 'deictic.url': op.page } : {}),
595
- 'deictic.viewport': `${op.viewport.width}x${op.viewport.height}`,
872
+ ...page,
596
873
  'deictic.count': String(op.count),
874
+ ...(op.point === undefined ? {} : { [POINT]: `${Math.round(op.point.x)},${Math.round(op.point.y)}` }),
597
875
  ...sourceOf(op.chain ?? []),
598
876
  };
599
877
  }
@@ -640,10 +918,10 @@ function placeIn(labels: Record<string, string>): Place | undefined {
640
918
  }
641
919
 
642
920
  /** The task's words: what was typed, or where nothing was, a line that sends the reader to what's attached. */
643
- 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());
644
922
 
645
923
  /** `See the recording and the voice note`: what stands for the words of a task sent with none, where something is attached. */
646
- function shown(op: Op): string | undefined {
924
+ function shown(op: Attaching): string | undefined {
647
925
  const named = (count: number | undefined, word: string) =>
648
926
  count === undefined || count === 0 ? [] : [`the ${word}${count === 1 ? '' : 's'}`];
649
927
  const attached = [