@adroit-app/chat-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.js ADDED
@@ -0,0 +1,2090 @@
1
+ import { accept, answeredForm, argumentHint, askedQuestions, askFor, askRecord, askSubject, askTool, attachmentsOf, ChatController, Completer, collect, commandProvider, contextShare, displayTitle, findTrigger, firstLine, formatBytes, formatDuration, IMAGE_MAX_DIMENSION, imageRefusal, imagesOf, inputStateOf, isWorking, lastTurn, layOut, linkTarget, looksLikePath, money, openAsks, parseLocation, promptOf, questionsLine, resourceLinks, sameInputState, sessionSettings, textOf, tokens, toolDetail, toolDiffs, toolDuration, toolTerminals, waitingTools, } from "@adroit-app/chat-core";
2
+ import { html, LitElement, nothing } from "lit";
3
+ import { repeat } from "lit/directives/repeat.js";
4
+ import { dragsFiles, filesOf, readImage } from "./attach.js";
5
+ import { deliveryOf, emptyCompletionText, movedSelection, placeholderOf, } from "./composer.js";
6
+ import { Follower } from "./follow.js";
7
+ import { numberInput } from "./form.js";
8
+ import { icon, kindIcon } from "./icons.js";
9
+ import { actionOf, chordLabel, keymapOf } from "./keymap.js";
10
+ import { markdownSheet } from "./markdown/frontend.js";
11
+ import { svgElementImage } from "./markdown/picture.js";
12
+ import { fenced, SAFE_MARKDOWN, servedPath, } from "./markdown/render.js";
13
+ import "./markdown/view.js";
14
+ import "./viewer.js";
15
+ import { FONT_SCALE_PROPERTY, fontScaleProperty } from "./scale.js";
16
+ import { chatStyles, documentTokens, tokens as themeTokens } from "./styles.js";
17
+ import { drawnParts } from "./tools.js";
18
+ /** How many of its latest steps a running subagent shows while its card is closed. */
19
+ const LATEST_STEPS = 3;
20
+ /**
21
+ * The Chat: one ACP session's transcript, the asks it waits on, and a
22
+ * composer to prompt it. Its only input is `connection`.
23
+ */
24
+ export class AdroitChat extends LitElement {
25
+ static properties = {
26
+ connection: { attribute: false },
27
+ theme: { reflect: true },
28
+ markdown: { attribute: false },
29
+ toolRenderer: { attribute: false },
30
+ cwd: {},
31
+ files: { attribute: false },
32
+ imageBaseUrl: { attribute: "image-base-url" },
33
+ openTools: { type: Boolean, attribute: "open-tools" },
34
+ keymap: { attribute: false },
35
+ foldThinking: { type: Boolean, attribute: "fold-thinking" },
36
+ toolWrap: { attribute: "tool-wrap" },
37
+ openLocation: { attribute: false },
38
+ openLink: { attribute: false },
39
+ openLocationEnabled: { type: Boolean, attribute: "open-location-enabled" },
40
+ linkifyPaths: { attribute: false },
41
+ titleEditable: { type: Boolean, attribute: "title-editable" },
42
+ agent: { attribute: false },
43
+ _renaming: { state: true },
44
+ _localTitle: { state: true },
45
+ fontScale: { type: Number, attribute: "font-scale" },
46
+ _state: { state: true },
47
+ _draft: { state: true },
48
+ _askIndex: { state: true },
49
+ _composeInstead: { state: true },
50
+ _signInStep: { state: true },
51
+ _completion: { state: true },
52
+ _delivery: { state: true },
53
+ completionProviders: { attribute: false },
54
+ terminalSignIn: { attribute: false },
55
+ imageMaxDimension: { type: Number, attribute: "image-max-dimension" },
56
+ openImage: { attribute: false },
57
+ imageActions: { attribute: false },
58
+ pickImages: { attribute: false },
59
+ _attachments: { state: true },
60
+ _rejected: { state: true },
61
+ _dropping: { state: true },
62
+ _lightbox: { state: true },
63
+ };
64
+ static styles = [themeTokens, chatStyles, documentTokens];
65
+ #controller = null;
66
+ #unsubscribe = null;
67
+ #follower = null;
68
+ #tools = new Set();
69
+ /** Tool box sections the user switched against `toolWrap`, by call and section. */
70
+ #rewrapped = new Set();
71
+ /** The view the user switched a tool's output to, by the box and its views; the first when none. */
72
+ #views = new Map();
73
+ /** Thinking the user folded or opened, against `foldThinking`. */
74
+ #thoughts = new Set();
75
+ #cards = new Set();
76
+ #completer = new Completer(80, (items) => {
77
+ if (this._completion)
78
+ this._completion = { ...this._completion, items, loading: false };
79
+ });
80
+ /** Paths accepted in the draft, sent beside it as resource links while still written. */
81
+ #accepted = [];
82
+ #inputState = inputStateOf(null, {});
83
+ #asking = false;
84
+ #askFocused = false;
85
+ /** The thinking tokens of each turn, by the turn's last reply. */
86
+ #replyTokens = new Map();
87
+ #dark = matchMedia("(prefers-color-scheme: dark)");
88
+ constructor() {
89
+ super();
90
+ this.connection = null;
91
+ this.markdown = {};
92
+ this.toolRenderer = null;
93
+ this.cwd = null;
94
+ this.files = null;
95
+ this.imageBaseUrl = null;
96
+ this.openTools = false;
97
+ this.keymap = null;
98
+ this.foldThinking = false;
99
+ this.toolWrap = "wrap";
100
+ this.openLocation = null;
101
+ this.openLink = null;
102
+ this.openLocationEnabled = false;
103
+ this.linkifyPaths = true;
104
+ this.fontScale = null;
105
+ this.titleEditable = true;
106
+ this.agent = null;
107
+ this._renaming = false;
108
+ this._localTitle = null;
109
+ this._state = null;
110
+ this._draft = "";
111
+ this._askIndex = 0;
112
+ this._composeInstead = false;
113
+ this._completion = null;
114
+ this._delivery = "after";
115
+ this.completionProviders = [];
116
+ this._signInStep = null;
117
+ this.terminalSignIn = null;
118
+ this.imageMaxDimension = IMAGE_MAX_DIMENSION;
119
+ this.openImage = null;
120
+ this.imageActions = null;
121
+ this.pickImages = null;
122
+ this._attachments = [];
123
+ this._rejected = [];
124
+ this._dropping = false;
125
+ this._lightbox = null;
126
+ }
127
+ /** The Chat's own provider, the agent's `/` commands, then the host's. */
128
+ get #providers() {
129
+ return [this.#commandProvider, ...this.completionProviders];
130
+ }
131
+ #commandProvider = commandProvider(() => this._state?.commands ?? []);
132
+ /**
133
+ * What the provider for `trigger` completes `query` with: the same
134
+ * providers the composer uses, for a host's own input to show its own way.
135
+ */
136
+ async complete(trigger, query, signal) {
137
+ const provider = this.#providers.find((p) => typeof p.trigger === "string" ? p.trigger === trigger : p.trigger.test(trigger));
138
+ if (!provider)
139
+ return [];
140
+ return collect(provider.complete(query, { signal: signal ?? new AbortController().signal }));
141
+ }
142
+ /** The controller of the session shown; none before a connection is set. */
143
+ get controller() {
144
+ return this.#controller;
145
+ }
146
+ /**
147
+ * Sends `text`, with any images, as a prompt, as the composer does.
148
+ * Delivered with `steer`, it stops the work running and runs first when
149
+ * `canSteer`; otherwise the agent takes it in when it can.
150
+ */
151
+ send(text, options = {}) {
152
+ // Without images of its own, a prompt takes the ones attached in the composer.
153
+ if (options.images === undefined && this._attachments.length > 0) {
154
+ const images = this._attachments.map(({ data, mimeType }) => ({ data, mimeType }));
155
+ this.clearAttachments();
156
+ this.send(text, { ...options, images });
157
+ return;
158
+ }
159
+ const sent = promptOf(text, options, this.#inputState);
160
+ if (sent)
161
+ this.#controller?.send(sent.prompt, { steer: sent.steer });
162
+ }
163
+ /** Stops the work running, as the stop key does in the Chat. */
164
+ /** The agent takes images with a prompt (ACP's prompt capabilities): images can be attached. */
165
+ get imagesAllowed() {
166
+ return this.connection?.promptCapabilities?.image === true;
167
+ }
168
+ /** The images attached to the next prompt, in the order attached. */
169
+ get attachments() {
170
+ return this._attachments;
171
+ }
172
+ /**
173
+ * Attaches `files` to the next prompt: each image scaled down to
174
+ * `imageMaxDimension`; a file that is no image the agent takes, or any
175
+ * file while the agent takes none, is listed as refused instead. A host that read
176
+ * a file and could not take it passes `{ refused }` with why.
177
+ */
178
+ async attach(files) {
179
+ for (const file of files) {
180
+ if (!(file instanceof Blob)) {
181
+ this._rejected = [...this._rejected, { id: crypto.randomUUID(), text: file.refused }];
182
+ continue;
183
+ }
184
+ const name = file instanceof File ? file.name : "image";
185
+ const refusal = this.imagesAllowed
186
+ ? imageRefusal({ name, type: file.type, size: file.size })
187
+ : `${name}: the agent takes no images`;
188
+ if (refusal) {
189
+ this._rejected = [...this._rejected, { id: crypto.randomUUID(), text: refusal }];
190
+ continue;
191
+ }
192
+ try {
193
+ const read = await readImage(file, this.imageMaxDimension);
194
+ this._attachments = [...this._attachments, { id: crypto.randomUUID(), name, ...read }];
195
+ }
196
+ catch (error) {
197
+ const why = error instanceof Error ? error.message : String(error);
198
+ this._rejected = [...this._rejected, { id: crypto.randomUUID(), text: `${name}: ${why}` }];
199
+ }
200
+ }
201
+ this.#attachmentsChanged();
202
+ }
203
+ /** Takes the attached image `id` off the next prompt. */
204
+ removeAttachment(id) {
205
+ this._attachments = this._attachments.filter((a) => a.id !== id);
206
+ this.#attachmentsChanged();
207
+ }
208
+ /** Takes every attached image off the next prompt, and the refusals with them. */
209
+ clearAttachments() {
210
+ this._attachments = [];
211
+ this._rejected = [];
212
+ this.#attachmentsChanged();
213
+ }
214
+ #attachmentsChanged() {
215
+ this.dispatchEvent(new CustomEvent("attachments-change", {
216
+ detail: { attachments: this._attachments },
217
+ bubbles: true,
218
+ composed: true,
219
+ }));
220
+ }
221
+ /** Shows `image` on its own: the host's way, or over the Chat when the host has none. */
222
+ #showImage(image) {
223
+ if (this.openImage?.(image) === true)
224
+ return;
225
+ const open = this.dispatchEvent(new CustomEvent("open-image", {
226
+ detail: image,
227
+ bubbles: true,
228
+ composed: true,
229
+ cancelable: true,
230
+ }));
231
+ if (!open)
232
+ return;
233
+ this._lightbox = image;
234
+ // Its keys (zoom, copy, Escape) go to the viewer at once.
235
+ void this.updateComplete.then(() => this.renderRoot.querySelector(".lightbox adroit-image-viewer")?.focus());
236
+ }
237
+ /** Lets the user choose images to attach: the host's dialog, or the page's file input. */
238
+ async #pick() {
239
+ if (this.pickImages) {
240
+ await this.attach(await this.pickImages());
241
+ return;
242
+ }
243
+ this.renderRoot.querySelector("input.pick")?.click();
244
+ }
245
+ stop() {
246
+ if (this.#inputState.working)
247
+ this.#controller?.cancel();
248
+ }
249
+ /** The keys in effect: `keymap` over the default, for a host's own input to read too. */
250
+ get effectiveKeymap() {
251
+ return keymapOf(this.keymap);
252
+ }
253
+ /** The agent is working in the foreground, or waiting on the user. */
254
+ get working() {
255
+ return this.#inputState.working;
256
+ }
257
+ /** A prompt sent now with `delivery: "steer"` stops the work running and runs first. */
258
+ get canSteer() {
259
+ return this.#inputState.canSteer;
260
+ }
261
+ /** How many asks the agent waits on the user's answer to. */
262
+ get openAsks() {
263
+ return this.#inputState.openAsks;
264
+ }
265
+ /** An ask is shown in the composer's place, waiting for the user's answer. */
266
+ get asking() {
267
+ return this.#asking;
268
+ }
269
+ /**
270
+ * The session's title as the header shows it: the name given here, the
271
+ * agent's, the first prompt's first line, or "New session".
272
+ */
273
+ get sessionTitle() {
274
+ return displayTitle(this._state ?? { title: null, entries: [] }, this._localTitle);
275
+ }
276
+ /**
277
+ * Renames the session to `title`: through the agent (`session/set_title`)
278
+ * when it can; otherwise a cancelable `rename-session` event tells the
279
+ * host, which may keep the name itself. The header shows the name either
280
+ * way, until the agent reports a title after it.
281
+ */
282
+ async rename(title) {
283
+ const name = title.trim();
284
+ if (!name || name === this.sessionTitle)
285
+ return;
286
+ this._localTitle = name;
287
+ this.#titleAtRename = this._state?.title ?? null;
288
+ const setTitle = this.connection?.setTitle;
289
+ if (setTitle) {
290
+ try {
291
+ await setTitle.call(this.connection, name);
292
+ }
293
+ catch (error) {
294
+ console.warn("adroit-chat: the agent did not take the title", error);
295
+ }
296
+ return;
297
+ }
298
+ this.dispatchEvent(new CustomEvent("rename-session", {
299
+ detail: { title: name },
300
+ bubbles: true,
301
+ composed: true,
302
+ cancelable: true,
303
+ }));
304
+ }
305
+ /** The agent's title when the user last renamed the session. */
306
+ #titleAtRename = null;
307
+ /** The title last told by `title-change`. */
308
+ #toldTitle = null;
309
+ /** Tells the host, by `title-change`, when the title shown has changed. */
310
+ #titleChanged() {
311
+ const agent = this._state?.title ?? null;
312
+ // A title the agent reports after a rename is the session's own again.
313
+ if (this._localTitle !== null && agent !== this.#titleAtRename)
314
+ this._localTitle = null;
315
+ const title = this.sessionTitle;
316
+ if (title === this.#toldTitle)
317
+ return;
318
+ this.#toldTitle = title;
319
+ this.dispatchEvent(new CustomEvent("title-change", {
320
+ detail: { title },
321
+ bubbles: true,
322
+ composed: true,
323
+ }));
324
+ }
325
+ /** Shows the composer though the agent waits on an answer, or the ask again. */
326
+ composeInstead(compose = true) {
327
+ this._composeInstead = compose;
328
+ }
329
+ /** The slash commands the agent offers. */
330
+ get commands() {
331
+ return this.#inputState.commands;
332
+ }
333
+ /**
334
+ * Moves focus to the input: the ask shown in the composer's place, or else
335
+ * the element in the `composer` slot, or the Chat's own composer.
336
+ */
337
+ focusInput() {
338
+ const asking = this.renderRoot.querySelector(".asking");
339
+ if (asking) {
340
+ asking.focus();
341
+ return;
342
+ }
343
+ const slotted = this.querySelector(':scope > [slot="composer"]');
344
+ (slotted ?? this.renderRoot.querySelector("textarea"))?.focus();
345
+ }
346
+ /** Moves focus to the transcript, where the keys scroll it and answer asks. */
347
+ focusTranscript() {
348
+ this.renderRoot.querySelector(".parts")?.focus();
349
+ }
350
+ /** Scrolls the transcript to its start, as a reader going back up does. */
351
+ scrollToStart() {
352
+ const scroller = this.renderRoot.querySelector(".parts");
353
+ if (scroller)
354
+ scroller.scrollTop = 0;
355
+ }
356
+ connectedCallback() {
357
+ super.connectedCallback();
358
+ this.#dark.addEventListener("change", this.#retheme);
359
+ this.addEventListener("keydown", this.#onKey);
360
+ }
361
+ disconnectedCallback() {
362
+ super.disconnectedCallback();
363
+ this.#dark.removeEventListener("change", this.#retheme);
364
+ this.removeEventListener("keydown", this.#onKey);
365
+ this.#follower?.dispose();
366
+ if (this.#ticker !== null)
367
+ clearInterval(this.#ticker);
368
+ this.#ticker = null;
369
+ this.#follower = null;
370
+ }
371
+ firstUpdated() {
372
+ const root = this.renderRoot;
373
+ root.adoptedStyleSheets = [markdownSheet(), ...root.adoptedStyleSheets];
374
+ }
375
+ willUpdate(changed) {
376
+ if (changed.has("fontScale")) {
377
+ const scale = fontScaleProperty(this.fontScale);
378
+ if (scale === null)
379
+ this.style.removeProperty(FONT_SCALE_PROPERTY);
380
+ else
381
+ this.style.setProperty(FONT_SCALE_PROPERTY, scale);
382
+ }
383
+ if (changed.has("_composeInstead"))
384
+ this.#inputChanged();
385
+ if (changed.has("_state") || changed.has("_localTitle"))
386
+ this.#titleChanged();
387
+ if (changed.has("connection")) {
388
+ this.#unsubscribe?.();
389
+ this.#controller?.dispose();
390
+ this.#controller = this.connection ? new ChatController(this.connection) : null;
391
+ this._state = this.#controller?.state ?? null;
392
+ this.#inputChanged();
393
+ this.#unsubscribe =
394
+ this.#controller?.subscribe((state) => {
395
+ this._state = state;
396
+ this.#inputChanged();
397
+ }) ?? null;
398
+ }
399
+ }
400
+ updated(changed) {
401
+ this.toggleAttribute("data-can-open", this.#canOpen);
402
+ // The chosen completion stays in view as it moves, and as items come or go.
403
+ if (changed.has("_completion")) {
404
+ this.renderRoot
405
+ .querySelector(".commands .command.selected")
406
+ ?.scrollIntoView({ block: "nearest" });
407
+ }
408
+ this.#tick();
409
+ const area = this.renderRoot.querySelector(".asking");
410
+ // An ask that takes the composer's place takes its focus too.
411
+ if (area && !this.#askFocused && this.#hasFocus())
412
+ area.focus();
413
+ this.#askFocused = area !== null;
414
+ void changed;
415
+ const scroller = this.renderRoot.querySelector(".parts");
416
+ const inner = this.renderRoot.querySelector(".parts-inner");
417
+ if (scroller && inner && !this.#follower) {
418
+ this.#follower = new Follower(scroller, inner, this.renderRoot.querySelector(".jump-latest"));
419
+ }
420
+ }
421
+ #retheme = () => this.requestUpdate();
422
+ /** Files can be opened: the host said so, or gave `openLocation`. */
423
+ get #canOpen() {
424
+ return this.openLocationEnabled || this.openLocation !== null;
425
+ }
426
+ /** Asks the host to open `location`; the Chat does nothing else with it. */
427
+ #open(location, source, toolCallId) {
428
+ const detail = { ...location, source, ...(toolCallId ? { toolCallId } : {}) };
429
+ if (this.openLocation?.(detail) === true)
430
+ return;
431
+ this.dispatchEvent(new CustomEvent("open-location", {
432
+ detail,
433
+ bubbles: true,
434
+ composed: true,
435
+ cancelable: true,
436
+ }));
437
+ }
438
+ #openUrl(url) {
439
+ if (this.openLink?.(url) === true)
440
+ return;
441
+ this.dispatchEvent(new CustomEvent("open-link", {
442
+ detail: { url },
443
+ bubbles: true,
444
+ composed: true,
445
+ cancelable: true,
446
+ }));
447
+ }
448
+ /** A path written in the Chat, drawn as a link when the host opens files. */
449
+ #pathLink(written, source, toolCallId) {
450
+ const location = parseLocation(written, this.cwd);
451
+ if (!this.#canOpen || !location)
452
+ return written;
453
+ return html `<a
454
+ class="loc"
455
+ href="#"
456
+ title="Open ${location.absolutePath ?? location.path}"
457
+ @click=${(e) => {
458
+ e.preventDefault();
459
+ this.#open(location, source, toolCallId);
460
+ }}
461
+ >${written}</a>`;
462
+ }
463
+ /**
464
+ * Links in the transcript's Markdown never navigate the webview: files go
465
+ * to the host as `open-location`, web and mail links as `open-link`; inline
466
+ * code in a reply that names a file under the session's folder opens it too.
467
+ */
468
+ #onTranscriptClick = (e) => {
469
+ const path = e.composedPath().filter((n) => n instanceof Element);
470
+ const inMarkdown = path.some((n) => n.classList?.contains("markdown-body"));
471
+ // An svg block switches between its image and its code.
472
+ const toggle = path.find((n) => n.hasAttribute("data-svg-toggle"));
473
+ const block = toggle?.closest(".svg-block");
474
+ if (block) {
475
+ e.preventDefault();
476
+ block.dataset.svgView = block.dataset.svgView === "code" ? "image" : "code";
477
+ return;
478
+ }
479
+ // A diagram drawn from the Markdown opens on its own, as an image does.
480
+ const diagram = path.find((n) => n instanceof SVGSVGElement && n.parentElement?.matches("pre.preprocessed-mermaid") === true);
481
+ if (diagram && inMarkdown) {
482
+ e.preventDefault();
483
+ this.#showImage({ ...svgElementImage(diagram), name: "Diagram", source: "markdown" });
484
+ return;
485
+ }
486
+ // An image the policy let into Markdown opens on its own.
487
+ const picture = path.find((n) => n instanceof HTMLImageElement);
488
+ if (picture && inMarkdown) {
489
+ e.preventDefault();
490
+ const src = picture.currentSrc || picture.src;
491
+ const file = servedPath(src, this.imageBaseUrl);
492
+ this.#showImage({
493
+ src,
494
+ ...(picture.alt ? { name: picture.alt } : file ? { name: file.split("/").pop() } : {}),
495
+ ...(file ? { path: file } : {}),
496
+ source: "markdown",
497
+ });
498
+ return;
499
+ }
500
+ // arto-markdown draws a link to a file as a span carrying its target.
501
+ const anchor = path.find((n) => (n.tagName === "A" && n.hasAttribute("href")) || n.hasAttribute("data-md-link"));
502
+ if (anchor && !anchor.classList.contains("loc")) {
503
+ const href = anchor.getAttribute("href") ?? anchor.getAttribute("data-md-link") ?? "";
504
+ if (href.startsWith("#"))
505
+ return;
506
+ e.preventDefault();
507
+ const target = linkTarget(href, this.cwd);
508
+ if (target?.type === "link")
509
+ this.#openUrl(target.url);
510
+ if (target?.type === "location") {
511
+ const mention = (anchor.textContent ?? "").startsWith("@");
512
+ this.#open(target.location, mention ? "mention" : "link");
513
+ }
514
+ return;
515
+ }
516
+ const code = path.find((n) => n.tagName === "CODE");
517
+ if (!code || !this.#canOpen || !this.linkifyPaths || path.some((n) => n.tagName === "PRE")) {
518
+ return;
519
+ }
520
+ if (!path.some((n) => n.classList?.contains("agent")))
521
+ return;
522
+ const text = code.textContent ?? "";
523
+ const location = looksLikePath(text, this.cwd) ? parseLocation(text, this.cwd) : null;
524
+ if (location)
525
+ this.#open(location, "code");
526
+ };
527
+ /** Marks inline code that would open a file, so it reads as clickable under the pointer. */
528
+ #onTranscriptOver = (e) => {
529
+ if (!this.#canOpen || !this.linkifyPaths)
530
+ return;
531
+ const code = e
532
+ .composedPath()
533
+ .find((n) => n instanceof Element && n.tagName === "CODE");
534
+ if (!code || code.closest("pre") || !code.closest(".message.agent"))
535
+ return;
536
+ code.classList.toggle("loc-code", looksLikePath(code.textContent ?? "", this.cwd));
537
+ };
538
+ #ticker = null;
539
+ /** While a timed call runs, redraws once a second so its count runs. */
540
+ #tick() {
541
+ const running = (this._state?.entries ?? []).some((e) => e.kind === "tool" && e.times && e.times.startedAt !== null && e.times.endedAt === null);
542
+ if (running && this.#ticker === null) {
543
+ this.#ticker = setInterval(() => this.requestUpdate(), 1000);
544
+ }
545
+ else if (!running && this.#ticker !== null) {
546
+ clearInterval(this.#ticker);
547
+ this.#ticker = null;
548
+ }
549
+ }
550
+ /** Tells the host, by `input-state-change`, when what an input needs has changed. */
551
+ #inputChanged() {
552
+ const next = inputStateOf(this._state, this.#controller?.abilities ?? {});
553
+ const asking = this._state?.signIn != null || (next.openAsks > 0 && !this._composeInstead);
554
+ if (sameInputState(next, this.#inputState) && asking === this.#asking)
555
+ return;
556
+ this.#inputState = next;
557
+ this.#asking = asking;
558
+ this.dispatchEvent(new CustomEvent("input-state-change", {
559
+ detail: { ...next, asking },
560
+ bubbles: true,
561
+ composed: true,
562
+ }));
563
+ }
564
+ get #themeName() {
565
+ return this.theme ?? (this.#dark.matches ? "dark" : "light");
566
+ }
567
+ get #policy() {
568
+ return { ...SAFE_MARKDOWN, ...this.markdown };
569
+ }
570
+ get #host() {
571
+ return {
572
+ basePath: `${(this.cwd ?? "/").replace(/\/$/, "")}/.chat.md`,
573
+ files: this.files,
574
+ deferredImageBaseUrl: this.imageBaseUrl,
575
+ };
576
+ }
577
+ render() {
578
+ const state = this._state;
579
+ return html `<div
580
+ class="chat ${this._dropping ? "dropping" : ""}"
581
+ @dragenter=${this.#onDrag}
582
+ @dragover=${this.#onDrag}
583
+ @dragleave=${(e) => {
584
+ // Leaving for a part of the Chat is not leaving the Chat.
585
+ if (!(e.relatedTarget instanceof Node && this.renderRoot.contains(e.relatedTarget))) {
586
+ this._dropping = false;
587
+ }
588
+ }}
589
+ @drop=${this.#onDrop}
590
+ >
591
+ ${this.#head(state)}
592
+ <div class="parts-wrap">
593
+ <div
594
+ class="parts"
595
+ tabindex="-1"
596
+ @click=${this.#onTranscriptClick}
597
+ @pointerover=${this.#onTranscriptOver}
598
+ >
599
+ <div class="parts-inner">${state ? this.#transcript(state) : nothing}</div>
600
+ ${!state || (state.entries.length === 0 && !state.pending.some((p) => p.sending))
601
+ ? this.#empty(state)
602
+ : nothing}
603
+ </div>
604
+ <button class="jump-latest" tabindex="-1" title="Go to the newest output">
605
+ ${icon("arrowBarToDown", 14)} New output
606
+ </button>
607
+ </div>
608
+ ${state ? this.#foot(state) : nothing}
609
+ ${state ? this.#retry(state) : nothing}
610
+ ${state?.signIn ? this.#signIn(state) : state ? this.#asks(state) : nothing}
611
+ <slot name="composer" ?hidden=${this.#asking}>${this.#composer(state)}</slot>
612
+ ${this._dropping
613
+ ? html `<div class="drop-target" aria-hidden="true">
614
+ ${icon("photo", 22)}<span>${this.imagesAllowed ? "Drop images to attach them" : "The agent takes no images"}</span>
615
+ </div>`
616
+ : nothing}
617
+ ${this._lightbox ? this.#lightboxView(this._lightbox) : nothing}
618
+ </div>`;
619
+ }
620
+ /** An image in the transcript, small, opening on its own on a click. */
621
+ #imageThumb(image, source) {
622
+ return html `<button
623
+ type="button"
624
+ class="image-thumb"
625
+ title="Show the image"
626
+ aria-label="Show the image"
627
+ @click=${() => this.#showImage({
628
+ data: image.data,
629
+ mimeType: image.mimeType,
630
+ ...(image.name !== undefined ? { name: image.name } : {}),
631
+ ...(image.path !== undefined ? { path: image.path } : {}),
632
+ source,
633
+ })}
634
+ >
635
+ <img alt="" src="data:${image.mimeType};base64,${image.data}" />
636
+ </button>`;
637
+ }
638
+ #onDrag = (e) => {
639
+ if (!dragsFiles(e.dataTransfer))
640
+ return;
641
+ e.preventDefault();
642
+ if (e.dataTransfer)
643
+ e.dataTransfer.dropEffect = this.imagesAllowed ? "copy" : "none";
644
+ this._dropping = true;
645
+ };
646
+ #onDrop = (e) => {
647
+ if (!dragsFiles(e.dataTransfer))
648
+ return;
649
+ e.preventDefault();
650
+ this._dropping = false;
651
+ void this.attach(filesOf(e.dataTransfer));
652
+ };
653
+ /** An image shown over the Chat, for a host that does not open images itself: zoomed, panned, copied and shared as in a window. */
654
+ #lightboxView(image) {
655
+ const close = () => {
656
+ this._lightbox = null;
657
+ this.focusInput();
658
+ };
659
+ return html `<div
660
+ class="lightbox"
661
+ role="dialog"
662
+ aria-label=${image.name ?? "Image"}
663
+ @click=${(e) => {
664
+ if (e.target === e.currentTarget)
665
+ close();
666
+ }}
667
+ >
668
+ <adroit-image-viewer
669
+ closable
670
+ .image=${image}
671
+ .actions=${this.imageActions}
672
+ theme=${this.#themeName}
673
+ @close=${close}
674
+ ></adroit-image-viewer>
675
+ </div>`;
676
+ }
677
+ #markdown(source, options = {}) {
678
+ return html `<adroit-markdown
679
+ .source=${source}
680
+ .policy=${{ ...this.#policy, ...options }}
681
+ .host=${this.#host}
682
+ theme=${this.#themeName}
683
+ ></adroit-markdown>`;
684
+ }
685
+ #code(language, text) {
686
+ return this.#markdown(fenced(language, text));
687
+ }
688
+ /** The header's title: renamed in place on a click, Enter or F2. */
689
+ #title() {
690
+ const title = this.sessionTitle;
691
+ if (this._renaming) {
692
+ const done = (save, input) => {
693
+ if (!this._renaming)
694
+ return;
695
+ this._renaming = false;
696
+ if (save)
697
+ void this.rename(input.value);
698
+ };
699
+ return html `<input
700
+ class="title-field"
701
+ aria-label="The session's title"
702
+ .value=${title}
703
+ @keydown=${(e) => {
704
+ if (e.isComposing)
705
+ return;
706
+ if (e.key === "Enter") {
707
+ e.preventDefault();
708
+ done(true, e.target);
709
+ }
710
+ else if (e.key === "Escape") {
711
+ e.preventDefault();
712
+ e.stopPropagation();
713
+ done(false, e.target);
714
+ }
715
+ }}
716
+ @blur=${(e) => done(false, e.target)}
717
+ />`;
718
+ }
719
+ if (!this.titleEditable || !this._state) {
720
+ return html `<span class="title">${title}</span>`;
721
+ }
722
+ const start = async () => {
723
+ this._renaming = true;
724
+ await this.updateComplete;
725
+ const field = this.renderRoot.querySelector(".title-field");
726
+ field?.focus();
727
+ field?.select();
728
+ };
729
+ return html `<button
730
+ class="title"
731
+ title="Rename the session (F2)"
732
+ @click=${start}
733
+ @keydown=${(e) => {
734
+ if (e.key !== "F2")
735
+ return;
736
+ e.preventDefault();
737
+ void start();
738
+ }}
739
+ >${title}</button>`;
740
+ }
741
+ /** Which agent runs the session, with its model, effort and mode as far as they are known. */
742
+ #about(state) {
743
+ const settings = sessionSettings(state?.configOptions ?? [], this.agent ?? {});
744
+ const name = this.agent?.name;
745
+ if (!name && settings.length === 0)
746
+ return nothing;
747
+ const lines = [
748
+ ...(name ? [`Agent: ${name}`] : []),
749
+ ...settings.map((s) => `${s.label}: ${s.value}`),
750
+ ];
751
+ return html `<span class="about" title=${lines.join("\n")}
752
+ >${name ? html `<span class="agent">${name}</span>` : nothing}${settings.map((s) => html `<span class=${`setting ${s.category}`}>${s.value}</span>`)}</span
753
+ >`;
754
+ }
755
+ #head(state) {
756
+ const turn = state ? lastTurn(state) : undefined;
757
+ const working = state ? isWorking(state) : false;
758
+ const usage = turn?.outcome === "ended" && turn.usage ? turn.usage : null;
759
+ const context = state?.context;
760
+ return html `<header class="head">
761
+ ${this.#title()}
762
+ ${this._renaming ? nothing : html `${this.#about(state)}<span class="spacer-title"></span>`}
763
+ ${state?.account
764
+ ? state.account.signedIn
765
+ ? state.account.label
766
+ ? html `<span class="meta account" title="Signed in">${state.account.label}</span>`
767
+ : nothing
768
+ : html `<span class="ended blocked">Signed out</span>`
769
+ : nothing}
770
+ ${working
771
+ ? state?.activity === "requires_action"
772
+ ? html `<span class="ended blocked">Waiting for you</span>`
773
+ : html `<span class="ended running">Working</span>`
774
+ : turn?.outcome === "failed"
775
+ ? html `<span class="ended failed" title=${turn.error ?? ""}>failed: ${turn.error}</span>`
776
+ : turn?.outcome === "cancelled"
777
+ ? html `<span class="ended cancelled">interrupted</span>`
778
+ : turn?.stopReason && turn.stopReason !== "end_turn"
779
+ ? html `<span class="ended cancelled">stopped: ${turn.stopReason.replaceAll("_", " ")}</span>`
780
+ : nothing}
781
+ ${usage ? html `<span class="meta">${tokens(usage.inputTokens)} in · ${tokens(usage.outputTokens)} out</span>` : nothing}
782
+ ${context
783
+ ? html `<span class="sep"></span
784
+ ><span class="meta" title="${context.used} of ${context.size} tokens"
785
+ >${contextShare(context)} of context${context.cost ? html ` · ${money(context.cost)}` : nothing}</span
786
+ >`
787
+ : nothing}
788
+ </header>`;
789
+ }
790
+ #empty(state) {
791
+ return html `<div class="empty">
792
+ ${icon("messageUp", 28)}
793
+ <strong>${state ? "Nothing said yet" : "Not connected"}</strong>
794
+ <span>${state?.signIn ? "Sign in below to start." : state ? "Write below to start." : "The Chat shows a session once it is connected to one."}</span>
795
+ </div>`;
796
+ }
797
+ #transcript(state) {
798
+ this.#replyTokens = replyTokens(state.entries);
799
+ const rows = layOut(state.entries);
800
+ const last = lastMessage(state.entries);
801
+ // A turn is drawn by how it went wrong, if it did, after its last line.
802
+ const items = [];
803
+ let turn = null;
804
+ const ended = () => {
805
+ const t = turn;
806
+ if (t && (t.outcome === "failed" || t.outcome === "cancelled")) {
807
+ items.push({ key: `end:${t.id}`, draw: () => this.#turnEnd(t) });
808
+ }
809
+ };
810
+ for (const row of rows) {
811
+ const entry = row.type === "entry" ? state.entries[row.index] : undefined;
812
+ if (entry?.kind === "turn") {
813
+ ended();
814
+ turn = entry;
815
+ continue;
816
+ }
817
+ items.push({ key: keyOf(row, state.entries), draw: () => this.#row(row, state, last) });
818
+ }
819
+ ended();
820
+ for (const p of state.pending) {
821
+ if (p.sending)
822
+ items.push({ key: `sending:${p.id}`, draw: () => this.#user(p.prompt, true) });
823
+ }
824
+ return html `${repeat(items, (item) => item.key, (item) => item.draw())}
825
+ ${isWorking(state)
826
+ ? html `<div class="working ${state.activity === "requires_action" ? "blocked" : ""}">
827
+ ${state.activity === "requires_action"
828
+ ? html `${icon("alertTriangle", 12)} Waiting for you`
829
+ : html `<span class="dots"><span></span><span></span><span></span></span
830
+ ><span class="shimmer">Working</span>`}
831
+ </div>`
832
+ : nothing}`;
833
+ }
834
+ #row(row, state, last) {
835
+ const entries = state.entries;
836
+ switch (row.type) {
837
+ case "quiet": {
838
+ const tool = entries[row.index];
839
+ return html `<div class="part row quiet">
840
+ <span class="status"></span><span class="kind">${icon(kindIcon(tool.toolKind), 13)}</span
841
+ ><span class="title">${inline(tool.title || tool.toolKind)}</span>
842
+ </div>`;
843
+ }
844
+ case "subagent":
845
+ return this.#subagent(state, row.sessionId, entries[row.index]);
846
+ case "entry":
847
+ return this.#entry(entries[row.index], state, last, state);
848
+ }
849
+ }
850
+ #entry(entry, state, last, transcript) {
851
+ switch (entry.kind) {
852
+ case "user":
853
+ return this.#user(entry.content);
854
+ case "agent":
855
+ return this.#agent(entry, isWorking(transcript) && entry === last);
856
+ case "thought":
857
+ return this.#thought(entry, isWorking(transcript) && entry === last);
858
+ case "session-message":
859
+ return this.#fromParent(entry);
860
+ case "tool":
861
+ return this.#tool(entry, transcript);
862
+ case "turn":
863
+ return nothing;
864
+ case "ask":
865
+ return this.#ask(entry, state);
866
+ case "notice":
867
+ return this.#notice(entry);
868
+ case "compaction":
869
+ return this.#compaction(entry);
870
+ case "subagent":
871
+ return this.#subagent(state, entry.id, entry);
872
+ }
873
+ }
874
+ #user(content, sending = false) {
875
+ return html `<div class="part message user ${sending ? "sending" : ""}">
876
+ <div class="who">
877
+ ${icon("messageUp", 13)} You${sending ? html `<span class="sending-mark">Sending…</span>` : nothing}
878
+ </div>
879
+ ${this.#markdown(this.#mentions(textOf(content)))} ${this.#attachments(content)}
880
+ </div>`;
881
+ }
882
+ /** The user's `@path` mentions as links, when the host opens files. */
883
+ #mentions(text) {
884
+ if (!this.#canOpen)
885
+ return text;
886
+ return text.replace(/(^|\s)@([\w./-]*[\w/])(?=\s|$)/g, (whole, space, path) => looksLikePath(path, this.cwd) || path.endsWith("/") ? `${space}[@${path}](<${path}>)` : whole);
887
+ }
888
+ #fromParent(entry) {
889
+ return html `<div class="part message user from-parent">
890
+ <div class="who">${icon("usersGroup", 13)} Task</div>
891
+ ${this.#markdown(textOf(entry.content))}
892
+ </div>`;
893
+ }
894
+ #agent(entry, streaming) {
895
+ const text = textOf(entry.content);
896
+ return html `<div class="part message agent">
897
+ ${text.trim() ? this.#markdown(text) : nothing} ${this.#attachments(entry.content)}
898
+ ${streaming ? html `<span class="streaming"></span>` : nothing}
899
+ ${this.#replyTokens.has(entry.id)
900
+ ? html `<div class="reply-meta">${tokens(this.#replyTokens.get(entry.id) ?? 0)} thinking tokens</div>`
901
+ : nothing}
902
+ </div>`;
903
+ }
904
+ #thought(entry, now) {
905
+ const text = textOf(entry.content);
906
+ // A thought known only by its count has nothing to read; the count goes with the turn's usage.
907
+ if (entry.tally || !text.trim())
908
+ return nothing;
909
+ const open = this.foldThinking === this.#thoughts.has(entry.id);
910
+ return html `<div class="part thinking ${open ? "open" : ""}">
911
+ <button
912
+ class="thinking-head"
913
+ aria-expanded=${open ? "true" : "false"}
914
+ title=${open ? "Fold this thinking" : "Show this thinking"}
915
+ @click=${() => this.#toggle(this.#thoughts, entry.id)}
916
+ >
917
+ <span class="status"><span class="chevron">${icon("chevronRight", 12)}</span></span
918
+ ><span class="kind">${icon("notes", 13)}</span><span class="title ${now ? "shimmer" : ""}">Thinking${entry.thinkingTokens ? ` for ~${tokens(entry.thinkingTokens)} tokens` : ""}</span>
919
+ </button>
920
+ ${open ? html `<div class="thinking-body">${this.#markdown(text)}</div>` : nothing}
921
+ </div>`;
922
+ }
923
+ #attachments(content) {
924
+ const all = attachmentsOf(content);
925
+ if (all.length === 0)
926
+ return nothing;
927
+ return html `<div class="attachments">
928
+ ${all.map((a) => a.type === "image"
929
+ ? this.#imageThumb(a, "message")
930
+ : html `<span class="link" title=${a.uri}>@${a.name}</span>`)}
931
+ </div>`;
932
+ }
933
+ #tool(tool, transcript) {
934
+ const state = toolState(tool.status);
935
+ const open = this.openTools !== this.#tools.has(tool.id);
936
+ const asked = askedQuestions(tool, this.#askFor(tool.id, transcript));
937
+ const detail = asked ? null : toolDetail(tool);
938
+ const took = toolDuration(tool, Date.now());
939
+ const waiting = this._state
940
+ ? waitingTools(this._state, transcript.sessionId).has(tool.id)
941
+ : false;
942
+ return html `<details class="part tool ${state}" ?open=${open}>
943
+ <summary
944
+ title=${tool.name ?? tool.title}
945
+ @click=${(e) => {
946
+ e.preventDefault();
947
+ this.#toggle(this.#tools, tool.id);
948
+ }}
949
+ >
950
+ <span class="status">${icon(statusIcon(tool.status), 13)}</span>
951
+ <span class="kind">${icon(kindIcon(tool.toolKind), 13)}</span>
952
+ <span class="title">${asked ? questionsLine(asked) : inline(tool.title || tool.name || tool.toolKind)}</span>
953
+ <span class=${detail?.code ? "told" : "note"}>${detail?.text ?? ""}</span>
954
+ ${waiting ? html `<span class="waiting">${icon("alertTriangle", 11)} waiting for you</span>` : nothing}
955
+ ${took !== null ? html `<span class="duration" title="How long it took">${formatDuration(took)}</span>` : nothing}
956
+ <span class="chevron">${icon("chevronRight", 12)}</span>
957
+ </summary>
958
+ ${open ? this.#toolBox(tool, transcript) : nothing}
959
+ </details>`;
960
+ }
961
+ /** The ask the Chat answered, or waits on, for tool call `id` of the session `transcript` is. */
962
+ #askFor(id, transcript) {
963
+ return this._state ? askFor(this._state, transcript.sessionId, id) : null;
964
+ }
965
+ #toolBox(tool, transcript) {
966
+ const parts = drawnParts(tool, this.toolRenderer, this.#askFor(tool.id, transcript));
967
+ const diffs = toolDiffs(tool);
968
+ const terminals = toolTerminals(tool).flatMap((id) => {
969
+ const t = transcript.terminals[id];
970
+ return t ? [t] : [];
971
+ });
972
+ const images = imagesOf(tool.content);
973
+ return html `<div class="tool-box">
974
+ ${parts.input ? this.#section(tool.id, "input", "Input", this.#drawn(parts.input, tool.id)) : nothing}
975
+ ${parts.output ? this.#section(tool.id, "output", "Output", this.#drawn(parts.output, tool.id)) : nothing}
976
+ ${images.length > 0
977
+ ? html `<div class="attachments tool-images">
978
+ ${images.map((image) => this.#imageThumb(image, "tool"))}
979
+ </div>`
980
+ : nothing}
981
+ ${diffs.map((diff, n) => this.#section(tool.id, `diff-${n}`, "Changes", html `${diff.changes.map((c) => html `<div class="path">${c.operation} ${c.oldPath ? html `${this.#pathLink(c.oldPath, "diff", tool.id)} → ` : nothing}${this.#pathLink(c.path, "diff", tool.id)}</div>`)}
982
+ ${diff.patch ? this.#code("diff", diff.patch) : nothing}`))}
983
+ ${terminals.map((t, n) => this.#section(tool.id, `terminal-${n}`, html `Terminal${t.command ? html ` · ${t.command}` : nothing}`, html `<pre class="terminal">${t.output}</pre>
984
+ ${t.exitStatus ? html `<div class="path">exit ${t.exitStatus.exitCode ?? t.exitStatus.signal}</div>` : nothing}`))}
985
+ </div>`;
986
+ }
987
+ /** One part of a tool's box: its label, a switch between wrapping and scrolling long lines, and what it holds. */
988
+ #section(id, name, label, body) {
989
+ const key = `${id}:${name}`;
990
+ const wrap = (this.toolWrap !== "scroll") !== this.#rewrapped.has(key);
991
+ return html `<div class="section ${name} ${wrap ? "wrap" : "scroll"}">
992
+ <div class="label">
993
+ <span>${label}</span>
994
+ <button
995
+ class="wrap-toggle"
996
+ aria-pressed=${wrap ? "false" : "true"}
997
+ title=${wrap ? "Don't wrap long lines: scroll them instead" : "Wrap long lines"}
998
+ @click=${() => this.#toggle(this.#rewrapped, key)}
999
+ >
1000
+ ${icon(wrap ? "arrowsHorizontal" : "textWrap", 11)}${wrap ? "No wrap" : "Wrap"}
1001
+ </button>
1002
+ </div>
1003
+ <div class="body">${body}</div>
1004
+ </div>`;
1005
+ }
1006
+ #drawn(drawn, toolCallId) {
1007
+ switch (drawn.as) {
1008
+ case "code":
1009
+ return this.#code(drawn.language, drawn.text);
1010
+ case "markdown":
1011
+ return this.#markdown(drawn.text, drawn.options);
1012
+ case "fields":
1013
+ return html `<dl class="fields">
1014
+ ${drawn.fields.map((f) => html `<dt>${f.label}</dt><dd class=${f.as ?? "text"}>${f.as === "path" ? this.#pathLink(f.value, "tool", toolCallId) : f.value}</dd>`)}
1015
+ </dl>`;
1016
+ case "group":
1017
+ return drawn.parts.map((part) => this.#drawn(part, toolCallId));
1018
+ case "views": {
1019
+ const key = `${toolCallId ?? ""}:${drawn.views.map((v) => v.label).join("/")}`;
1020
+ const chosen = drawn.views.find((v) => v.label === this.#views.get(key)) ??
1021
+ drawn.views[0];
1022
+ return html `<div class="views">
1023
+ <div class="view-switch" role="tablist" aria-label="Show as">
1024
+ ${drawn.views.map((v) => html `<button
1025
+ role="tab"
1026
+ class=${v === chosen ? "on" : ""}
1027
+ aria-selected=${v === chosen ? "true" : "false"}
1028
+ @click=${() => {
1029
+ this.#views.set(key, v.label);
1030
+ this.requestUpdate();
1031
+ }}
1032
+ >${v.label}</button>`)}
1033
+ </div>
1034
+ ${this.#drawn(chosen.drawn, toolCallId)}
1035
+ </div>`;
1036
+ }
1037
+ case "images":
1038
+ return html `<div class="attachments tool-images file-images">
1039
+ ${drawn.images.map((image) => this.#imageThumb(image, "tool"))}
1040
+ </div>`;
1041
+ case "element":
1042
+ return drawn.element;
1043
+ case "answers":
1044
+ return this.#answers(drawn);
1045
+ }
1046
+ }
1047
+ /** Questions as the form that asked them laid them out, read only, with what was answered. */
1048
+ #answers(asked) {
1049
+ return html `<div class="form answers">
1050
+ ${asked.questions.map((q) => {
1051
+ const written = q.chosen.filter((c) => !q.options.some((o) => o.label === c));
1052
+ return html `<span class="answer-label">${q.header ?? "Question"}</span>
1053
+ <div class="field">
1054
+ <span class="question">${q.question}</span>
1055
+ <div class="choices">
1056
+ ${q.options.map((o) => readOnlyChoice(q.multiSelect ? "check" : "radio", q.chosen.includes(o.label), o.label, o.description))}
1057
+ ${[...written, ...(q.text ? [q.text] : [])].map((t) => html `<span class="written">${icon("filePencil", 11)}${t}</span>`)}
1058
+ </div>
1059
+ </div>`;
1060
+ })}
1061
+ ${answerOutcome(asked.status === "answered" ? "accept" : asked.status === "cancelled" ? "cancel" : null)}
1062
+ </div>`;
1063
+ }
1064
+ /** A form the user answered, read only: each field with what was entered, and the button pressed. */
1065
+ #answeredForm(form) {
1066
+ return html `<div class="form answers">
1067
+ ${form.message ? html `<span class="answer-label"></span><span class="question">${form.message}</span>` : nothing}
1068
+ ${form.fields.map((f) => html `<span class="answer-label">${f.label}</span>
1069
+ <div class="field">
1070
+ ${answeredValue(f)}
1071
+ ${f.description ? html `<span class="hint">${f.description}</span>` : nothing}
1072
+ </div>`)}
1073
+ ${answerOutcome(form.action)}
1074
+ </div>`;
1075
+ }
1076
+ #turnEnd(turn) {
1077
+ const label = turn.outcome === "failed" ? `failed: ${turn.error ?? ""}` : "interrupted";
1078
+ return html `<div class="part turn ${turn.outcome}">
1079
+ ${icon(turn.outcome === "failed" ? "alertCircle" : "playerStop", 12)}<span>${label}</span
1080
+ ><span class="rule"></span>
1081
+ </div>`;
1082
+ }
1083
+ /** An ask's trace in the transcript: where it waits, then how it was answered. */
1084
+ #ask(entry, state) {
1085
+ // An ask about a tool call is told in that call's row.
1086
+ if (askTool(entry) !== null && entry.ask.type === "elicitation")
1087
+ return nothing;
1088
+ const form = answeredForm(entry);
1089
+ if (form) {
1090
+ const key = `ask:${entry.id}`;
1091
+ const open = this.openTools !== this.#tools.has(key);
1092
+ return html `<details class="part tool ask-form ${form.action === "accept" ? "done" : "cancelled"}" ?open=${open}>
1093
+ <summary
1094
+ @click=${(e) => {
1095
+ e.preventDefault();
1096
+ this.#toggle(this.#tools, key);
1097
+ }}
1098
+ >
1099
+ <span class="status">${icon(form.action === "accept" ? "check" : "ban", 13)}</span>
1100
+ <span class="kind">${icon("listCheck", 13)}</span>
1101
+ <span class="title">${askRecord(entry, state)}</span>
1102
+ <span class="chevron">${icon("chevronRight", 12)}</span>
1103
+ </summary>
1104
+ ${open ? html `<div class="tool-box">${this.#answeredForm(form)}</div>` : nothing}
1105
+ </details>`;
1106
+ }
1107
+ if (entry.answer !== null) {
1108
+ return html `<div class="part row ask-record">
1109
+ <span class="status">${icon("check", 13)}</span
1110
+ ><span class="kind">${icon(entry.ask.type === "permission" ? "lock" : "listCheck", 13)}</span
1111
+ ><span class="title">${askRecord(entry, state)}</span>
1112
+ </div>`;
1113
+ }
1114
+ if (askTool(entry) !== null)
1115
+ return nothing;
1116
+ const title = entry.ask.type === "permission"
1117
+ ? entry.ask.request.title
1118
+ : entry.ask.request.message;
1119
+ return html `<div class="part row ask-record waiting">
1120
+ <span class="status">${icon("alertTriangle", 13)}</span><span class="kind"></span
1121
+ ><span class="title">Waiting for you · ${inline(firstLine(title))}</span>
1122
+ </div>`;
1123
+ }
1124
+ /** Sign-in, in the composer's place, while the agent waits for it. */
1125
+ #signIn(state) {
1126
+ const signIn = state.signIn;
1127
+ if (!signIn)
1128
+ return nothing;
1129
+ const methods = this.#controller?.auth?.methods ?? [];
1130
+ const step = this._signInStep;
1131
+ const run = async (method) => {
1132
+ if (method.type !== "terminal") {
1133
+ await this.#controller?.signIn(method.id);
1134
+ return;
1135
+ }
1136
+ const command = this.terminalSignIn ? await this.terminalSignIn(method) : null;
1137
+ this._signInStep = { method, command };
1138
+ };
1139
+ return html `<section class="part ask open asking signin" tabindex="-1" aria-label="Sign in">
1140
+ <div class="ask-head">
1141
+ ${icon("lock", 13)}<span class="what">Sign in</span
1142
+ ><span class="title"
1143
+ >${signIn.reason === "signed_out" ? "You were signed out" : "The agent needs you to sign in"}</span
1144
+ >
1145
+ </div>
1146
+ <div class="description">
1147
+ ${signIn.reason === "signed_out"
1148
+ ? "Sign in again to go on; the prompt that failed can be sent again after."
1149
+ : "Sign in to start the session."}
1150
+ </div>
1151
+ ${step
1152
+ ? html `<div class="description">
1153
+ ${step.command
1154
+ ? html `Run this in a terminal to sign in, then continue:`
1155
+ : html `Finish signing in in the terminal that opened, then continue.`}
1156
+ </div>
1157
+ ${step.command ? html `<pre class="ask-line">${step.command}</pre>` : nothing}
1158
+ <div class="ask-answers">
1159
+ <button class="ask-answer primary default" @click=${async () => {
1160
+ await this.#controller?.signIn(step.method.id);
1161
+ this._signInStep = null;
1162
+ }}>Continue</button>
1163
+ <button class="ask-answer reject" @click=${() => {
1164
+ this._signInStep = null;
1165
+ }}>Back</button>
1166
+ </div>`
1167
+ : html `<div class="ask-answers">
1168
+ ${methods.map((method, n) => html `<button
1169
+ class="ask-answer ${n === 0 ? "default" : ""}"
1170
+ title=${method.description ?? ""}
1171
+ @click=${() => run(method)}
1172
+ >
1173
+ ${method.type === "terminal" ? icon("terminal", 12) : nothing}${method.name}
1174
+ </button>`)}
1175
+ ${methods.length === 0 ? html `<span class="description">The agent names no way to sign in.</span>` : nothing}
1176
+ </div>`}
1177
+ ${signIn.error ? html `<div class="signin-error">${signIn.error}</div>` : nothing}
1178
+ </section>`;
1179
+ }
1180
+ /** The prompt that failed for want of sign-in, offered again once signed in. */
1181
+ #retry(state) {
1182
+ const retry = state.retry;
1183
+ if (!retry || state.signIn)
1184
+ return nothing;
1185
+ return html `<div class="retry">
1186
+ ${icon("refresh", 12)}
1187
+ <span class="first">Signed in. Send again: ${firstLine(textOf(retry.prompt))}</span>
1188
+ <button class="ask-answer primary" @click=${() => this.#controller?.retrySignedOut()}>
1189
+ Retry
1190
+ </button>
1191
+ <button class="ask-answer reject" @click=${() => this.#controller?.dismissRetry()}>
1192
+ Dismiss
1193
+ </button>
1194
+ </div>`;
1195
+ }
1196
+ /** The open asks, one at a time, in the composer's place; or a note that one waits. */
1197
+ #asks(state) {
1198
+ const asks = openAsks(state);
1199
+ if (asks.length === 0)
1200
+ return nothing;
1201
+ const index = Math.min(this._askIndex, asks.length - 1);
1202
+ const entry = asks[index];
1203
+ if (this._composeInstead) {
1204
+ return html `<div class="ask-waiting">
1205
+ ${icon("alertTriangle", 12)}
1206
+ <span>The agent waits for your answer${asks.length > 1 ? ` to ${asks.length} questions` : ""}</span>
1207
+ <button class="link" @click=${() => this.composeInstead(false)}>Answer</button>
1208
+ </div>`;
1209
+ }
1210
+ const pager = asks.length > 1
1211
+ ? html `<span class="pager">
1212
+ <button
1213
+ title="The previous question"
1214
+ ?disabled=${index === 0}
1215
+ @click=${() => {
1216
+ this._askIndex = index - 1;
1217
+ }}
1218
+ >${icon("chevronLeft", 12)}</button>
1219
+ <span>${index + 1} of ${asks.length}</span>
1220
+ <button
1221
+ title="The next question"
1222
+ ?disabled=${index === asks.length - 1}
1223
+ @click=${() => {
1224
+ this._askIndex = index + 1;
1225
+ }}
1226
+ >${icon("chevronRight", 12)}</button>
1227
+ </span>`
1228
+ : nothing;
1229
+ const body = entry.ask.type === "permission"
1230
+ ? this.#permissionAsk(entry, state, pager)
1231
+ : this.#elicitationAsk(entry, pager);
1232
+ return html `<section class="part ask open asking" tabindex="-1" aria-label="The agent asks">
1233
+ ${body}
1234
+ <div class="ask-foot">
1235
+ <span class="hint">${this.#askHint(entry)}</span>
1236
+ <button class="link" @click=${() => this.composeInstead(true)}>
1237
+ Write a message instead
1238
+ </button>
1239
+ </div>
1240
+ </section>`;
1241
+ }
1242
+ #askHint(entry) {
1243
+ const stop = html `<kbd>${this.#chord("stop")}</kbd> stops`;
1244
+ if (entry.ask.type !== "permission")
1245
+ return stop;
1246
+ const options = entry.ask.request.options;
1247
+ const first = options[0];
1248
+ return html `<kbd>1</kbd>${options.length > 1 ? html `–<kbd>${options.length}</kbd>` : nothing}
1249
+ answer${first ? html ` · <kbd>Enter</kbd> ${first.name}` : nothing} · ${stop}`;
1250
+ }
1251
+ #permissionAsk(entry, state, pager) {
1252
+ const request = entry.ask.request;
1253
+ const subject = request.subject;
1254
+ const line = askSubject(entry, state);
1255
+ const rejects = request.options.some((o) => o.kind.startsWith("reject"));
1256
+ const reason = () => this.renderRoot.querySelector(".ask-reason")?.value ?? "";
1257
+ const choose = (option) => this.#controller?.answerPermission(entry.id, option.optionId, option.kind.startsWith("reject") ? reason() : undefined);
1258
+ return html `<div class="ask-head">
1259
+ ${icon("alertTriangle", 13)}<span class="what">Allow?</span
1260
+ ><span class="title">${inline(request.title)}</span>${pager}
1261
+ </div>
1262
+ ${request.description ? html `<div class="description">${request.description}</div>` : nothing}
1263
+ ${line
1264
+ ? html `<pre class="ask-line">${line}${subject?.type === "command" && subject.cwd
1265
+ ? html `<span class="cwd"> in ${subject.cwd}</span>`
1266
+ : nothing}</pre>`
1267
+ : nothing}
1268
+ <div class="ask-answers">
1269
+ ${request.options.map((option, n) => html `<button
1270
+ class="ask-answer ${option.kind.startsWith("reject") ? "reject" : ""} ${n === 0 ? "default" : ""}"
1271
+ @click=${() => choose(option)}
1272
+ >
1273
+ <kbd>${n + 1}</kbd>${option.name}
1274
+ </button>`)}
1275
+ </div>
1276
+ ${rejects
1277
+ ? html `<input
1278
+ class="ask-reason"
1279
+ type="text"
1280
+ placeholder="Or tell the agent what to do instead, and Enter to reject"
1281
+ @keydown=${(e) => {
1282
+ if (e.key === "Escape") {
1283
+ // Escape leaves the field for the options, whose keys answer.
1284
+ this.renderRoot.querySelector(".asking")?.focus();
1285
+ return;
1286
+ }
1287
+ if (e.key !== "Enter" || e.isComposing || !reason().trim())
1288
+ return;
1289
+ e.preventDefault();
1290
+ const reject = request.options.find((o) => o.kind.startsWith("reject"));
1291
+ if (reject)
1292
+ choose(reject);
1293
+ }}
1294
+ />`
1295
+ : nothing}`;
1296
+ }
1297
+ #elicitationAsk(entry, pager) {
1298
+ const request = entry.ask.request;
1299
+ return html `<div class="ask-head">
1300
+ ${icon("alertTriangle", 13)}<span class="what">Asks</span>${pager}
1301
+ </div>
1302
+ <div class="description">${request.message}</div>
1303
+ <div class="ask-body">
1304
+ ${request.mode === "form"
1305
+ ? this.#form(entry.id, request.requestedSchema ?? {})
1306
+ : html `${request.url ? html `<pre class="ask-line">${request.url}</pre>` : nothing}
1307
+ <div class="ask-answers">
1308
+ <button class="ask-answer primary default" @click=${() => this.#controller?.answerElicitation(entry.id, { action: "accept" })}>Done</button>
1309
+ <button class="ask-answer reject" @click=${() => this.#controller?.answerElicitation(entry.id, { action: "decline" })}>Decline</button>
1310
+ </div>`}
1311
+ </div>`;
1312
+ }
1313
+ /** Focus is in the Chat: in its shadow root, or on an element the host slotted. */
1314
+ #hasFocus() {
1315
+ const active = document.activeElement;
1316
+ return active === this || (active !== null && this.contains(active));
1317
+ }
1318
+ #form(id, schema) {
1319
+ const fields = Object.entries(schema.properties ?? {});
1320
+ const required = new Set(schema.required ?? []);
1321
+ const submit = (e) => {
1322
+ e.preventDefault();
1323
+ const form = e.target;
1324
+ const content = {};
1325
+ for (const [name, field] of fields) {
1326
+ const type = field.type;
1327
+ if (type === "boolean") {
1328
+ content[name] = form.elements.namedItem(name).checked;
1329
+ }
1330
+ else if (type === "array") {
1331
+ content[name] = [
1332
+ ...form.querySelectorAll(`input[name="${name}"]:checked`),
1333
+ ].map((i) => i.value);
1334
+ }
1335
+ else {
1336
+ const value = form.elements.namedItem(name)
1337
+ .value;
1338
+ if (value === "")
1339
+ continue;
1340
+ content[name] = type === "number" || type === "integer" ? Number(value) : value;
1341
+ }
1342
+ }
1343
+ this.#controller?.answerElicitation(id, { action: "accept", content });
1344
+ };
1345
+ return html `<form @submit=${submit}>
1346
+ <div class="form">
1347
+ ${fields.map(([name, field]) => {
1348
+ const f = field;
1349
+ return html `<label for=${name}
1350
+ >${f.title ?? name}${required.has(name) ? html `<span class="required"> *</span>` : nothing}</label
1351
+ >
1352
+ <div class="field">
1353
+ ${formField(name, f, required.has(name))}
1354
+ ${f.description ? html `<span class="hint">${f.description}</span>` : nothing}
1355
+ </div>`;
1356
+ })}
1357
+ </div>
1358
+ <div class="ask-answers" style="margin-top:calc(8 * var(--px))">
1359
+ <button class="ask-answer primary" type="submit">Submit</button>
1360
+ <button
1361
+ class="ask-answer reject"
1362
+ type="button"
1363
+ @click=${() => this.#controller?.answerElicitation(id, { action: "decline" })}
1364
+ >
1365
+ Decline
1366
+ </button>
1367
+ </div>
1368
+ </form>`;
1369
+ }
1370
+ #notice(entry) {
1371
+ const name = entry.severity === "info" ? "infoCircle" : "alertCircle";
1372
+ return html `<div class="part notice ${entry.severity}">
1373
+ ${icon(name, 13)}<span class="what">${entry.title}</span>
1374
+ ${entry.description ? html `<span class="description">${entry.description}</span>` : nothing}
1375
+ </div>`;
1376
+ }
1377
+ #compaction(entry) {
1378
+ const label = entry.status === "in_progress"
1379
+ ? "Compacting the context…"
1380
+ : entry.status === "failed"
1381
+ ? `Compaction failed${entry.error ? `: ${entry.error}` : ""}`
1382
+ : "Context compacted";
1383
+ return html `<details class="part compaction">
1384
+ <summary>${icon("fold", 12)} ${label}</summary>
1385
+ ${entry.summary.length > 0 ? html `<div class="summary">${this.#markdown(textOf(entry.summary))}</div>` : nothing}
1386
+ </details>`;
1387
+ }
1388
+ #subagent(state, sessionId, at) {
1389
+ const subagent = state.subagents[sessionId];
1390
+ const starter = at.kind === "tool" ? at : undefined;
1391
+ const running = subagent
1392
+ ? isWorking(subagent)
1393
+ : starter
1394
+ ? toolState(starter.status) === "running"
1395
+ : false;
1396
+ const failed = starter?.status === "failed" || (subagent && lastTurn(subagent)?.outcome === "failed");
1397
+ const status = running ? "running" : failed ? "failed" : "done";
1398
+ const steps = (subagent?.entries ?? []).filter((e) => e.kind === "tool");
1399
+ const opened = this.#cards.has(sessionId);
1400
+ const shown = opened ? steps : running ? steps.slice(-LATEST_STEPS) : [];
1401
+ const task = subagent?.entries.find((e) => e.kind === "session-message");
1402
+ const description = subagent?.description ?? (task ? firstLine(textOf(task.content)) : (starter?.title ?? ""));
1403
+ const result = !running && subagent
1404
+ ? lastMessage(subagent.entries.filter((e) => e.kind === "agent"))
1405
+ : undefined;
1406
+ return html `<div class="part subagent ${status} ${opened ? "opened" : ""}">
1407
+ <button
1408
+ class="subagent-head"
1409
+ tabindex="-1"
1410
+ title=${opened ? "Show only its latest steps" : "Show every step"}
1411
+ @click=${() => this.#toggle(this.#cards, sessionId)}
1412
+ >
1413
+ <span class="status"
1414
+ >${running
1415
+ ? html `<span class="dots"><span></span><span></span><span></span></span>`
1416
+ : icon(failed ? "x" : "check", 12)}</span
1417
+ >
1418
+ <span class="name">${subagent?.title ?? starter?.title ?? "Subagent"}</span>
1419
+ <span class="description">${description}</span>
1420
+ <span class="count">${steps.length === 1 ? "1 step" : `${steps.length} steps`}</span>
1421
+ <span class="chevron">${icon("chevronRight", 12)}</span>
1422
+ </button>
1423
+ <div class="subagent-steps">${shown.length > 0
1424
+ ? html `${steps.length > shown.length
1425
+ ? html `<div class="subagent-more">${steps.length - shown.length} earlier</div>`
1426
+ : nothing}${shown.map((s) => this.#tool(s, subagent ?? state))}`
1427
+ : nothing}</div>
1428
+ ${result && result.kind === "agent"
1429
+ ? html `<div class="subagent-result">${this.#markdown(textOf(result.content))}</div>`
1430
+ : nothing}
1431
+ </div>`;
1432
+ }
1433
+ #foot(state) {
1434
+ const plans = Object.values(state.plans);
1435
+ const plan = plans[plans.length - 1];
1436
+ const listed = state.pending.some((p) => !p.sending);
1437
+ if (!plan && !listed)
1438
+ return nothing;
1439
+ return html `<div class="foot">
1440
+ ${plan ? this.#plan(plan) : nothing} ${listed ? this.#pending(state) : nothing}
1441
+ </div>`;
1442
+ }
1443
+ #plan(plan) {
1444
+ if (plan.type === "markdown") {
1445
+ return html `<div class="plan">
1446
+ <div class="plan-head">${icon("listCheck", 12)} Plan</div>
1447
+ ${this.#markdown(plan.content)}
1448
+ </div>`;
1449
+ }
1450
+ const entries = plan.entries ?? [];
1451
+ return html `<div class="plan">
1452
+ <div class="plan-head">${icon("listCheck", 12)} Plan</div>
1453
+ ${entries.map((item) => {
1454
+ // Marked as a tool row's status is: done, running, or nothing yet.
1455
+ const mark = item.status === "completed" ? "done" : item.status === "in_progress" ? "doing" : "todo";
1456
+ return html `<div class="item ${mark}">
1457
+ <span class="mark" data-mark=${mark}
1458
+ >${mark === "done" ? icon("check", 12) : mark === "doing" ? icon("loader", 12) : nothing}</span
1459
+ ><span class="text">${item.content}</span>
1460
+ </div>`;
1461
+ })}
1462
+ </div>`;
1463
+ }
1464
+ #pending(state) {
1465
+ const waiting = state.pending.filter((p) => p.error === null && !p.sending);
1466
+ const failed = state.pending.filter((p) => p.error !== null);
1467
+ return html `<div class="queued-list">
1468
+ ${waiting.length > 0
1469
+ ? html `<div class="queued-head">${icon("progress", 12)} Waiting for this turn to end · ${waiting.length}</div>`
1470
+ : nothing}
1471
+ ${waiting.map((p) => this.#submission(p))}
1472
+ ${failed.length > 0
1473
+ ? html `<div class="queued-head">${icon("alertCircle", 12)} Not taken in · ${failed.length}</div>`
1474
+ : nothing}
1475
+ ${failed.map((p) => this.#submission(p))}
1476
+ </div>`;
1477
+ }
1478
+ #submission(p) {
1479
+ const text = textOf(p.prompt);
1480
+ return html `<details class="queued ${p.error ? "failed" : ""}">
1481
+ <summary>
1482
+ <span class="chevron">${icon("chevronRight", 11)}</span>
1483
+ <span class="first" title=${p.error ?? ""}>${firstLine(text)}</span>
1484
+ ${p.error
1485
+ ? html `<span class="actions">
1486
+ <button @click=${(e) => {
1487
+ e.preventDefault();
1488
+ this.#controller?.retry(p.id);
1489
+ }}>
1490
+ ${icon("refresh", 11)} Send again
1491
+ </button>
1492
+ <button @click=${(e) => {
1493
+ e.preventDefault();
1494
+ this.#controller?.dismiss(p.id);
1495
+ }}>
1496
+ ${icon("x", 11)} Dismiss
1497
+ </button>
1498
+ </span>`
1499
+ : html `<span class="actions">
1500
+ ${this.#controller?.abilities.steer && this.#controller.abilities.withdraw
1501
+ ? html `<button
1502
+ title="Stop the work running and take this first"
1503
+ @click=${(e) => {
1504
+ e.preventDefault();
1505
+ this.#controller?.steer(p.id);
1506
+ }}
1507
+ >
1508
+ ${icon("arrowUp", 11)} Send now
1509
+ </button>`
1510
+ : nothing}
1511
+ ${this.#controller?.abilities.withdraw
1512
+ ? html `<button
1513
+ title="Take it back before the agent does"
1514
+ @click=${(e) => {
1515
+ e.preventDefault();
1516
+ this.#controller?.withdraw(p.id);
1517
+ }}
1518
+ >
1519
+ ${icon("x", 11)} Remove
1520
+ </button>`
1521
+ : nothing}
1522
+ </span>`}
1523
+ </summary>
1524
+ <div class="queued-whole">${p.error ? html `<strong>${p.error}</strong>\n\n` : nothing}${text}</div>
1525
+ </details>`;
1526
+ }
1527
+ #composer(state) {
1528
+ const working = state ? isWorking(state) : false;
1529
+ const completion = this._completion;
1530
+ const empty = this._draft.trim() === "";
1531
+ const steerable = working && this.canSteer;
1532
+ const delivery = deliveryOf(this._delivery, { working, canSteer: this.canSteer });
1533
+ const triggers = this.#providers.map((p) => p.trigger);
1534
+ const hint = argumentHint(this._draft, this._state?.commands ?? []);
1535
+ return html `<form class="composer" @submit=${(e) => {
1536
+ e.preventDefault();
1537
+ this.#submit();
1538
+ }}>
1539
+ ${completion ? this.#completionList(completion) : nothing}
1540
+ <div class="composer-top">${this.#composerTop()}</div>
1541
+ <div class="draft">
1542
+ <textarea
1543
+ rows="1"
1544
+ .value=${this._draft}
1545
+ ?disabled=${!state}
1546
+ placeholder=${placeholderOf(working, triggers)}
1547
+ aria-controls=${completion ? "completion-list" : nothing}
1548
+ aria-expanded=${completion ? "true" : "false"}
1549
+ aria-activedescendant=${completion && completion.items.length > 0 ? `completion-${completion.selected}` : nothing}
1550
+ @input=${(e) => this.#input(e.target)}
1551
+ @keydown=${(e) => this.#composerKey(e)}
1552
+ @paste=${(e) => {
1553
+ const files = filesOf(e.clipboardData).filter((f) => f.type.startsWith("image/"));
1554
+ if (files.length === 0)
1555
+ return;
1556
+ e.preventDefault();
1557
+ void this.attach(files);
1558
+ }}
1559
+ @click=${(e) => this.#complete(e.target)}
1560
+ ></textarea>
1561
+ ${hint
1562
+ ? html `<div class="ghost" aria-hidden="true"><span class="typed">${this._draft}</span><span class="hint">${hint}</span></div>`
1563
+ : nothing}
1564
+ </div>
1565
+ <div class="composer-foot">
1566
+ <span class="tools">${this.#composerTools(state)}</span>
1567
+ ${steerable
1568
+ ? html `<span class="delivery" role="radiogroup" aria-label="When the next prompt is sent">
1569
+ <button
1570
+ type="button"
1571
+ role="radio"
1572
+ aria-checked=${delivery === "after" ? "true" : "false"}
1573
+ title="The agent takes it in when this turn allows"
1574
+ @click=${() => {
1575
+ this._delivery = "after";
1576
+ }}
1577
+ >After this turn</button>
1578
+ <button
1579
+ type="button"
1580
+ role="radio"
1581
+ aria-checked=${delivery === "steer" ? "true" : "false"}
1582
+ title="Stop the work running and send it first${this.#chordHint("steer")}"
1583
+ @click=${() => {
1584
+ this._delivery = "steer";
1585
+ }}
1586
+ >Steer now</button>
1587
+ </span>`
1588
+ : nothing}
1589
+ <span class="spacer"></span>
1590
+ <span class="keys-hint" aria-hidden="true">${this.#keysHint(working, steerable)}</span>
1591
+ ${working
1592
+ ? html `<button
1593
+ type="button"
1594
+ class="composer-button stop"
1595
+ title="Stop${this.#chordHint("stop")}"
1596
+ aria-label="Stop"
1597
+ @click=${() => this.#controller?.cancel()}
1598
+ >
1599
+ ${icon("playerStop", 14)}
1600
+ </button>`
1601
+ : nothing}
1602
+ <button
1603
+ type="submit"
1604
+ class="composer-button send"
1605
+ title="Send${delivery === "steer" ? " now" : ""}${this.#chordHint("send")}"
1606
+ aria-label="Send"
1607
+ ?disabled=${!this.#canSend(empty) || !state}
1608
+ >
1609
+ ${icon("arrowUp", 14)}
1610
+ </button>
1611
+ </div>
1612
+ </form>`;
1613
+ }
1614
+ /** What sits above the text area: nothing yet; attachments when there are. */
1615
+ #composerTop() {
1616
+ if (this._attachments.length === 0 && this._rejected.length === 0)
1617
+ return nothing;
1618
+ return html `<div class="strip" role="list" aria-label="Attached images">
1619
+ ${this._rejected.map((r) => html `<span class="refused" role="listitem">
1620
+ ${icon("alertCircle", 12)}<span>${r.text}</span>
1621
+ <button
1622
+ type="button"
1623
+ title="Dismiss"
1624
+ aria-label="Dismiss"
1625
+ @click=${() => {
1626
+ this._rejected = this._rejected.filter((x) => x.id !== r.id);
1627
+ }}
1628
+ >${icon("x", 11)}</button>
1629
+ </span>`)}
1630
+ ${this._attachments.map((a) => html `<span class="thumb" role="listitem">
1631
+ <button
1632
+ type="button"
1633
+ class="thumb-image"
1634
+ title="${a.name}, ${formatBytes(a.size)}"
1635
+ aria-label="Show ${a.name}"
1636
+ @click=${() => this.#showImage({
1637
+ data: a.data,
1638
+ mimeType: a.mimeType,
1639
+ name: a.name,
1640
+ source: "attachment",
1641
+ })}
1642
+ >
1643
+ <img alt="" src="data:${a.mimeType};base64,${a.data}" />
1644
+ </button>
1645
+ <span class="thumb-name">${a.name}</span>
1646
+ <span class="thumb-size">${formatBytes(a.size)}</span>
1647
+ <button
1648
+ type="button"
1649
+ class="thumb-remove"
1650
+ title="Remove ${a.name}"
1651
+ aria-label="Remove ${a.name}"
1652
+ @click=${() => this.removeAttachment(a.id)}
1653
+ >${icon("x", 11)}</button>
1654
+ </span>`)}
1655
+ </div>`;
1656
+ }
1657
+ /** The toolbar's own tools, left of the delivery. */
1658
+ #composerTools(state) {
1659
+ const allowed = this.imagesAllowed;
1660
+ return html `<button
1661
+ type="button"
1662
+ class="composer-tool attach"
1663
+ ?disabled=${!state || !allowed}
1664
+ title=${allowed ? "Attach images: PNG, JPEG, GIF or WebP" : "The agent takes no images"}
1665
+ aria-label="Attach images"
1666
+ @click=${() => void this.#pick()}
1667
+ >
1668
+ ${icon("photo", 15)}
1669
+ </button>
1670
+ <input
1671
+ class="pick"
1672
+ type="file"
1673
+ accept="image/png,image/jpeg,image/gif,image/webp"
1674
+ multiple
1675
+ hidden
1676
+ @change=${(e) => {
1677
+ const input = e.target;
1678
+ void this.attach([...(input.files ?? [])]);
1679
+ input.value = "";
1680
+ }}
1681
+ />`;
1682
+ }
1683
+ /** Whether there is something to send. */
1684
+ #canSend(empty) {
1685
+ return !empty || this._attachments.length > 0;
1686
+ }
1687
+ /** ` (Cmd+Enter)`: the first key of `action`, spelled out, for a tooltip. */
1688
+ #chordHint(action) {
1689
+ const chord = this.#chord(action);
1690
+ return chord ? ` (${chord})` : "";
1691
+ }
1692
+ /** The composer's keys that apply now, spelled out: steer and stop only while work runs. */
1693
+ #keysHint(working, steerable) {
1694
+ const part = (action, what) => {
1695
+ const chord = this.#chord(action);
1696
+ return chord ? `${chord} ${what}` : null;
1697
+ };
1698
+ return [
1699
+ part("send", "sends"),
1700
+ steerable ? part("steer", "sends now") : null,
1701
+ part("newline", "new line"),
1702
+ working ? part("stop", "stops") : null,
1703
+ ]
1704
+ .filter((p) => p !== null)
1705
+ .join(" · ");
1706
+ }
1707
+ /** The completion list over the composer: its items, or that none came yet. */
1708
+ #completionList(completion) {
1709
+ return html `<div class="commands" role="listbox" id="completion-list">
1710
+ ${completion.items.length === 0
1711
+ ? html `<div class="completion-empty">${emptyCompletionText({
1712
+ loading: completion.loading,
1713
+ commands: completion.commands,
1714
+ reported: this._state?.commandsReported === true,
1715
+ })}</div>`
1716
+ : completion.items.map((item, n) => html `<button
1717
+ type="button"
1718
+ role="option"
1719
+ id="completion-${n}"
1720
+ tabindex="-1"
1721
+ aria-selected=${n === completion.selected ? "true" : "false"}
1722
+ class="command ${item.kind} ${n === completion.selected ? "selected" : ""}"
1723
+ @mousedown=${(e) => e.preventDefault()}
1724
+ @click=${() => this.#accept(item)}
1725
+ >
1726
+ ${icon(completionIcon(item.kind), 12)}<span class="name">${item.label}</span
1727
+ >${item.hint ? html `<span class="hint">${item.hint}</span>` : nothing}<span class="description"
1728
+ >${item.detail ?? ""}</span
1729
+ >
1730
+ </button>`)}
1731
+ </div>`;
1732
+ }
1733
+ #input(area) {
1734
+ this._draft = area.value;
1735
+ area.style.height = "auto";
1736
+ area.style.height = `${area.scrollHeight}px`;
1737
+ // Only text taller than the field may be, at its cap, scrolls.
1738
+ area.style.overflowY = area.scrollHeight > area.clientHeight ? "auto" : "";
1739
+ this.#complete(area);
1740
+ }
1741
+ /** Opens, follows or closes the completion the caret is in. */
1742
+ #complete(area) {
1743
+ const found = findTrigger(area.value, area.selectionStart, this.#providers);
1744
+ if (!found) {
1745
+ this.#closeCompletion();
1746
+ return;
1747
+ }
1748
+ // Until the provider answers, what it gave before stays only where it still fits.
1749
+ const typed = area.value.slice(found.start, area.selectionStart).toLowerCase();
1750
+ this._completion = {
1751
+ range: { start: found.start, end: area.selectionStart },
1752
+ items: (this._completion?.items ?? []).filter((i) => i.insertText.toLowerCase().startsWith(typed)),
1753
+ selected: 0,
1754
+ loading: true,
1755
+ commands: found.provider === this.#commandProvider,
1756
+ };
1757
+ this.#completer.update(found.provider, found.query);
1758
+ }
1759
+ #closeCompletion() {
1760
+ this.#completer.close();
1761
+ this._completion = null;
1762
+ }
1763
+ #accept(item) {
1764
+ const completion = this._completion;
1765
+ const area = this.renderRoot.querySelector("textarea");
1766
+ if (!completion || !area)
1767
+ return;
1768
+ const done = accept(this._draft, completion.range, item);
1769
+ if (item.uri)
1770
+ this.#accepted.push(item);
1771
+ this._draft = done.text;
1772
+ area.value = done.text;
1773
+ area.setSelectionRange(done.caret, done.caret);
1774
+ area.focus();
1775
+ if (done.again)
1776
+ this.#complete(area);
1777
+ else
1778
+ this.#closeCompletion();
1779
+ }
1780
+ /** The keys of an open completion list: moving, accepting, closing. */
1781
+ #completionKey(e) {
1782
+ const completion = this._completion;
1783
+ if (!completion)
1784
+ return false;
1785
+ const count = completion.items.length;
1786
+ if (e.key === "Escape") {
1787
+ e.preventDefault();
1788
+ e.stopPropagation();
1789
+ this.#closeCompletion();
1790
+ return true;
1791
+ }
1792
+ if (count === 0)
1793
+ return false;
1794
+ const moved = movedSelection(completion.selected, count, e);
1795
+ if (moved !== null) {
1796
+ e.preventDefault();
1797
+ this._completion = { ...completion, selected: moved };
1798
+ return true;
1799
+ }
1800
+ const plainEnter = e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey;
1801
+ if (e.key === "Tab" || plainEnter) {
1802
+ e.preventDefault();
1803
+ const item = completion.items[completion.selected] ?? completion.items[0];
1804
+ if (item)
1805
+ this.#accept(item);
1806
+ return true;
1807
+ }
1808
+ return false;
1809
+ }
1810
+ #composerKey(e) {
1811
+ const area = e.target;
1812
+ // Backspace in an empty text area takes the last image off, as it would a character.
1813
+ if (e.key === "Backspace" && area.value === "" && this._attachments.length > 0) {
1814
+ e.preventDefault();
1815
+ const last = this._attachments[this._attachments.length - 1];
1816
+ if (last)
1817
+ this.removeAttachment(last.id);
1818
+ return;
1819
+ }
1820
+ if (e.isComposing)
1821
+ return;
1822
+ if (this.#completionKey(e))
1823
+ return;
1824
+ switch (actionOf(e, this.effectiveKeymap)) {
1825
+ case "send":
1826
+ case "steer":
1827
+ e.preventDefault();
1828
+ // The steer key steers whatever is chosen; the send key sends as chosen.
1829
+ this.#submit(actionOf(e, this.effectiveKeymap) === "steer" ? "steer" : undefined);
1830
+ return;
1831
+ case "newline": {
1832
+ // The textarea writes Enter's new line itself; other keys bound to one need it written.
1833
+ if (e.key === "Enter")
1834
+ return;
1835
+ e.preventDefault();
1836
+ const area = e.target;
1837
+ area.setRangeText("\n", area.selectionStart, area.selectionEnd, "end");
1838
+ this.#input(area);
1839
+ return;
1840
+ }
1841
+ }
1842
+ }
1843
+ /** How the first key of `action` is written. */
1844
+ #chord(action) {
1845
+ const chord = this.effectiveKeymap[action][0];
1846
+ return chord ? chordLabel(chord) : "";
1847
+ }
1848
+ #submit(delivery) {
1849
+ const text = this._draft;
1850
+ if (!text.trim() && this._attachments.length === 0)
1851
+ return;
1852
+ const chosen = delivery ?? deliveryOf(this._delivery, { working: this.working, canSteer: this.canSteer });
1853
+ const resources = resourceLinks(text, this.#accepted);
1854
+ this.send(text, {
1855
+ delivery: chosen,
1856
+ ...(resources.length > 0 ? { resources } : {}),
1857
+ });
1858
+ this._delivery = "after";
1859
+ this.#accepted = [];
1860
+ this.#closeCompletion();
1861
+ this._draft = "";
1862
+ const area = this.renderRoot.querySelector("textarea");
1863
+ if (area) {
1864
+ area.style.height = "auto";
1865
+ area.style.overflowY = "";
1866
+ }
1867
+ this.#follower?.toEnd();
1868
+ }
1869
+ /** Text is selected in the Chat, or in the field the key was pressed in. */
1870
+ #hasSelection(e) {
1871
+ const target = e.composedPath()[0];
1872
+ if (target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement) {
1873
+ if (target.selectionStart !== target.selectionEnd)
1874
+ return true;
1875
+ }
1876
+ const root = this.renderRoot;
1877
+ const inShadow = root.getSelection?.()?.toString() ?? "";
1878
+ return inShadow !== "" || (document.getSelection()?.toString() ?? "") !== "";
1879
+ }
1880
+ #onKey = (e) => {
1881
+ const state = this._state;
1882
+ if (!state || e.isComposing || this.#fromSlot(e))
1883
+ return;
1884
+ if (actionOf(e, this.effectiveKeymap) === "stop" && isWorking(state)) {
1885
+ // With text selected, the key copies it, as Ctrl+C does everywhere else.
1886
+ if (this.#hasSelection(e))
1887
+ return;
1888
+ e.preventDefault();
1889
+ this.#controller?.cancel();
1890
+ return;
1891
+ }
1892
+ const target = e.composedPath()[0];
1893
+ if (target instanceof HTMLTextAreaElement ||
1894
+ target instanceof HTMLInputElement ||
1895
+ target instanceof HTMLSelectElement) {
1896
+ return;
1897
+ }
1898
+ if (!this.#asking)
1899
+ return;
1900
+ const asks = openAsks(state);
1901
+ const ask = asks[Math.min(this._askIndex, asks.length - 1)];
1902
+ if (ask?.ask.type !== "permission")
1903
+ return;
1904
+ const options = ask.ask.request.options;
1905
+ // Enter on a button presses that button; elsewhere it takes the first option.
1906
+ const n = e.key === "Enter" && !(target instanceof HTMLButtonElement) ? 1 : Number(e.key);
1907
+ if (!Number.isInteger(n) || n < 1)
1908
+ return;
1909
+ const option = options[n - 1];
1910
+ if (!option)
1911
+ return;
1912
+ e.preventDefault();
1913
+ this.#controller?.answerPermission(ask.id, option.optionId);
1914
+ };
1915
+ /** The key comes from the host's input in the `composer` slot, which owns its keys. */
1916
+ #fromSlot(e) {
1917
+ return e
1918
+ .composedPath()
1919
+ .some((node) => node instanceof Element && node.slot === "composer" && node.parentElement === this);
1920
+ }
1921
+ #toggle(set, id) {
1922
+ if (!set.delete(id))
1923
+ set.add(id);
1924
+ this.requestUpdate();
1925
+ }
1926
+ }
1927
+ /** Each turn's thinking tokens, by the id of the last reply in it. */
1928
+ function replyTokens(entries) {
1929
+ const counts = new Map();
1930
+ let turn = null;
1931
+ let reply = null;
1932
+ const close = () => {
1933
+ if (turn?.thinkingTokens && reply)
1934
+ counts.set(reply, turn.thinkingTokens);
1935
+ };
1936
+ for (const entry of entries) {
1937
+ if (entry.kind === "turn") {
1938
+ close();
1939
+ turn = entry;
1940
+ reply = null;
1941
+ }
1942
+ else if (entry.kind === "agent") {
1943
+ reply = entry.id;
1944
+ }
1945
+ }
1946
+ close();
1947
+ return counts;
1948
+ }
1949
+ function keyOf(row, entries) {
1950
+ const entry = entries[row.index];
1951
+ return `${row.type}:${entry.kind}:${entry.id}`;
1952
+ }
1953
+ function lastMessage(entries) {
1954
+ for (let i = entries.length - 1; i >= 0; i--) {
1955
+ const e = entries[i];
1956
+ if (e?.kind === "agent" || e?.kind === "thought")
1957
+ return e;
1958
+ if (e?.kind === "tool" || e?.kind === "user")
1959
+ return undefined;
1960
+ }
1961
+ return undefined;
1962
+ }
1963
+ function toolState(status) {
1964
+ switch (status) {
1965
+ case "pending":
1966
+ case "in_progress":
1967
+ return "running";
1968
+ case "failed":
1969
+ return "failed";
1970
+ case "cancelled":
1971
+ return "cancelled";
1972
+ case "paused":
1973
+ return "paused";
1974
+ default:
1975
+ return "done";
1976
+ }
1977
+ }
1978
+ function statusIcon(status) {
1979
+ switch (toolState(status)) {
1980
+ case "running":
1981
+ return "loader";
1982
+ case "failed":
1983
+ return "x";
1984
+ case "cancelled":
1985
+ return "ban";
1986
+ case "paused":
1987
+ return "playerPause";
1988
+ default:
1989
+ return "check";
1990
+ }
1991
+ }
1992
+ /** `text` with its `code spans` drawn as code, as agents write titles. */
1993
+ function inline(text) {
1994
+ const parts = text.split(/(`[^`]+`)/g);
1995
+ return parts.map((part) => part.startsWith("`") && part.endsWith("`") && part.length > 1
1996
+ ? html `<code>${part.slice(1, -1)}</code>`
1997
+ : part);
1998
+ }
1999
+ /** A choice as a form showed it, drawn rather than an input so it does not look as if it could change. */
2000
+ function readOnlyChoice(kind, chosen, label, hint = null) {
2001
+ return html `<span
2002
+ class="ro-choice ${chosen ? "chosen" : ""}"
2003
+ role=${kind === "check" ? "checkbox" : "radio"}
2004
+ aria-checked=${chosen ? "true" : "false"}
2005
+ aria-disabled="true"
2006
+ ><span class="ro-mark ${kind}">${chosen ? (kind === "check" ? icon("check", 10) : html `<span class="dot"></span>`) : nothing}</span
2007
+ >${label}${hint ? html `<span class="hint">${hint}</span>` : nothing}</span
2008
+ >`;
2009
+ }
2010
+ /** What was entered in `field`, drawn as its kind of control, read only. */
2011
+ function answeredValue(field) {
2012
+ const value = field.value;
2013
+ switch (field.kind) {
2014
+ case "boolean":
2015
+ return html `<div class="choices">${readOnlyChoice("check", value === true, "Yes")}</div>`;
2016
+ case "choices":
2017
+ return html `<div class="choices">
2018
+ ${field.options.map((o) => readOnlyChoice("check", Array.isArray(value) && value.includes(o.value), o.label))}
2019
+ </div>`;
2020
+ case "choice": {
2021
+ const chosen = field.options.find((o) => o.value === value);
2022
+ return html `<span class="ro-value select ${chosen ? "" : "empty"}"
2023
+ >${chosen?.label ?? (value === null ? "Not chosen" : String(value))}${icon("chevronRight", 11)}</span
2024
+ >`;
2025
+ }
2026
+ default:
2027
+ return value === null || value === ""
2028
+ ? html `<span class="ro-value empty">Not entered</span>`
2029
+ : html `<span class="ro-value">${String(value)}</span>`;
2030
+ }
2031
+ }
2032
+ /** The button that answered a form, or that it was not answered. */
2033
+ function answerOutcome(action) {
2034
+ const [glyph, label] = action === "accept"
2035
+ ? ["check", "Submitted"]
2036
+ : action === "decline"
2037
+ ? ["x", "Declined"]
2038
+ : action === "cancel"
2039
+ ? ["playerStop", "Cancelled"]
2040
+ : ["progress", "Not answered"];
2041
+ return html `<span class="answer-label"></span
2042
+ ><span class="outcome ${action ?? "none"}">${icon(glyph, 11)}${label}</span>`;
2043
+ }
2044
+ function formField(name, field, required) {
2045
+ const oneOf = field.oneOf;
2046
+ const choices = field.enum;
2047
+ if (field.type === "boolean") {
2048
+ return html `<label class="check"><input type="checkbox" name=${name} id=${name} ?checked=${field.default === true} /> Yes</label>`;
2049
+ }
2050
+ if (field.type === "array") {
2051
+ const items = field.items;
2052
+ const values = items?.anyOf?.map((o) => [o.const, o.title]) ?? items?.enum?.map((v) => [v, v]) ?? [];
2053
+ return html `<div class="choices">
2054
+ ${values.map(([value, title]) => html `<label><input type="checkbox" name=${name} value=${value ?? ""} /> ${title}</label>`)}
2055
+ </div>`;
2056
+ }
2057
+ if (oneOf || choices) {
2058
+ const values = oneOf?.map((o) => [o.const, o.title]) ?? choices?.map((v) => [v, v]) ?? [];
2059
+ return html `<select name=${name} id=${name} ?required=${required}>
2060
+ ${required ? nothing : html `<option value=""></option>`}
2061
+ ${values.map(([value, title]) => html `<option value=${value ?? ""} ?selected=${field.default === value}>${title}</option>`)}
2062
+ </select>`;
2063
+ }
2064
+ const numeric = field.type === "number" || field.type === "integer";
2065
+ const bounds = numeric ? numberInput(field) : null;
2066
+ return html `<input
2067
+ type=${numeric ? "number" : "text"}
2068
+ name=${name}
2069
+ id=${name}
2070
+ step=${bounds?.step ?? nothing}
2071
+ min=${bounds?.min ?? nothing}
2072
+ max=${bounds?.max ?? nothing}
2073
+ ?required=${required}
2074
+ .value=${field.default === undefined || field.default === null ? "" : String(field.default)}
2075
+ />`;
2076
+ }
2077
+ if (!customElements.get("adroit-chat"))
2078
+ customElements.define("adroit-chat", AdroitChat);
2079
+ function completionIcon(kind) {
2080
+ switch (kind) {
2081
+ case "file":
2082
+ return "file";
2083
+ case "directory":
2084
+ return "folder";
2085
+ case "skill":
2086
+ return "sparkles";
2087
+ default:
2088
+ return "slash";
2089
+ }
2090
+ }