From 5712a220089b4b3e300cd8ccf17aa820a4d27fe8 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Mon, 30 Nov 2026 19:29:25 -0500 Subject: [PATCH 1/7] Node 26.14.0 and marked 18.4.0 --- CHANGELOG.md | 2 +- mise.toml | 2 +- package.json | 2 +- pnpm-lock.yaml | 10 +++++----- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f54c42..18c786f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ All notable changes to `@standards-lab/web-components` are documented here. The - The repository's tooling takes marathon 0.25.0, pnpm 12.23.0, typescript-eslint 8.74.0, chrome-headless-shell 158.0.8127.88, `@types/node` 26.6.11, ESLint 10.16.0, eslint-plugin-boundaries 7.4.5, and jdx/mise-action v5.4.0. -- `marked` is at 18.3.0. +- `marked` is at 18.4.0, and the repository takes Node 26.14.0. - The browser tier takes web-tooling 0.2.0, whose `launch()` runs the browser in a network namespace of its own, so a link or address change on the machine no longer aborts the tests' page loads with `ERR_NETWORK_CHANGED`. The machine now needs `unshare`, `ip`, and unprivileged diff --git a/mise.toml b/mise.toml index a5103e1..1d3387b 100644 --- a/mise.toml +++ b/mise.toml @@ -6,7 +6,7 @@ task.run_auto_install = false [tools] "github:standards-lab/claude-plugins" = { version = "0.25.0", version_prefix = "marathon/v" } actionlint = "1.7.12" -node = "26.13.1" +node = "26.14.0" pnpm = "12.23.0" shellcheck = "0.11.0" "github:microsoft/typescript-go" = { version = "7.0.2", version_prefix = "typescript/v", bin_path = "package/lib" } diff --git a/package.json b/package.json index 1fb12ca..373fb20 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ }, "dependencies": { "lit": "3.3.3", - "marked": "18.3.0" + "marked": "18.4.0" }, "peerDependencies": { "@standards-lab/web-foundation": "^0.4.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e576fde..b797be4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12,8 +12,8 @@ importers: specifier: 3.3.3 version: 3.3.3 marked: - specifier: 18.3.0 - version: 18.3.0 + specifier: 18.4.0 + version: 18.4.0 devDependencies: '@eslint-community/eslint-plugin-eslint-comments': specifier: 4.8.1 @@ -688,8 +688,8 @@ packages: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} - marked@18.3.0: - resolution: {integrity: sha512-ed8zmPXlBb3UfGXN5iHMQyMhFpdqLgoV5umUXx/Q1R+FW3q8VpqpyoKUwlENL9appo2UMvNLURDVaT3AMOryGA==} + marked@18.4.0: + resolution: {integrity: sha512-evbvoaiBPFO2lk2kSkIbrwjPMuX/HjKyefPdZbtwccsJWY91xlLF/SzB5hRsAOwStztmKC09i+IGsUcTYMt//A==} engines: {node: '>= 20'} hasBin: true @@ -1461,7 +1461,7 @@ snapshots: dependencies: p-locate: 5.0.0 - marked@18.3.0: {} + marked@18.4.0: {} minimatch@11.0.9: dependencies: From 0ac015abda19f9a3e5f314f07d325db06a5311a0 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Mon, 30 Nov 2026 19:35:59 -0500 Subject: [PATCH 2/7] sl-drawer's frameless and whole-word table cells in sl-chat-thread, for v0.3.0 sl-drawer gains `frameless`, a reflected boolean property and attribute in the style of `modal`. Docked, it drops the aside's border and radius and the header's and body's padding, and puts the foundation's `visually-hidden` class on the header, so the h2 stays the aside's accessible name (aria-labelledby) while taking no row. The rules are scoped to `:host([frameless]) aside`, so the modal dialog keeps its header, padding, and visible heading. The aside keeps its --bg-1 surface: the brief named border, radius, and padding only. In sl-chat-thread, `.markdown table` sets `overflow-wrap: normal`, so the content's `anywhere` no longer reaches the cells and shrinks the table's min-content; the table's own overflow-x then scrolls it inside the thread. Paragraphs keep breaking long words. The example pages show both: the chat thread has a wide-table state (in the states and at 20rem; the specimen count is 66), and the drawer page a Frameless checkbox, which two new screenshot states use (docked at 1280px, and open at 480px with its frame kept). package.json is 0.3.0; CHANGELOG's Unreleased becomes [0.3.0] - 2026-11-30, with the drawer under Added and the table under Fixed, ordered Added, Changed, Fixed; the README installs v0.3.0. Not tagged. --- CHANGELOG.md | 14 +++++- README.md | 11 ++--- docs/components.md | 18 +++++--- docs/layout.md | 6 +++ examples/chat-thread.html | 18 ++++++++ examples/drawer.html | 8 +++- package.json | 2 +- scripts/screenshots.config.ts | 37 +++++++++++++--- src/chat-thread.css | 1 + src/chat-thread.ts | 4 +- src/drawer.css | 16 ++++++- src/drawer.ts | 17 +++++-- test/browser/chat-thread.test.ts | 63 ++++++++++++++++++++++++++ test/browser/components.test.ts | 4 +- test/browser/drawer.test.ts | 76 ++++++++++++++++++++++++++++++++ 15 files changed, 265 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18c786f..9408e72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,13 @@ All notable changes to `@standards-lab/web-components` are documented here. The [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.3.0] - 2026-11-30 + +### Added + +- `sl-drawer`'s `frameless` attribute, which draws the docked aside with no border, radius, or + padding and hides its heading visually, still the aside's accessible name; the modal drawer keeps + its frame and visible heading. ### Changed @@ -27,6 +33,11 @@ All notable changes to `@standards-lab/web-components` are documented here. The - The demo pages are the example pages: `demo/` is `examples/`, `mise run demo` is `mise run examples`, and their stylesheet is `examples/examples.css`, in the `examples` layer. +### Fixed + +- In `sl-chat-thread`, a Markdown table's cells keep their words whole, no longer breaking them + mid-word, and a table wider than the thread scrolls sideways in its own box. + ## [0.2.0] - 2026-11-22 ### Removed @@ -93,5 +104,6 @@ All notable changes to `@standards-lab/web-components` are documented here. The - Releases by tag: each `v` tag marks a pack commit whose tree is the pack, the build included, and whose one parent is main's merge commit; its GitHub release carries the tarball. +[0.3.0]: https://github.com/standards-lab/web-components/releases/tag/v0.3.0 [0.2.0]: https://github.com/standards-lab/web-components/releases/tag/v0.2.0 [0.1.0]: https://github.com/standards-lab/web-components/releases/tag/v0.1.0 diff --git a/README.md b/README.md index 99c12da..83a7734 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,9 @@ and the components share one copy of each, and a restyle of the foundation's she name reaches the components' shadow roots too. Install all three by their tags: ``` -pnpm add github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 -bun add github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 -npm install --allow-git=root github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 +pnpm add github:standards-lab/web-components#v0.3.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 +bun add github:standards-lab/web-components#v0.3.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 +npm install --allow-git=root github:standards-lab/web-components#v0.3.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 ``` npm 12 refuses git dependencies unless `--allow-git` allows them; `root` allows the ones the @@ -56,7 +56,8 @@ the foundation's `page.css`: - `./entry.js`: `sl-entry`, one directory or file of a document hierarchy, as a button. - `./pagination.js`: `sl-pagination`, a page of entries between its summary and its controls. - `./drawer.js`: `sl-drawer`, its children docked inline on a wide viewport, in a modal drawer - below, or in the modal drawer at every width with `modal`. + below, or in the modal drawer at every width with `modal`; `frameless` docks them with no frame + and no visible heading. - `./shortcuts.js`: `sl-shortcuts`, the keyboard shortcuts of the dialog that holds it, as a table. - `./settings.js`: `sl-settings`, the reader's theme and keyboard settings, applied and stored at once. @@ -190,7 +191,7 @@ mise run currency # report every tool, package, and acti ``` `mise run screenshots` captures each specimen page light and dark, in vertical tiles at most -1200px tall; it captures the drawer's page in its viewport at each of its six states, and the +1200px tall; it captures the drawer's page in its viewport at each of its eight states, and the settings and shortcuts pages again with their dialogs open. It runs the `web-screenshots` bin of [web-tooling](https://github.com/standards-lab/web-tooling), the devDependency the browser tier's driver and server also come from, over the capture description diff --git a/docs/components.md b/docs/components.md index 173d37c..c2dece4 100644 --- a/docs/components.md +++ b/docs/components.md @@ -40,8 +40,11 @@ the tests measure as they do. swaps only the wrapper, so the slotted content is never moved, disconnected, or re-created: an open drawer docks, and docked content becomes a closed drawer. It slides only when the reader allows motion. `modal`, a reflected boolean, makes it the modal dialog at every width, ignoring - `dock`; setting or removing it is a switch too, so it closes an open drawer silently. Its mode is - the custom state `docked` or `drawer`, which a page may style. + `dock`; setting or removing it is a switch too, so it closes an open drawer silently. + `frameless`, a reflected boolean, draws the docked aside with no border, radius, or padding and + hides its heading visually, still the aside's accessible name; the modal drawer keeps its frame + and visible heading either way. Its mode is the custom state `docked` or `drawer`, which a page + may style. - `./shortcuts.js`: `sl-shortcuts`, the page's keyboard shortcuts for a help dialog, as a plain-text table of Keys and Action: exactly what the foundation's `bindings(dialog)` gives for the dialog that holds it, `bindings(null)` outside one, in its order, each key in a `kbd` as the keys @@ -183,8 +186,9 @@ screenshot script focuses the focus section's `[data-focus-start]` mark, which t script, then presses Tab as many times as the mark's value says, so `:focus-visible` matches. A page whose component draws its own frame drops the dashed one, so a capture shows the component's frame alone. The drawer's mode is the viewport's, so its page is an app's frame instead, its states the -page's at two widths: docked at 1280px, and closed, open, and open right to left at 480px. Its -Outline drawer is `modal`, and its captures open it at 1280px, then reach its Close by Tab. The -settings and shortcuts captures add each page's dialog, opened by its key. The specimen pages link -the foundation's `page-full.css` and import its `register-full.js`, so a profile applies by its -attribute on the root. +page's at two widths: docked, and docked and frameless, at 1280px, and closed, open, open right to +left, and frameless and open at 480px; its Frameless checkbox sets the Documents drawer's +`frameless`. Its Outline drawer is `modal`, and its captures open it at 1280px, then reach its +Close by Tab. The settings and shortcuts captures add each page's dialog, opened by its key. The +specimen pages link the foundation's `page-full.css` and import its `register-full.js`, so a +profile applies by its attribute on the root. diff --git a/docs/layout.md b/docs/layout.md index 2975bf7..b37e4fc 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -107,6 +107,9 @@ layout each one promises. - A function's name and a call's id, a `call_` id of 37 characters as a rule, move to the next line whole and break anywhere only when longer than the line, so a narrow thread shows them whole inside its frame. Inline code in a reply keeps whole the same way rather than break at a hyphen. +- A reply's word longer than its line breaks anywhere, except in a table: the table's cells keep + their words whole, and a table wider than the thread scrolls sideways in its own box, as a code + block does, so the thread never widens. - A refusal's rule is in the warning hue, so it reads apart from the answer and from a quotation's neutral rule. - A streaming status's dot pulses unless motion is reduced. @@ -114,6 +117,9 @@ layout each one promises. ## Drawer - `--drawer-from` is the edge the drawer hides past, by the writing direction. +- A `frameless` docked aside drops its border, its radius, and the header's and body's padding, so + the children sit flush in the host's box; its header is visually hidden, a one-pixel clipped box + that takes no row, and its heading still names the aside. - The label takes the step the foundation gives an `h4`, `--text-l`: the heading of a contained surface, one above the body text and the entries' names it heads and two below a page's section `h2`, so it never competes with the page's `h1` or `h2`. diff --git a/examples/chat-thread.html b/examples/chat-thread.html index cc5dea2..b3ff2f3 100644 --- a/examples/chat-thread.html +++ b/examples/chat-thread.html @@ -151,6 +151,23 @@ ), ]).flat(); + const table = [ + user("List the run's outputs with their stages and sizes."), + assistant( + "msg_01J9X4R7QE", + [ + "The run `run-01J9X4R7Q2M8ZK3T5V6W` wrote four outputs:", + "", + "| Item | Stage | Description | Format | Size | Status |", + "| :--- | :--- | :--- | :--- | ---: | :--- |", + "| summary.md | summarize | The run's summary, reviewed | Markdown | 1.5 kB | Completed |", + "| stages.csv | classify | Each stage's timing | CSV | 48 kB | Completed |", + "| labels.json | classify | Classification labels | JSON | 12 kB | Completed |", + "| report.pdf | summarize | The printable report | PDF | 2.4 MB | Incomplete |", + ].join("\n"), + ), + ]; + const thread = (fields) => () => make("sl-chat-thread", fields); const states = [ ["Empty", []], @@ -162,6 +179,7 @@ ["Failed: the reply failed part way", failed], ["Reasoning and tool calls", tools], ["An unknown item and an unknown part among known ones, skipped", unknown], + ["A wide table, scrolling sideways in its own box where the thread is narrower, its cells' words whole", table], ["Long content: held to 16rem by the page, scrolling inside the thread, opened at its end", long, "held"], ].flatMap(([label, items, className = ""]) => [false, true].map((verbose) => ({ diff --git a/examples/drawer.html b/examples/drawer.html index ce1aa1e..a5a5d59 100644 --- a/examples/drawer.html +++ b/examples/drawer.html @@ -35,6 +35,9 @@ drawer.addEventListener("open", expanded); drawer.addEventListener("close", expanded); } + document.querySelector("#frameless").addEventListener("change", (event) => { + document.querySelector("#documents").frameless = event.target.checked; + }); @@ -43,8 +46,11 @@

Drawer

sl-drawer, docked beside the content at 48rem and wider, and below it a modal drawer over the whole viewport, sliding in from the inline-start edge. The Outline - drawer is modal, a modal drawer at every width. + drawer is modal, a modal drawer at every width. Frameless, the docked + Documents drawer draws no border, radius, or padding, and its heading is visually hidden; + the modal drawer keeps both.

+

diff --git a/package.json b/package.json index 373fb20..48bd0c4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@standards-lab/web-components", - "version": "0.2.0", + "version": "0.3.0", "license": "Apache-2.0", "type": "module", "files": [ diff --git a/scripts/screenshots.config.ts b/scripts/screenshots.config.ts index c4d03cd..04815be 100644 --- a/scripts/screenshots.config.ts +++ b/scripts/screenshots.config.ts @@ -1,11 +1,12 @@ // The capture description web-tooling's web-screenshots bin reads for mise run screenshots: each // specimen page under examples/, whole in tiles; the drawer's page in its viewport at a wide and a -// narrow width in four states, and its modal drawer open at the wide width, then with its Close -// reached by Tab and its hint shown; the settings' page whole, then with the Settings dialog opened -// by S, wide and narrow, focus in its rows; the shortcuts' page whole, then with the Help dialog -// opened by ?, its Close reached by Tab and its hint shown; the palette, space, and type facets at -// the foundation's defaults; --all's profiles; each page's registered profiles; and the repository -// served as the browser tier serves it. +// narrow width in four states, docked and frameless, frameless and open below the dock, and its +// modal drawer open at the wide width, then with its Close reached by Tab and its hint shown; the +// settings' page whole, then with the Settings dialog opened by S, wide and narrow, focus in its +// rows; the shortcuts' page whole, then with the Help dialog opened by ?, its Close reached by Tab +// and its hint shown; the palette, space, and type facets at the foundation's defaults; --all's +// profiles; each page's registered profiles; and the repository served as the browser tier serves +// it. import type { DescribedPage, @@ -93,6 +94,13 @@ const pressed = await then?.(page); }; +const frameless: Step = async (page) => { + await page.evaluate(`(async () => { + document.querySelector("#frameless").click(); + await document.querySelector("#documents").updateComplete; + })()`); +}; + const drawerStates: DescribedState[] = [ { name: "drawer-docked", @@ -100,6 +108,23 @@ const drawerStates: DescribedState[] = [ viewport: docked, full: false, }, + { + name: "drawer-frameless", + caption: "the drawer, docked and frameless at 48rem and wider", + viewport: docked, + full: false, + open: frameless, + }, + { + name: "drawer-frameless-open", + caption: "the drawer, frameless and open below 48rem, its frame and heading kept", + viewport: undocked, + full: false, + open: async (page) => { + await frameless(page); + await openedByEnter("ltr")(page); + }, + }, { name: "drawer-closed", caption: "the drawer, closed below 48rem", diff --git a/src/chat-thread.css b/src/chat-thread.css index 209047f..f3df623 100644 --- a/src/chat-thread.css +++ b/src/chat-thread.css @@ -95,6 +95,7 @@ summary, display: block; max-inline-size: max-content; overflow-x: auto; + overflow-wrap: normal; } .refusal { padding-inline-start: var(--space-s); diff --git a/src/chat-thread.ts b/src/chat-thread.ts index 3a4697c..47dc7db 100644 --- a/src/chat-thread.ts +++ b/src/chat-thread.ts @@ -129,7 +129,9 @@ function end(frame: HTMLElement) { * show too, each collapsed in a native details; otherwise they are hidden. A reasoning item's line * carries its summary after its kind and status, and its details holds its content alone; with a * summary and no content, the line stands alone, with nothing to expand. Item and part types the - * thread doesn't know are skipped. Display-only: it sends no event and binds no key. + * thread doesn't know are skipped. A word longer than the thread's line breaks to fit, except in a + * Markdown table, whose cells keep their words whole and which scrolls sideways in its own box when + * wider than the thread. Display-only: it sends no event and binds no key. * * The items are an ordered list of articles, not a log: order is the thread's meaning, and a list * tells assistive technology how many items there are and where each sits. A log's live region diff --git a/src/drawer.css b/src/drawer.css index b0f3857..00e3622 100644 --- a/src/drawer.css +++ b/src/drawer.css @@ -1,6 +1,6 @@ /* - * The drawer's shadow-root sheet: the docked aside's frame and the modal dialog covering the - * viewport, each a dialog header over a scrolling body, and the dialog's slide, in the motion + * The drawer's shadow-root sheet: the docked aside's frame, none when `frameless`, and the modal + * dialog covering the viewport, each a dialog header over a scrolling body, and the dialog's slide, in the motion * sheet's --duration-m. * Unlayered, above the foundation's reset, elements, utilities, glyph-button, dialog, and motion * sheets; it reads only the baseline tokens. @@ -24,6 +24,18 @@ aside { background-color: var(--bg-1); color: var(--fg); } +:host([frameless]) aside { + border: 0; + border-radius: 0; +} +:host([frameless]) aside > header { + padding: 0; + border: 0; +} +:host([frameless]) aside > .body { + padding: 0; + scroll-padding: 0; +} dialog { position: fixed; inset: 0; diff --git a/src/drawer.ts b/src/drawer.ts index 8cfa377..5a43f4c 100644 --- a/src/drawer.ts +++ b/src/drawer.ts @@ -4,7 +4,7 @@ // the one heading that names them, over a body holding the slot. The mode is the viewport's, by a // media query on `dock`, unless `modal` is set; a switch swaps only the shadow root's wrapper and // its slot, so the slotted content, the host's own children, is never moved, disconnected, or -// re-created. +// re-created. With `frameless`, the docked aside draws no frame and its heading is visually hidden. // See docs/internals.md import { html, LitElement, type PropertyDeclarations, type PropertyValues } from "lit"; @@ -66,7 +66,10 @@ export type CloseDetail = Record; * rem and em are the initial font size's, so a viewport of exactly `dock` docks; a length the * query can't read never matches, so the drawer stays docked. * `modal`, reflected, makes the drawer a modal dialog at every width, as below `dock`, and `dock` - * is ignored while it is set. Setting or removing `modal` is a switch too: it closes an open drawer + * is ignored while it is set. + * `frameless`, reflected, takes the docked aside's frame away: no border, no radius, and no padding + * around the children, and its header is visually hidden, the heading still naming the aside for + * assistive technology. The modal drawer keeps its frame and visible heading either way. Setting or removing `modal` is a switch too: it closes an open drawer * silently, whether or not the mode changes. * Each mode renders only its own header, so the shadow tree holds one heading at a time. The mode * is the custom state `docked` or `drawer`, which a page may style. @@ -77,6 +80,7 @@ export class Drawer extends LitElement { static properties = { open: { type: Boolean, reflect: true }, modal: { type: Boolean, reflect: true }, + frameless: { type: Boolean, reflect: true }, dock: { type: String }, label: { type: String }, } satisfies PropertyDeclarations; @@ -85,9 +89,11 @@ export class Drawer extends LitElement { declare open: boolean; /** Whether the drawer is a modal dialog at every width, ignoring `dock`; reflected to `modal`. */ declare modal: boolean; + /** Whether the docked aside draws no frame and hides its heading visually; reflected. */ + declare frameless: boolean; /** The width at which the drawer docks, and wider: a CSS length, read in a media query. */ declare dock: string; - /** The visible heading of the docked aside and of the drawer, which names each. */ + /** The heading of the docked aside and of the drawer, which names each. */ declare label: string; readonly #internals = this.attachInternals(); @@ -99,6 +105,7 @@ export class Drawer extends LitElement { super(); this.open = false; this.modal = false; + this.frameless = false; this.dock = "48rem"; this.label = ""; } @@ -221,7 +228,9 @@ export class Drawer extends LitElement { render() { if (!this.#narrow) { return html``; } diff --git a/test/browser/chat-thread.test.ts b/test/browser/chat-thread.test.ts index ea2f31c..af6ffe4 100644 --- a/test/browser/chat-thread.test.ts +++ b/test/browser/chat-thread.test.ts @@ -339,6 +339,69 @@ describe("chat thread", { timeout: 60_000 }, () => { ); }); + test("in a narrow thread a table's cells keep their words whole and a wide table scrolls in its own box, while a paragraph's long word breaks to fit", async () => { + const word = "x".repeat(120); + const header = ["Item", "Quantity", "Description", "Supplier", "Warehouse", "Status"]; + const text = [ + word, + "", + `| ${header.join(" | ")} |`, + `|${" --- |".repeat(header.length)}`, + "| Widget | 12 | Bracket | Northwind | Central | Shipped |", + ].join("\n"); + const measure = ( + width: string, + ): Promise<{ + frameScrolls: boolean; + tableScrolls: boolean; + tableInside: boolean; + paragraphLines: number; + paragraphInside: boolean; + cells: [string, number][]; + }> => + page.evaluate(`(async () => { + const thread = Object.assign(document.createElement("sl-chat-thread"), { + items: [${JSON.stringify(assistant("msg_1", text))}], + }); + thread.style.inlineSize = "${width}"; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + const root = thread.shadowRoot; + const frame = root.querySelector(".frame"); + const table = root.querySelector(".markdown table"); + const paragraph = root.querySelector(".markdown p"); + const lines = (element) => { + const range = document.createRange(); + range.selectNodeContents(element); + return new Set( + [...range.getClientRects()].filter((rect) => rect.width > 0).map((rect) => Math.round(rect.top)), + ).size; + }; + const right = frame.getBoundingClientRect().left + frame.clientLeft + frame.clientWidth; + return { + frameScrolls: frame.scrollWidth > frame.clientWidth, + tableScrolls: table.scrollWidth > table.clientWidth, + tableInside: table.getBoundingClientRect().right <= right + 0.5, + paragraphLines: lines(paragraph), + paragraphInside: paragraph.getBoundingClientRect().right <= right + 0.5, + cells: [...table.querySelectorAll("th, td")].map((cell) => [cell.textContent, lines(cell)]), + }; + })()`); + const narrow = await measure("16rem"); + assert.equal(narrow.frameScrolls, false, "the thread never widens"); + assert.equal(narrow.tableScrolls, true, "the table scrolls sideways"); + assert.equal(narrow.tableInside, true, "the table's box stays inside the thread"); + assert.ok(narrow.paragraphLines > 1, `the long word wraps: ${narrow.paragraphLines}`); + assert.equal(narrow.paragraphInside, true); + assert.deepEqual( + narrow.cells.filter(([, lines]) => lines !== 1), + [], + "each one-word cell is one line, its word whole", + ); + const wide = await measure("80rem"); + assert.deepEqual([wide.frameScrolls, wide.tableScrolls], [false, false]); + }); + test("a reasoning item's summary is on its line, after the kind, and its content alone inside", async () => { const view = await shown({ verbose: true, diff --git a/test/browser/components.test.ts b/test/browser/components.test.ts index 9ca1a7c..f67e8e7 100644 --- a/test/browser/components.test.ts +++ b/test/browser/components.test.ts @@ -1522,8 +1522,8 @@ describe("components", { timeout: 60_000 }, () => { assert.ok(overflow <= 0, `${profile}: the states overflow the column by ${overflow}`); assert.equal( shown.length, - 62, - `${profile}: 29 states twice, the three fits, and the focus state`, + 66, + `${profile}: 31 states twice, the three fits, and the focus state`, ); const wrapped = (narrow: boolean) => shown.filter((thread) => thread.narrow === narrow).flatMap((thread) => thread.wrapped); diff --git a/test/browser/drawer.test.ts b/test/browser/drawer.test.ts index 52c352d..b600aae 100644 --- a/test/browser/drawer.test.ts +++ b/test/browser/drawer.test.ts @@ -304,6 +304,82 @@ describe("drawer", { timeout: 60_000 }, () => { ); }); + const frame = (): Promise<{ + aside: string[]; + header: number[]; + body: string; + child: number[]; + host: number[]; + }> => + page.evaluate(`(() => { + const drawer = document.querySelector("sl-drawer"); + const root = drawer.shadowRoot; + const aside = getComputedStyle(root.querySelector("aside")); + const header = root.querySelector("header").getBoundingClientRect(); + const child = document.querySelector("#filter").getBoundingClientRect(); + const host = drawer.getBoundingClientRect(); + return { + aside: [aside.borderTopWidth, aside.borderInlineStartWidth, aside.borderTopLeftRadius], + header: [header.width, header.height], + body: getComputedStyle(root.querySelector(".body")).padding, + child: [child.left, child.top], + host: [host.left, host.top], + }; + })()`); + + test("docked and frameless, the aside draws no border, radius, or padding, its heading visually hidden and still its name", async () => { + await mount(WIDE, {}, "", HEIGHT, { attributes: "frameless" }); + const { host, ...shown } = await frame(); + assert.deepEqual(shown, { + aside: ["0px", "0px", "0px"], + header: [1, 1], + body: "0px", + child: host, + }); + assert.deepEqual(await headings(), { + texts: ["Documents"], + inWrapper: true, + visible: true, + labelledby: "title", + label: null, + }); + assert.deepEqual(await exposed("complementary"), ["Documents"]); + assert.deepEqual(await exposed("heading"), ["Documents"]); + }); + + test("frameless reflects from the property, and removed the docked aside's frame and visible heading return", async () => { + await mount(WIDE); + const framed = await frame(); + assert.notEqual(framed.aside[0], "0px"); + assert.ok(framed.header[1] > 1, "the header takes a row"); + await page.evaluate(`document.querySelector("sl-drawer").frameless = true`); + await page.evaluate(`document.querySelector("sl-drawer").updateComplete`); + assert.equal( + await page.evaluate(`document.querySelector("sl-drawer").hasAttribute("frameless")`), + true, + ); + assert.deepEqual((await frame()).header, [1, 1]); + await page.evaluate(`document.querySelector("sl-drawer").frameless = false`); + await page.evaluate(`document.querySelector("sl-drawer").updateComplete`); + assert.deepEqual(await frame(), framed); + }); + + test("frameless, the modal drawer keeps its frame's padding and its visible heading", async () => { + await mount(NARROW, {}, "", HEIGHT, { attributes: "frameless" }); + await openByKeyboard(); + const shown: { header: number; body: string } = await page.evaluate(`(() => { + const root = document.querySelector("sl-drawer").shadowRoot; + return { + header: root.querySelector("header").getBoundingClientRect().height, + body: getComputedStyle(root.querySelector(".body")).padding, + }; + })()`); + assert.ok(shown.header > 1, `the header takes a row: ${shown.header}`); + assert.notEqual(shown.body, "0px"); + assert.deepEqual(await exposed("dialog"), ["Documents"]); + assert.equal((await read()).focused, "drawer h2"); + }); + for (const [mode, width] of [ ["docked", WIDE], ["drawer", NARROW], From 0eac0d4da8b43bc2853d8429ec08e1ce8940fb71 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Mon, 30 Nov 2026 21:03:26 -0500 Subject: [PATCH 3/7] sl-drawer's frameless docs keep modal's switch with modal and wrap at the line width Package documentation: the class doc comment's frameless paragraph had split modal's own switch sentence off onto an overlong line, and the sheet's header ran past 100 columns. --- src/drawer.css | 4 ++-- src/drawer.ts | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/drawer.css b/src/drawer.css index 00e3622..7e44d76 100644 --- a/src/drawer.css +++ b/src/drawer.css @@ -1,7 +1,7 @@ /* * The drawer's shadow-root sheet: the docked aside's frame, none when `frameless`, and the modal - * dialog covering the viewport, each a dialog header over a scrolling body, and the dialog's slide, in the motion - * sheet's --duration-m. + * dialog covering the viewport, each a dialog header over a scrolling body, and the dialog's slide, + * in the motion sheet's --duration-m. * Unlayered, above the foundation's reset, elements, utilities, glyph-button, dialog, and motion * sheets; it reads only the baseline tokens. * See docs/layout.md diff --git a/src/drawer.ts b/src/drawer.ts index 5a43f4c..2b61c8f 100644 --- a/src/drawer.ts +++ b/src/drawer.ts @@ -66,11 +66,11 @@ export type CloseDetail = Record; * rem and em are the initial font size's, so a viewport of exactly `dock` docks; a length the * query can't read never matches, so the drawer stays docked. * `modal`, reflected, makes the drawer a modal dialog at every width, as below `dock`, and `dock` - * is ignored while it is set. + * is ignored while it is set. Setting or removing `modal` is a switch too: it closes an open drawer + * silently, whether or not the mode changes. * `frameless`, reflected, takes the docked aside's frame away: no border, no radius, and no padding * around the children, and its header is visually hidden, the heading still naming the aside for - * assistive technology. The modal drawer keeps its frame and visible heading either way. Setting or removing `modal` is a switch too: it closes an open drawer - * silently, whether or not the mode changes. + * assistive technology. The modal drawer keeps its frame and visible heading either way. * Each mode renders only its own header, so the shadow tree holds one heading at a time. The mode * is the custom state `docked` or `drawer`, which a page may style. */ From 8f0db17a0c3941a6345e48783153e5245be2c592 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Mon, 30 Nov 2026 21:22:53 -0500 Subject: [PATCH 4/7] Editor pass: the frameless drawer's wording --- CHANGELOG.md | 4 ++-- docs/components.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9408e72..1c348ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ All notable changes to `@standards-lab/web-components` are documented here. The ### Added - `sl-drawer`'s `frameless` attribute, which draws the docked aside with no border, radius, or - padding and hides its heading visually, still the aside's accessible name; the modal drawer keeps - its frame and visible heading. + padding and hides its heading visually, though the heading still names the aside; the modal + drawer keeps its frame and visible heading. ### Changed diff --git a/docs/components.md b/docs/components.md index c2dece4..28b6900 100644 --- a/docs/components.md +++ b/docs/components.md @@ -42,8 +42,8 @@ the tests measure as they do. allows motion. `modal`, a reflected boolean, makes it the modal dialog at every width, ignoring `dock`; setting or removing it is a switch too, so it closes an open drawer silently. `frameless`, a reflected boolean, draws the docked aside with no border, radius, or padding and - hides its heading visually, still the aside's accessible name; the modal drawer keeps its frame - and visible heading either way. Its mode is the custom state `docked` or `drawer`, which a page + hides its heading visually, though the heading still names the aside; the modal drawer keeps its + frame and visible heading either way. Its mode is the custom state `docked` or `drawer`, which a page may style. - `./shortcuts.js`: `sl-shortcuts`, the page's keyboard shortcuts for a help dialog, as a plain-text table of Keys and Action: exactly what the foundation's `bindings(dialog)` gives for the dialog From cc605ef097727d91f28804988147423e64b14c69 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 1 Dec 2026 07:48:10 -0500 Subject: [PATCH 5/7] sl-chat-thread's after slot, subagent_result item, and user Markdown, for v0.3.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - An `after` slot inside the frame, after the items, in a box of its own hidden until an element is assigned (set on slotchange, not rendered), so an empty slot takes no room. The follower's ResizeObserver watches that box too, and measures the last item's and the box's growth together. - Following: an update reads "at the end" against the current scroll height or the one last seen, so a delta arriving after unfollowed growth (slotted children, an image) and before the observer's callback keeps following. Tested with growth and deltas in one task, and with deltas streamed faster than frames, at the end and scrolled up. - `subagent_result` item `{type, id?, name, status, href?, label?, content?, error?}`: status is text to show, not ItemStatus, so an app passes its own states (Mikoshi's finished/failed/stopped) through. Validated before render: name and status non-empty text, other fields text where given, else skipped like an unknown item. Rendered in both modes as a collapsed details, "Sub-agent · ", holding the link (label, else href; an href markdown wouldn't link shows as its label alone), then the error, then the content as Markdown, or "No result." when neither. - A user's input_text renders as Markdown with `breaks: true`; answers keep `breaks: false`. markdown() takes `{ breaks }`, and markdown.ts exports `linkable(url)`, the link check the result's href reuses. - Example page: a user message with code, a list, and line breaks; a result collapsed (verbose off and on), opened, and failed opened; a decision form slotted in a held thread. CHANGELOG 0.3.0, README, and docs updated. --- CHANGELOG.md | 16 ++ README.md | 6 +- docs/components.md | 33 +-- docs/internals.md | 16 +- docs/layout.md | 15 +- examples/chat-thread.html | 58 +++++ examples/examples.css | 15 ++ src/chat-thread.css | 23 +- src/chat-thread.ts | 145 ++++++++++--- src/markdown.ts | 41 ++-- test/browser/chat-thread.test.ts | 353 ++++++++++++++++++++++++++++++- test/browser/components.test.ts | 10 +- test/browser/markdown.test.ts | 34 ++- 13 files changed, 684 insertions(+), 81 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c348ce..f0c4050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,23 @@ All notable changes to `@standards-lab/web-components` are documented here. The - `sl-drawer`'s `frameless` attribute, which draws the docked aside with no border, radius, or padding and hides its heading visually, though the heading still names the aside; the modal drawer keeps its frame and visible heading. +- `sl-chat-thread`'s `after` slot: children slotted as `after`, such as a form the conversation + waits on, sit in the thread's frame after its items and scroll with them, and the thread follows + their growth as it follows the last item's, only while the reader is at the frame's end. +- `sl-chat-thread`'s `subagent_result` item, `{type, id?, name, status, href?, label?, content?, + error?}`: a sub-agent's result, shown with verbose on or off as a collapsed line, "Sub-agent", its + name, and its status, holding its link, then its error or its content rendered as Markdown; one + whose name or status isn't non-empty text, or whose other fields aren't text where given, is + skipped. +- `markdown()`'s `breaks` option, which keeps a paragraph's single line break, and `linkable(url)`, + whether a URL may be a link's href, from `./markdown.js`. ### Changed +- `sl-chat-thread` renders a user's `input_text` as Markdown with its line breaks kept, HTML shown + as its text, where it showed plain text; the assistant's Markdown still joins a paragraph's + lines. + - The repository's tooling takes marathon 0.25.0, pnpm 12.23.0, typescript-eslint 8.74.0, chrome-headless-shell 158.0.8127.88, `@types/node` 26.6.11, ESLint 10.16.0, eslint-plugin-boundaries 7.4.5, and jdx/mise-action v5.4.0. @@ -35,6 +49,8 @@ All notable changes to `@standards-lab/web-components` are documented here. The ### Fixed +- `sl-chat-thread` goes on following when a delta arrives after content grew below the reader's + place and before the thread followed that growth, where it read the reader as scrolled up. - In `sl-chat-thread`, a Markdown table's cells keep their words whole, no longer breaking them mid-word, and a table wider than the thread scrolls sideways in its own box. diff --git a/README.md b/README.md index 83a7734..a1b9b72 100644 --- a/README.md +++ b/README.md @@ -61,12 +61,14 @@ the foundation's `page.css`: - `./shortcuts.js`: `sl-shortcuts`, the keyboard shortcuts of the dialog that holds it, as a table. - `./settings.js`: `sl-settings`, the reader's theme and keyboard settings, applied and stored at once. -- `./markdown.js`: `markdown(source)`, a Markdown string as a Lit template of plain elements. +- `./markdown.js`: `markdown(source, { breaks })`, a Markdown string as a Lit template of plain + elements, and `linkable(url)`, whether a URL may be a link's href. - `./artifact-viewer.js`: `sl-artifact-viewer`, one artifact's content by its content type. - `./event-log.js`: `sl-event-log`, events as a log in the order given. - `./search-results.js`: `sl-search-results`, a search's matches under a status line. - `./document-list.js`: `sl-document-list`, a page of documents, an `sl-entry` per document. -- `./chat-thread.js`: `sl-chat-thread`, a conversation's items in order. +- `./chat-thread.js`: `sl-chat-thread`, a conversation's items in order, and its `after` slot's + children after them. - `./composer.js`: `sl-composer`, a multi-line text field and its send control. - `./upload-dropzone.js`: `sl-upload-dropzone`, a zone that takes files, and the app's uploads. - `./stage-timeline.js`: `sl-stage-timeline`, a run's stages as an ordered list of steps. diff --git a/docs/components.md b/docs/components.md index 28b6900..d107330 100644 --- a/docs/components.md +++ b/docs/components.md @@ -71,10 +71,11 @@ the tests measure as they do. ## Rendering -- `./markdown.js`: `markdown(source)`, a Markdown string as a Lit template of plain elements, by - marked's lexer: raw HTML shows as text, an image as its alt text, and a link is an anchor only - to an http, https, or mailto URL or a relative one. It is the one module that imports marked, - which an import map then maps too. +- `./markdown.js`: `markdown(source, { breaks })`, a Markdown string as a Lit template of plain + elements, by marked's lexer: raw HTML shows as text, an image as its alt text, and a link is an + anchor only to an http, https, or mailto URL or a relative one, which `linkable(url)` tells; with + `breaks`, a paragraph's single line break is kept as a `br`. It is the one module that imports + marked, which an import map then maps too. ## Inspection @@ -140,15 +141,21 @@ the tests measure as they do. ## Conversation - `./chat-thread.js`: `sl-chat-thread`, a conversation's items in order, a structural subset of - Open Responses: a user's text as plain text, the assistant's as rendered Markdown, a refusal - labelled, and a streaming reply re-rendered in place; with `verbose`, reasoning, function calls, - and their outputs too, each collapsed in a native details, a reasoning item's summary on its - line and its content inside, and a call's arguments and its output that are valid JSON - formatted from their own tokens by the foundation's `format.js`. A thread its consumer holds - to a height scrolls inside, opening at its end and following the newest item only from its end - or on a user's message; unheld, it is as tall as its content and follows nothing, so a consumer - that wants it followed holds it. It exports its item types and sends no event. It imports - `./markdown.js`, so its page maps marked too. + Open Responses: a user's text as rendered Markdown with its line breaks kept, the assistant's as + rendered Markdown, a refusal labelled, and a streaming reply re-rendered in place; with + `verbose`, reasoning, function calls, and their outputs too, each collapsed in a native details, + a reasoning item's summary on its line and its content inside, and a call's arguments and its + output that are valid JSON formatted from their own tokens by the foundation's `format.js`. A + `subagent_result` item, the thread's own, `{type, id?, name, status, href?, label?, content?, + error?}`, shows in either mode as a collapsed line, "Sub-agent", its name, and its status as + given, holding its link, `label` or else `href`, then its error or its Markdown content; one + whose name or status isn't non-empty text, or whose other fields aren't text where given, is + skipped. Children slotted as `after`, such as a form the conversation waits on, sit in the frame + after the items and scroll with them. A thread its consumer holds to a height scrolls inside, + opening at its end and following the newest item, its last item's growth, and the slotted + children's, only from its end or on a user's message; unheld, it is as tall as its content and + follows nothing, so a consumer that wants it followed holds it. It exports its item types and + sends no event. It imports `./markdown.js`, so its page maps marked too. - `./composer.js`: `sl-composer`, a multi-line text field that grows to eight lines, and its send control, which a stop control replaces while `busy`; it dispatches `send` with the text, then clears the field, and `stop`. Its `send()` does what activating send does, so an app that diff --git a/docs/internals.md b/docs/internals.md index 2c3afef..ac46799 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -48,7 +48,10 @@ each sheet is laid out as it is. - An update follows the newest item when the frame was at its end before it, showed no items yet, or the update adds a user's message, the newest or the one before the reply's first text when the - consumer adds both at once. + consumer adds both at once. At its end is measured against the scroll height now and the one last + seen, either: content grown since the last update, the slotted children or an image, that the + observer hasn't yet followed, would otherwise leave a delta arriving before its callback reading + the reader as scrolled up, and the follow would stop. - The last item growing with no update, a details opened in it or an image that loads, is watched by a `ResizeObserver` on the frame's content rather than the details' `toggle` event: it sees every cause and leaves the details toggling natively. Its callback runs after layout, so the reader's @@ -56,9 +59,16 @@ each sheet is laid out as it is. height. Every resize records the heights it leaves, so a growth above the end, which leaves the reader short of the new end, measures the next growth of the last item against the end as it now is. The scroll leaves the content's size alone, so it never loops the observer. +- The `after` slot sits in a box of its own after the list, which the same observer watches, and + the growth it follows is the last item's and that box's together. The box is hidden while no + element is assigned, set on `slotchange` rather than rendered, so its padding takes no room and + its first child shows through the observer, followed as any growth is. - Connected again, the frame is measured and observed anew, so the observer's first callback finds the content as the reader does and scrolls nothing on its own. Detached, the frame has no layout to follow or measure. +- A sub-agent result is checked before it renders: its name and status must be non-empty text, and + its id, link, label, content, and error text where given, or it is skipped as an unknown item is. + Its status is text to show, not an `ItemStatus`, so an app passes its own states through. - A reasoning item's summary parts join into one run; a part with no text yet, as one just begun streaming, is no summary. The standalone line puts no whitespace before its kind, which would widen it past the summaries' marker. @@ -119,7 +129,9 @@ each sheet is laid out as it is. ## Markdown - Each call lexes on a fresh copy of marked's defaults, so no `marked.use()` or `setOptions()` - elsewhere on the page reaches this renderer. + elsewhere on the page reaches this renderer. `breaks` is off unless the caller asks: the chat + thread asks for a user's text, typed with its line breaks meant, and not for an answer, whose + Markdown wraps its paragraphs' lines as it pleases. - The lexer leaves named character references in text, link destinations, and titles for its own renderer's HTML to resolve, and text inside a raw block as written. They are resolved by the HTML parser in a `textarea`'s RCDATA, where no markup is parsed, of a document with no browsing diff --git a/docs/layout.md b/docs/layout.md index b37e4fc..1784153 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -97,7 +97,9 @@ layout each one promises. ## Chat thread - A user's message sits at the inline end, short of the full width, on the first elevated surface; - the assistant's spans the list. Neither has a border: the thread's frame is the one. + the assistant's spans the list. Neither has a border: the thread's frame is the one. A user's + Markdown renders in the bubble as an answer's does, a single paragraph the one the plain text + was, so the bubble keeps its layout. - A reasoning item with nothing to expand is a paragraph whose gutter is an inline list item with the summaries' own disclosure marker, undrawn, so its kind lines up with theirs. The gutter is hidden from the accessibility tree, so no marker is read for a disclosure that isn't one. @@ -111,7 +113,16 @@ layout each one promises. their words whole, and a table wider than the thread scrolls sideways in its own box, as a code block does, so the thread never widens. - A refusal's rule is in the warning hue, so it reads apart from the answer and from a quotation's - neutral rule. + neutral rule; a sub-agent result's error takes the same rule in the failure hue. +- A sub-agent result's line is a summary like a verbose item's, its status an inline block after a + middle dot, so the status never breaks inside itself and its name, like a function's, breaks only + when longer than the line. Its content keeps the reply's color, not a verbose item's quieter one: + it is the sub-agent's answer. Its link, error, and content stand a paragraph's space apart, as + the elements sheet sets paragraphs. +- The `after` slot's box takes the list's inline padding and its block-end padding, the list's own + block-end padding standing as the gap between the last item and the slotted children, the same + as between items; it is hidden while nothing is slotted, so an empty slot adds nothing to the + frame. - A streaming status's dot pulses unless motion is reduced. ## Drawer diff --git a/examples/chat-thread.html b/examples/chat-thread.html index b3ff2f3..8c40a0e 100644 --- a/examples/chat-thread.html +++ b/examples/chat-thread.html @@ -136,6 +136,46 @@ }, ]; + const asked = [ + user( + [ + "Rerun `classify` on `run-01J9X4R7Q2M8ZK3T5V6W`, then:", + "", + "- compare its **labels** with the last run's", + "- list what changed", + "", + "Keep it short.", + "One line per label.", + ].join("\n"), + ), + assistant("msg_01J9X4R7QF", "The rerun's labels match the last run's, except **invoice**, now **receipt**."), + ]; + + const subagent = { + type: "subagent_result", + id: "sr_01J9X4R7QG", + name: "harbor-review", + status: "finished", + href: "https://example.com/contexts/harbor/items/an_01J9X4R7QH", + label: "Harbor review", + content: [ + "The harbor's two contexts agree on the **berth schedule**:", + "", + "- `berth-4` is booked through Friday", + "- `berth-7` is free from Thursday", + ].join("\n"), + }; + const delegated = [ + user("Ask a sub-agent to review the harbor's schedule."), + assistant("msg_01J9X4R7QJ", "I started a sub-agent over **/projects/harbor**; its result follows."), + subagent, + assistant("msg_01J9X4R7QK", "Berth 7 is free from Thursday."), + ]; + const failedResult = [ + user("Ask a sub-agent to review the harbor's schedule."), + { ...subagent, status: "failed", href: undefined, label: undefined, content: undefined, error: "The target context /projects/harbor no longer exists." }, + ]; + const long = Array.from({ length: 6 }, (_, turn) => [ user(`Step ${turn + 1}: what happened in stage ${(turn % 2) + 1}?`), assistant( @@ -177,7 +217,9 @@ ["A refusal", refusal], ["Incomplete: the reply stopped before finishing", incomplete], ["Failed: the reply failed part way", failed], + ["A user's message as Markdown: code, a list, and its line breaks kept", asked], ["Reasoning and tool calls", tools], + ["A sub-agent's result, a collapsed line between the replies", delegated], ["An unknown item and an unknown part among known ones, skipped", unknown], ["A wide table, scrolling sideways in its own box where the thread is narrower, its cells' words whole", table], ["Long content: held to 16rem by the page, scrolling inside the thread, opened at its end", long, "held"], @@ -256,6 +298,22 @@ { label: "Reasoning and tool calls, each opened; verbose on", build: opened({ items: tools, verbose: true }) }, ...reasoningStates, ); + states.splice( + states.findIndex(({ label }) => label.startsWith("A sub-agent's result")) + 2, + 0, + { label: "A sub-agent's result, opened: its link and its content", build: opened({ items: delegated }) }, + { label: "A sub-agent's result that failed, opened: its error", build: opened({ items: failedResult }) }, + ); + const decision = () => + make("form", { slot: "after", className: "decision" }, [ + make("p", { textContent: "Allow start_subagent over /projects/harbor?" }), + make("button", { type: "button", textContent: "Deny" }), + make("button", { type: "button", textContent: "Allow" }), + ]); + states.push({ + label: "A decision form slotted after the items, in a held thread opened at its end", + build: () => make("sl-chat-thread", { items: [...long, user("Review the harbor.")], className: "held" }, [decision()]), + }); specimens(states, { label: "Focused by Tab: the scrolling frame", build: thread({ items: long, className: "held" }), diff --git a/examples/examples.css b/examples/examples.css index 70e8014..16995ea 100644 --- a/examples/examples.css +++ b/examples/examples.css @@ -63,6 +63,21 @@ block-size: 16rem; } + /* A decision form slotted after a chat thread's items: its question, then its actions. */ + .decision { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2xs) var(--space-s); + padding: var(--space-xs) var(--space-s); + border: var(--line-s) solid var(--border); + border-radius: var(--radius-md); + } + .decision > p { + flex: 1 1 16ch; + margin: 0; + } + /* The parents that size a component to its content, each outlining the width it took. */ .fit-inline-block, .fit-flex, diff --git a/src/chat-thread.css b/src/chat-thread.css index f3df623..5d2af93 100644 --- a/src/chat-thread.css +++ b/src/chat-thread.css @@ -1,7 +1,8 @@ /* * The chat thread's shadow-root sheet: the utilities' scrolling frame around the bare list of - * items, each message's place and label row, a verbose item's line, a refusal's mark, and the - * streaming indicator's dot, which the motion sheet's pulse runs. + * items and the slotted children after it, each message's place and label row, a verbose item's + * and a sub-agent result's line, a refusal's and a result error's mark, and the streaming + * indicator's dot, which the motion sheet's pulse runs. * Unlayered, above the foundation's reset, elements, utilities, and motion sheets; it reads only * the baseline tokens. * See docs/layout.md @@ -62,7 +63,8 @@ summary, .summary-text { overflow-wrap: anywhere; } -.summary-text::before { +.summary-text::before, +.outcome::before { content: "·\a0" / ""; color: var(--fg-3); } @@ -71,7 +73,8 @@ summary, font-weight: 600; } .kind, -.status { +.status, +.outcome { display: inline-block; } .id { @@ -97,10 +100,14 @@ summary, overflow-x: auto; overflow-wrap: normal; } -.refusal { +.refusal, +.error { padding-inline-start: var(--space-s); border-inline-start: var(--line-m) solid var(--orange); } +.error { + border-inline-start-color: var(--red); +} .refusal > .label { color: var(--orange); } @@ -125,7 +132,13 @@ summary, .verbose .text + .text { margin-block-start: var(--space-2xs); } +.result > .content > * + * { + margin-block-start: var(--space-s); +} .empty-thread { padding: var(--space-xs) var(--space-s); color: var(--fg-2); } +.after { + padding: 0 var(--space-s) var(--space-s); +} diff --git a/src/chat-thread.ts b/src/chat-thread.ts index 47dc7db..ade174b 100644 --- a/src/chat-thread.ts +++ b/src/chat-thread.ts @@ -2,7 +2,8 @@ // inside one frame that scrolls when its consumer constrains its block size. The items are a // structural subset of Open Responses (spec 2026-04-24): messages, reasoning, function calls, and // their outputs, by the spec's JSON field names, so a response's output or a conversation's -// history fits as it is. +// history fits as it is; a sub-agent's result is an item of the thread's own, shaped as they are. +// Content slotted as `after` follows the items inside the frame. // See docs/internals.md import { @@ -21,7 +22,7 @@ import motion from "@standards-lab/web-foundation/motion.css" with { type: "css" import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define } from "@standards-lab/web-foundation/dom.js"; import { tryFormatJson } from "@standards-lab/web-foundation/format.js"; -import { markdown } from "./markdown.ts"; +import { linkable, markdown } from "./markdown.ts"; import styles from "./chat-thread.css" with { type: "css" }; /** The tag the element defines. */ @@ -33,7 +34,7 @@ export const tagName = "sl-chat-thread"; */ export type ItemStatus = "in_progress" | "completed" | "incomplete" | "failed"; -/** Text a user gave the model: an `input_text` part, shown as plain text. */ +/** Text a user gave the model: an `input_text` part, rendered as Markdown, its line breaks kept. */ export interface InputTextPart { type: "input_text"; text: string; @@ -98,8 +99,47 @@ export interface FunctionCallOutputItem { output: string | readonly InputTextPart[]; } -/** An item the thread shows; an item of any other type is skipped. */ -export type ThreadItem = MessageItem | ReasoningItem | FunctionCallItem | FunctionCallOutputItem; +/** + * A `subagent_result` item: a sub-agent's result, by its display name and its status as text to + * show, with an optional link, its `href` and `label`, and its Markdown `content` or its `error`. + */ +export interface SubagentResultItem { + type: "subagent_result"; + id?: string; + name: string; + status: string; + href?: string; + label?: string; + content?: string; + error?: string; +} + +/** An item the thread shows; an item of any other type, or a sub-agent result malformed, is + * skipped. */ +export type ThreadItem = + MessageItem | ReasoningItem | FunctionCallItem | FunctionCallOutputItem | SubagentResultItem; + +type LineItem = ReasoningItem | FunctionCallItem | FunctionCallOutputItem; + +function text(value: unknown, filled = false): value is string { + return typeof value === "string" && (!filled || value.trim() !== ""); +} + +function optional(value: unknown): value is string | undefined { + return value === undefined || typeof value === "string"; +} + +function wellFormed(item: SubagentResultItem): boolean { + return ( + text(item.name, true) && + text(item.status, true) && + optional(item.id) && + optional(item.href) && + optional(item.label) && + optional(item.content) && + optional(item.error) + ); +} function pretty(text: string): string { const json = tryFormatJson(text); @@ -122,22 +162,30 @@ function end(frame: HTMLElement) { } /** - * Shows a conversation's items in order: a user's text as plain text, the assistant's as rendered - * Markdown, and a refusal as a labelled refusal. A message still in progress reads as streaming, - * and as its text grows it re-renders in place, the items above it untouched; an incomplete or a - * failed message is labelled so. With `verbose` set, reasoning, function calls, and their outputs - * show too, each collapsed in a native details; otherwise they are hidden. A reasoning item's line - * carries its summary after its kind and status, and its details holds its content alone; with a - * summary and no content, the line stands alone, with nothing to expand. Item and part types the - * thread doesn't know are skipped. A word longer than the thread's line breaks to fit, except in a - * Markdown table, whose cells keep their words whole and which scrolls sideways in its own box when - * wider than the thread. Display-only: it sends no event and binds no key. + * Shows a conversation's items in order: a user's text as rendered Markdown with its line breaks + * kept, the assistant's as rendered Markdown, and a refusal as a labelled refusal. A message still + * in progress reads as streaming, and as its text grows it re-renders in place, the items above it + * untouched; an incomplete or a failed message is labelled so. With `verbose` set, reasoning, + * function calls, and their outputs show too, each collapsed in a native details; otherwise they + * are hidden. A reasoning item's line carries its summary after its kind and status, and its + * details holds its content alone; with a summary and no content, the line stands alone, with + * nothing to expand. A sub-agent's result shows in either mode, collapsed in a native details whose + * line reads "Sub-agent", its name, and its status, and which holds its link, then its error or its + * content rendered as Markdown; one whose name or status isn't text, or whose other fields aren't + * text where given, is skipped, and a link to a URL the Markdown wouldn't link is its label alone. + * Item and part types the thread doesn't know are skipped. A word longer than the thread's line + * breaks to fit, except in a Markdown table, whose cells keep their words whole and which scrolls + * sideways in its own box when wider than the thread. Display-only: it sends no event and binds no + * key. * * The items are an ordered list of articles, not a log: order is the thread's meaning, and a list * tells assistive technology how many items there are and where each sits. A log's live region * would announce every word of a streaming reply; a consumer that wants an announcement adds a * status of its own. * + * The children slotted as `after`, such as a form the conversation waits on, sit in the frame after + * the items, so they scroll with them. + * * When its consumer constrains its block size, the frame scrolls, and it follows the newest item, * as the event log does: an update, an item added or a streaming reply's text grown, scrolls the * frame to its end while the reader is at its end, within a pixel or two, so a reader who scrolled @@ -145,12 +193,12 @@ function end(frame: HTMLElement) { * again. A conversation reads from its newest item, so the first items shown open at the end, and a * user's message added to the end, the one the reader just sent, alone or with the reply's first * text, brings the frame to its end wherever the reader was. The last item grown with no update, - * a details the reader opens in it or an image that loads, is followed the same way: while the - * reader is at the frame's end, its end stays in view, and a reader who scrolled up keeps their - * place. Only the last item's growth follows: an item above it grown, a details the reader opens - * there, behaves natively, the summary clicked staying where it was and its content opening below - * it, and leaves the reader short of the end. The scroll is instant, never smooth, under any - * motion preference. + * a details the reader opens in it or an image that loads, and the slotted children added or + * grown, are followed the same way: while the reader is at the frame's end, its end stays in view, + * and a reader who scrolled up keeps their place. Only the last item's growth follows: an item + * above it grown, a details the reader opens there, behaves natively, the summary clicked staying + * where it was and its content opening below it, and leaves the reader short of the end. The + * scroll is instant, never smooth, under any motion preference. * The thread follows only in its own frame: unconstrained, it is as tall as its content and its * consumer's scroll moves it, which the thread never scrolls, so a consumer that wants it followed * holds it to a height. @@ -174,6 +222,8 @@ export class ChatThread extends LitElement { #content: Element | null = null; + #after: Element | null = null; + #last: Element | null = null; #size = 0; @@ -197,6 +247,7 @@ export class ChatThread extends LitElement { const frame = this.renderRoot.querySelector(".frame"); if (!frame) return; this.#content = null; + this.#after = null; this.#observe(frame); this.#seen(frame); } @@ -216,7 +267,7 @@ export class ChatThread extends LitElement { .some((item) => item?.type === "message" && item.role === "user"); this.#follow = (changed.has("items") || changed.has("verbose")) && - (frame === null || before.length === 0 || sent || atEnd(frame)); + (frame === null || before.length === 0 || sent || atEnd(frame) || atEnd(frame, this.#height)); } protected override updated() { @@ -236,18 +287,30 @@ export class ChatThread extends LitElement { } #measured() { - return this.#last?.getBoundingClientRect().height ?? 0; + const height = (element: Element | null) => element?.getBoundingClientRect().height ?? 0; + return height(this.#last) + height(this.#after); } #observe(frame: HTMLElement) { const content = frame.firstElementChild; this.#last = content?.matches("ol") ? content.lastElementChild : content; + const after = frame.lastElementChild; + if (after !== this.#after) { + if (this.#after) this.#resized.unobserve(this.#after); + this.#after = after; + if (after) this.#resized.observe(after); + } if (content === this.#content) return; if (this.#content) this.#resized.unobserve(this.#content); this.#content = content; if (content) this.#resized.observe(content); } + #slotted = (event: Event) => { + const slot = event.target as HTMLSlotElement; + slot.parentElement!.hidden = slot.assignedElements().length === 0; + }; + #status(status: ItemStatus | undefined) { const label = status ? STATUS_LABELS[status] : undefined; if (!label) return nothing; @@ -263,7 +326,7 @@ export class ChatThread extends LitElement { const parts = (item.content ?? []).map((part) => { switch (part?.type) { case "input_text": - return html`

${part.text}

`; + return html`
${markdown(part.text ?? "", { breaks: true })}
`; case "output_text": return html`
${markdown(part.text ?? "")}
`; case "refusal": @@ -283,7 +346,7 @@ export class ChatThread extends LitElement { `; } - #line(item: ThreadItem, kind: string, names: TemplateResult[], described: TemplateResult[]) { + #line(item: LineItem, kind: string, names: TemplateResult[], described: TemplateResult[]) { const status = this.#status(item.status); const parts = [html`${kind}`, ...names]; if (status !== nothing) parts.push(status); @@ -292,7 +355,7 @@ export class ChatThread extends LitElement { } #details( - item: ThreadItem, + item: LineItem, kind: string, names: TemplateResult[], body: unknown, @@ -366,6 +429,32 @@ export class ChatThread extends LitElement { ); } + #result(item: SubagentResultItem) { + const label = item.label?.trim() ? item.label : item.href; + const link = + item.href === undefined + ? nothing + : html``; + const error = item.error?.trim() ? html`

${item.error}

` : nothing; + const content = item.content?.trim() + ? html`
${markdown(item.content)}
` + : nothing; + const empty = + error === nothing && content === nothing + ? html`

No result.

` + : nothing; + return html`
+ Sub-agent ${item.name} ${item.status} +
${link}${error}${content}${empty}
+
`; + } + render() { const names = new Map(); const shown: { key: string; kind: string; view: TemplateResult }[] = []; @@ -389,6 +478,9 @@ export class ChatThread extends LitElement { shown.push({ key, kind: "verbose", view: this.#output(item, names.get(item.call_id)) }); } return; + case "subagent_result": + if (wellFormed(item)) shown.push({ key, kind: "result", view: this.#result(item) }); + return; } }); return html`
@@ -403,6 +495,7 @@ export class ChatThread extends LitElement { ` : html`

No messages yet.

` } +
`; } } diff --git a/src/markdown.ts b/src/markdown.ts index 8e86230..2808a93 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -11,19 +11,36 @@ import { styleMap } from "lit/directives/style-map.js"; type Rendered = TemplateResult | string | typeof nothing | Rendered[]; +/** How `markdown()` reads its source: with `breaks`, each line break in a paragraph is kept. */ +export interface MarkdownOptions { + breaks?: boolean; +} + /** * The source as a template: headings, paragraphs, emphasis, strong, code spans, fenced and * indented code, ordered and unordered lists to any depth, task items, blockquotes, rules, links, - * GFM tables and strikethrough, and line breaks. Raw HTML, block or inline, shows as its own text; - * an image shows its alt text; a link is an anchor only to an http, https, or mailto URL or a - * relative one. Partial source, an unclosed fence or a list still growing, renders what has - * arrived, and rendering a longer source into the same container updates its DOM in place. + * GFM tables and strikethrough, and line breaks, a paragraph's single line break kept too with + * `breaks`. Raw HTML, block or inline, shows as its own text; an image shows its alt text; a link + * is an anchor only to an http, https, or mailto URL or a relative one. Partial source, an + * unclosed fence or a list still growing, renders what has arrived, and rendering a longer source + * into the same container updates its DOM in place. */ -export function markdown(source: string): TemplateResult { - const tokens = Lexer.lex(source, { ...getDefaults(), gfm: true, breaks: false }); +export function markdown(source: string, { breaks = false }: MarkdownOptions = {}): TemplateResult { + const tokens = Lexer.lex(source, { ...getDefaults(), gfm: true, breaks }); return html`${blocks(tokens)}`; } +const schemes = new Set(["http:", "https:", "mailto:"]); + +/** Whether a URL may be an anchor's href: an http, https, or mailto URL, or a relative one. */ +export function linkable(url: string): boolean { + try { + return schemes.has(new URL(url, "https://base.invalid/").protocol); + } catch { + return false; + } +} + function blocks(tokens: Token[]): Rendered[] { return tokens.map(block); } @@ -142,22 +159,12 @@ function generic(token: Token): Rendered { function link({ href, title, tokens, text, autolink }: Tokens.Link): Rendered { const url = autolink ? href : decode(href); const content = autolink ? text : inline(tokens); - if (!safe(url)) return content; + if (!linkable(url)) return content; return html`${content}`; } -const schemes = new Set(["http:", "https:", "mailto:"]); - -function safe(url: string): boolean { - try { - return schemes.has(new URL(url, "https://base.invalid/").protocol); - } catch { - return false; - } -} - function plain(tokens: Token[]): string { return tokens .map((token): string => { diff --git a/test/browser/chat-thread.test.ts b/test/browser/chat-thread.test.ts index af6ffe4..77a73db 100644 --- a/test/browser/chat-thread.test.ts +++ b/test/browser/chat-thread.test.ts @@ -152,17 +152,48 @@ describe("chat thread", { timeout: 60_000 }, () => { assert.deepEqual(view.frame, { tabindex: "0", role: "region", label: "Conversation" }); }); - test("a user's input_text is plain text, labelled User, its line breaks kept", async () => { - const view = await shown({ items: [user("# not a heading\n**not bold**")] }); + test("a user's input_text renders as Markdown, labelled User, its line breaks kept", async () => { + const view = await shown({ + items: [user("Run `mise run check`, then:\n\n- **one**\n- two\n\nline one\nline two")], + }); assert.equal(view.list, "ol"); assert.equal(view.items.length, 1); const [item] = view.items; assert.deepEqual([item.kind, item.element, item.label], ["user", "article", "User"]); - assert.deepEqual(item.plain, ["# not a heading\n**not bold**"]); - assert.equal(item.markdown, null); + assert.equal( + item.markdown, + "

Run mise run check, then:

" + + "
  • one
  • two
" + + "

line one
line two

", + ); + assert.deepEqual(item.plain, []); assert.equal(item.status, null); }); + test("a user's raw HTML shows as its text, and an assistant's single line break doesn't break", async () => { + const view: { elements: number; text: string; answer: string } = + await page.evaluate(`(async () => { + const thread = document.createElement("sl-chat-thread"); + thread.items = [ + { type: "message", role: "user", content: [{ type: "input_text", + text: 'bold\\nnext' }] }, + { type: "message", id: "m", role: "assistant", status: "completed", + content: [{ type: "output_text", text: "line one\\nline two" }] }, + ]; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + const [asked, answered] = thread.shadowRoot.querySelectorAll(".markdown"); + return { + elements: asked.querySelectorAll("img, b").length, + text: asked.textContent, + answer: answered.innerHTML.replace(//g, ""), + }; + })()`); + assert.equal(view.elements, 0); + assert.equal(view.text, 'boldnext'); + assert.equal(view.answer, "

line one\nline two

"); + }); + test("an assistant's output_text renders as Markdown, labelled Assistant", async () => { const view = await shown({ items: [assistant("msg_1", "# Title\n\n- **one**\n- [two](https://example.com)")], @@ -606,9 +637,9 @@ describe("chat thread", { timeout: 60_000 }, () => { assert.deepEqual( view.view.items.map(({ kind, plain, markdown }) => [kind, plain, markdown]), [ - ["user", ["one"], null], + ["user", [], "

one

"], ["assistant", [], "

two

"], - ["user", ["three"], null], + ["user", [], "

three

"], ], ); }); @@ -707,6 +738,161 @@ describe("chat thread", { timeout: 60_000 }, () => { }); }); + const result = (fields: Record = {}) => ({ + type: "subagent_result", + id: "sr_1", + name: "harbor-review", + status: "finished", + href: "/contexts/harbor/items/an_1", + label: "Harbor review", + content: "The harbor's **two** contexts agree.\n\nraw", + ...fields, + }); + + test("a sub-agent's result is a collapsed line, Sub-agent, its name, and its status, in either mode", async () => { + for (const verbose of [false, true]) { + const view = await shown({ items: [user("Review the harbor."), result()], verbose }); + const [, item] = view.items; + assert.deepEqual( + [item.kind, item.element, item.label, item.names, item.open, item.line], + [ + "result", + "details", + "Sub-agent", + ["harbor-review"], + false, + "Sub-agent harbor-review finished", + ], + `verbose ${verbose}`, + ); + } + const separator: string = await page.evaluate(`getComputedStyle( + document.querySelector("sl-chat-thread").shadowRoot.querySelector(".outcome"), "::before").content`); + assert.equal(separator, '"·\u00a0" / ""'); + }); + + test("a sub-agent's result line is named, in the accessibility tree, for its kind, its name, and its status", async () => { + await shown({ items: [result(), result({ id: "sr_2", status: "failed" })] }); + const { nodes }: { nodes: AXNode[] } = await page.cdp("Accessibility.getFullAXTree", {}); + const names = nodes + .filter((node) => !node.ignored && node.role?.value === "DisclosureTriangle") + .map((node) => node.name?.value ?? ""); + assert.deepEqual(names, ["Sub-agent harbor-review finished", "Sub-agent harbor-review failed"]); + }); + + test("a sub-agent's result holds its link, then its content as Markdown, its raw HTML as text", async () => { + const view: { link: string; href: string | null; markdown: string; elements: number } = + await page.evaluate(`(async () => { + const thread = document.createElement("sl-chat-thread"); + thread.items = [${JSON.stringify(result())}]; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + const content = thread.shadowRoot.querySelector("details > .content"); + const markdown = content.querySelector(".markdown"); + return { + link: content.firstElementChild.outerHTML.replace(//g, ""), + href: content.querySelector("a")?.getAttribute("href") ?? null, + markdown: markdown.innerHTML.replace(//g, ""), + elements: markdown.querySelectorAll("b").length, + }; + })()`); + assert.equal( + view.link, + '', + ); + assert.equal( + view.markdown, + "

The harbor's two contexts agree.

<b>raw</b>

", + ); + assert.equal(view.elements, 0); + }); + + test("a sub-agent's error shows as its text; with no content or error it says so; a link the Markdown wouldn't make is its label", async () => { + const view = await page.evaluate(`(async () => { + const thread = document.createElement("sl-chat-thread"); + thread.items = [ + ${JSON.stringify(result({ id: "sr_e", status: "failed", content: undefined, error: "The target is gone." }))}, + ${JSON.stringify(result({ id: "sr_n", href: undefined, label: undefined, content: "" }))}, + ${JSON.stringify(result({ id: "sr_j", href: "javascript:alert(1)" }))}, + ${JSON.stringify(result({ id: "sr_u", label: "" }))}, + ]; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + return [...thread.shadowRoot.querySelectorAll("details > .content")].map((content) => ({ + line: content.previousElementSibling.textContent.replace(/\\s+/g, " ").trim(), + anchors: content.querySelectorAll("a").length, + link: content.querySelector(".link")?.textContent ?? null, + error: content.querySelector(".error")?.textContent ?? null, + markdown: content.querySelector(".markdown") !== null, + empty: content.querySelector(".empty")?.textContent ?? null, + })); + })()`); + assert.deepEqual(view, [ + { + line: "Sub-agent harbor-review failed", + anchors: 1, + link: "Harbor review", + error: "The target is gone.", + markdown: false, + empty: null, + }, + { + line: "Sub-agent harbor-review finished", + anchors: 0, + link: null, + error: null, + markdown: false, + empty: "No result.", + }, + { + line: "Sub-agent harbor-review finished", + anchors: 0, + link: "Harbor review", + error: null, + markdown: true, + empty: null, + }, + { + line: "Sub-agent harbor-review finished", + anchors: 1, + link: "/contexts/harbor/items/an_1", + error: null, + markdown: true, + empty: null, + }, + ]); + }); + + test("a sub-agent's result whose name or status isn't text, or another field not text, is skipped, with no error", async () => { + const malformed = [ + result({ name: undefined }), + result({ name: " " }), + result({ status: 2 }), + result({ status: "" }), + result({ href: 1 }), + result({ label: {} }), + result({ content: ["text"] }), + result({ error: true }), + result({ id: 7 }), + ]; + const view: { errors: string[]; view: View } = await page.evaluate(`(async () => { + const errors = []; + const onError = (event) => errors.push(String(event.message)); + window.addEventListener("error", onError); + const thread = document.createElement("sl-chat-thread"); + thread.items = [...${JSON.stringify(malformed)}, ${JSON.stringify(result({ id: "sr_ok" }))}]; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + window.removeEventListener("error", onError); + return { errors, view: window.read(thread) }; + })()`); + assert.deepEqual(view.errors, []); + assert.deepEqual( + view.view.items.map(({ kind, line }) => [kind, line]), + [["result", "Sub-agent harbor-review finished"]], + ); + }); + const followed = async ( steps: { items: unknown[]; scroll?: "up" | "end"; verbose?: boolean }[], ): Promise<(Where & { scrolled: number | null })[]> => { @@ -1013,6 +1199,161 @@ describe("chat thread", { timeout: 60_000 }, () => { assert.equal(result.settled, result.reattached, "and keeps the place it reattached at"); }); + const slotted = async (script: string): Promise> => + page.evaluate(`(async () => { + const frames = () => new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve))); + const thread = document.createElement("sl-chat-thread"); + thread.style.blockSize = "10rem"; + thread.items = ${JSON.stringify(turns(4))}; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + await frames(); + const frame = thread.shadowRoot.querySelector(".frame"); + const after = frame.querySelector(".after"); + const where = () => ({ + top: Math.round(frame.scrollTop), + end: Math.round(frame.scrollHeight - frame.clientHeight), + }); + const form = Object.assign(document.createElement("form"), { slot: "after" }); + form.style.blockSize = "3rem"; + ${script} + })()`); + + test("the after slot's children sit in the frame after the items and scroll with them; empty, it takes no room", async () => { + const view = await slotted(` + const empty = { hidden: after.hidden, height: after.getBoundingClientRect().height, ...where() }; + thread.append(form); + await frames(); + const last = frame.querySelector("ol > li:last-child").getBoundingClientRect(); + const placed = form.getBoundingClientRect(); + return { + empty, + filled: { hidden: after.hidden, ...where() }, + inFrame: form.assignedSlot?.closest(".frame") === frame, + below: placed.top >= last.bottom, + grew: Math.round(placed.height), + }; + `); + const { empty, filled, inFrame, below, grew } = view as { + empty: { hidden: boolean; height: number } & Where; + filled: { hidden: boolean } & Where; + inFrame: boolean; + below: boolean; + grew: number; + }; + assert.deepEqual([empty.hidden, empty.height], [true, 0], "empty, the slot takes no room"); + assert.equal(empty.top, empty.end, "at its end"); + assert.equal(filled.hidden, false); + assert.ok(inFrame, "the slotted form is in the frame"); + assert.ok(below, "after the last item"); + assert.ok( + filled.end >= empty.end + grew, + `the form adds to the scroll: ${JSON.stringify(view)}`, + ); + assert.equal(filled.top, filled.end, "the frame followed it to its end"); + }); + + test("held at its end, the slotted children growing keep the end in view; scrolled up, the reader keeps their place", async () => { + const view = (await slotted(` + thread.append(form); + await frames(); + form.style.blockSize = "6rem"; + await frames(); + const grown = where(); + frame.scrollTop -= 40; + await frames(); + const up = where(); + form.style.blockSize = "9rem"; + await frames(); + const kept = where(); + frame.scrollTop = frame.scrollHeight; + await frames(); + form.style.blockSize = "12rem"; + await frames(); + return { places: [grown, up, kept, where()] }; + `)) as { places: Where[] }; + const [grown, up, kept, again] = view.places; + assert.equal(grown.top, grown.end, "grown at its end, the frame follows"); + assert.ok(up.top < up.end, `scrolled up: ${JSON.stringify(up)}`); + assert.ok(kept.end > up.end, "the form grew the scroll"); + assert.equal(kept.top, up.top, "and the reader's place is kept"); + assert.ok(again.end > kept.end, "back at the end, the form grew again"); + assert.equal(again.top, again.end, "and the frame follows again"); + }); + + test("a delta arriving as the slotted children grow, before the growth is followed, goes on following", async () => { + const view = (await slotted(` + thread.append(form); + await frames(); + const places = []; + for (let count = 1; count <= 8; count++) { + form.style.blockSize = (3 + count) + "rem"; + thread.items = [...thread.items.slice(0, 8), { + type: "message", id: "msg_s", role: "assistant", status: "in_progress", + content: [{ type: "output_text", text: "A streamed word. ".repeat(count * 4) }], + }]; + await thread.updateComplete; + await frames(); + places.push(where()); + } + return { places }; + `)) as { places: Where[] }; + for (const [index, { top, end }] of view.places.entries()) { + assert.equal(top, end, `delta ${index}: at its end`); + } + }); + + const streamedFast = async (up: boolean): Promise<{ places: Where[]; left: number }> => + page.evaluate(`(async () => { + const thread = document.createElement("sl-chat-thread"); + thread.style.blockSize = "10rem"; + const history = ${JSON.stringify([...turns(4), user("How did the run go?")])}; + thread.items = history; + document.querySelector("main").replaceChildren(thread); + await thread.updateComplete; + const frame = thread.shadowRoot.querySelector(".frame"); + const places = []; + let left = -1; + const words = ${JSON.stringify(words)}; + for (let count = 1; count <= 40; count++) { + if (${up} && count === 10) { + frame.scrollTop -= 60; + left = Math.round(frame.scrollTop); + } + const text = Array.from({ length: count }, (_, index) => words[index % words.length]).join(" "); + thread.items = [...history, { type: "message", id: "msg_f", role: "assistant", + status: "in_progress", content: [{ type: "output_text", text }] }]; + await new Promise((resolve) => setTimeout(resolve, 0)); + if (count % 10 === 0) { + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + places.push({ + top: Math.round(frame.scrollTop), + end: Math.round(frame.scrollHeight - frame.clientHeight), + }); + } + } + return { places, left }; + })()`); + + test("held, the thread follows a reply streamed in deltas faster than frames", async () => { + const { places } = await streamedFast(false); + for (const [index, { top, end }] of places.entries()) { + assert.equal(top, end, `after ${(index + 1) * 10} deltas: at its end`); + } + assert.ok(places.at(-1)!.end > places[0].end, "the reply grew the scroll"); + }); + + test("scrolled up by the reader as deltas stream in faster than frames, the thread keeps their place", async () => { + const { places, left } = await streamedFast(true); + const [, ...after] = places; + assert.ok(left >= 0 && left < places[0].end, `scrolled up to ${left}`); + for (const [index, { top, end }] of after.entries()) { + assert.equal(top, left, `after ${(index + 2) * 10} deltas: the place kept`); + assert.ok(end > top, "short of the end"); + } + }); + test("not held, the thread is as tall as its content and scrolls no container it doesn't own", async () => { const scrolled: { frame: Where; pane: Where }[] = await page.evaluate(`(async () => { const pane = document.createElement("div"); diff --git a/test/browser/components.test.ts b/test/browser/components.test.ts index f67e8e7..2c996dd 100644 --- a/test/browser/components.test.ts +++ b/test/browser/components.test.ts @@ -1495,7 +1495,7 @@ describe("components", { timeout: 60_000 }, () => { return rect.left < box.left - 0.5 || rect.right > box.right + 0.5; }) .map((part) => part.localName + "." + part.className), - broken: [...root.querySelectorAll(".id, .name, .kind, .role, .status, .markdown code:not(pre code)")] + broken: [...root.querySelectorAll(".id, .name, .kind, .role, .status, .outcome, .markdown code:not(pre code)")] .filter((part) => lines(part) > 1 && !(part.matches(".id, .name") && fills(part))) .map((part) => part.textContent), wrapped: [...root.querySelectorAll(".id, .name")] @@ -1522,8 +1522,8 @@ describe("components", { timeout: 60_000 }, () => { assert.ok(overflow <= 0, `${profile}: the states overflow the column by ${overflow}`); assert.equal( shown.length, - 66, - `${profile}: 31 states twice, the three fits, and the focus state`, + 80, + `${profile}: 38 states twice, the three fits, and the focus state`, ); const wrapped = (narrow: boolean) => shown.filter((thread) => thread.narrow === narrow).flatMap((thread) => thread.wrapped); @@ -1534,8 +1534,8 @@ describe("components", { timeout: 60_000 }, () => { ); assert.equal( shown.filter(({ held }) => held).length, - 9, - `${profile}: the long content and the two streamed, twice each in the states and at 20rem, and the long content once focused`, + 11, + `${profile}: the long content, the two streamed, and the slotted form, twice each in the states and at 20rem, and the long content once focused`, ); for (const [ index, diff --git a/test/browser/markdown.test.ts b/test/browser/markdown.test.ts index d75b70f..07e7aab 100644 --- a/test/browser/markdown.test.ts +++ b/test/browser/markdown.test.ts @@ -20,10 +20,11 @@ describe("markdown", { timeout: 60_000 }, () => { page = await browser.open(`${server.origin}/test/fixtures/components.html`); await page.evaluate(`window.verdict.then(async () => { const { render } = await import("lit"); - const { markdown } = await import("/dist/markdown.js"); - window.rendered = (source) => { + const { linkable, markdown } = await import("/dist/markdown.js"); + window.linkable = linkable; + window.rendered = (source, options) => { const container = document.createElement("div"); - render(markdown(source), container); + render(markdown(source, options), container); return container.innerHTML.replace(//g, ""); }; })`); @@ -201,6 +202,33 @@ describe("markdown", { timeout: 60_000 }, () => { }); } + test("with breaks, a paragraph's single line break is kept, as a br; without, it isn't", async () => { + const source = "one\ntwo\n\n- three\n four"; + assert.equal( + await page.evaluate(`window.rendered(${JSON.stringify(source)}, { breaks: true })`), + "

one
two

  • three
    four
", + ); + assert.equal(await rendered(source), "

one\ntwo

  • three\nfour
"); + }); + + test("linkable admits the URLs a link is an anchor to, and refuses the rest", async () => { + const urls = { + "https://example.com": true, + "HTTP://example.com": true, + "mailto:me@example.com": true, + "/docs/x.md": true, + "#part": true, + "javascript:alert(1)": false, + " javascript:alert(1)": false, + "data:text/html,x": false, + "custom:thing": false, + }; + const admitted: boolean[] = await page.evaluate( + `${JSON.stringify(Object.keys(urls))}.map((url) => window.linkable(url))`, + ); + assert.deepEqual(admitted, Object.values(urls)); + }); + test("renders an autolink to a refused scheme as its text", async () => { assert.equal(await rendered(""), "

javascript:alert(1)

"); }); From de9ccd3087b95fc0bd92943e752e014ffb6028fd Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 1 Dec 2026 08:06:30 -0500 Subject: [PATCH 6/7] Standards review: sub-agent result validation, logical padding, doc comments A sub-agent result's blank href is no link, as a blank label, error, or content is none (validation-first), with its test case; the after slot's box takes logical padding; the name/status check is one filled() helper; ThreadItem's doc comment is a well-formed block and ChatThread's says name and status must be non-empty; the CHANGELOG's Changed list is one list. --- CHANGELOG.md | 1 - docs/components.md | 6 +++--- src/chat-thread.css | 3 ++- src/chat-thread.ts | 36 ++++++++++++++++---------------- test/browser/chat-thread.test.ts | 11 +++++++++- 5 files changed, 33 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0c4050..6cba4fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,6 @@ All notable changes to `@standards-lab/web-components` are documented here. The - `sl-chat-thread` renders a user's `input_text` as Markdown with its line breaks kept, HTML shown as its text, where it showed plain text; the assistant's Markdown still joins a paragraph's lines. - - The repository's tooling takes marathon 0.25.0, pnpm 12.23.0, typescript-eslint 8.74.0, chrome-headless-shell 158.0.8127.88, `@types/node` 26.6.11, ESLint 10.16.0, eslint-plugin-boundaries 7.4.5, and jdx/mise-action v5.4.0. diff --git a/docs/components.md b/docs/components.md index d107330..6a1296e 100644 --- a/docs/components.md +++ b/docs/components.md @@ -148,9 +148,9 @@ the tests measure as they do. output that are valid JSON formatted from their own tokens by the foundation's `format.js`. A `subagent_result` item, the thread's own, `{type, id?, name, status, href?, label?, content?, error?}`, shows in either mode as a collapsed line, "Sub-agent", its name, and its status as - given, holding its link, `label` or else `href`, then its error or its Markdown content; one - whose name or status isn't non-empty text, or whose other fields aren't text where given, is - skipped. Children slotted as `after`, such as a form the conversation waits on, sit in the frame + given, holding its link, `label` or else `href`, and none for a blank `href`, then its error or + its Markdown content; one whose name or status isn't non-empty text, or whose other fields + aren't text where given, is skipped. Children slotted as `after`, such as a form the conversation waits on, sit in the frame after the items and scroll with them. A thread its consumer holds to a height scrolls inside, opening at its end and following the newest item, its last item's growth, and the slotted children's, only from its end or on a user's message; unheld, it is as tall as its content and diff --git a/src/chat-thread.css b/src/chat-thread.css index 5d2af93..5d943c0 100644 --- a/src/chat-thread.css +++ b/src/chat-thread.css @@ -140,5 +140,6 @@ summary, color: var(--fg-2); } .after { - padding: 0 var(--space-s) var(--space-s); + padding-inline: var(--space-s); + padding-block-end: var(--space-s); } diff --git a/src/chat-thread.ts b/src/chat-thread.ts index ade174b..fa70cf5 100644 --- a/src/chat-thread.ts +++ b/src/chat-thread.ts @@ -114,15 +114,16 @@ export interface SubagentResultItem { error?: string; } -/** An item the thread shows; an item of any other type, or a sub-agent result malformed, is - * skipped. */ +/** + * An item the thread shows; an item of any other type, or a malformed sub-agent result, is skipped. + */ export type ThreadItem = MessageItem | ReasoningItem | FunctionCallItem | FunctionCallOutputItem | SubagentResultItem; type LineItem = ReasoningItem | FunctionCallItem | FunctionCallOutputItem; -function text(value: unknown, filled = false): value is string { - return typeof value === "string" && (!filled || value.trim() !== ""); +function filled(value: unknown): value is string { + return typeof value === "string" && value.trim() !== ""; } function optional(value: unknown): value is string | undefined { @@ -131,8 +132,8 @@ function optional(value: unknown): value is string | undefined { function wellFormed(item: SubagentResultItem): boolean { return ( - text(item.name, true) && - text(item.status, true) && + filled(item.name) && + filled(item.status) && optional(item.id) && optional(item.href) && optional(item.label) && @@ -171,12 +172,12 @@ function end(frame: HTMLElement) { * details holds its content alone; with a summary and no content, the line stands alone, with * nothing to expand. A sub-agent's result shows in either mode, collapsed in a native details whose * line reads "Sub-agent", its name, and its status, and which holds its link, then its error or its - * content rendered as Markdown; one whose name or status isn't text, or whose other fields aren't - * text where given, is skipped, and a link to a URL the Markdown wouldn't link is its label alone. - * Item and part types the thread doesn't know are skipped. A word longer than the thread's line - * breaks to fit, except in a Markdown table, whose cells keep their words whole and which scrolls - * sideways in its own box when wider than the thread. Display-only: it sends no event and binds no - * key. + * content rendered as Markdown; one whose name or status isn't non-empty text, or whose other + * fields aren't text where given, is skipped; a blank link is none, and a link to a URL the + * Markdown wouldn't link is its label alone. Item and part types the thread doesn't know are + * skipped. A word longer than the thread's line breaks to fit, except in a Markdown table, whose + * cells keep their words whole and which scrolls sideways in its own box when wider than the + * thread. Display-only: it sends no event and binds no key. * * The items are an ordered list of articles, not a log: order is the thread's meaning, and a list * tells assistive technology how many items there are and where each sits. A log's live region @@ -431,12 +432,11 @@ export class ChatThread extends LitElement { #result(item: SubagentResultItem) { const label = item.label?.trim() ? item.label : item.href; - const link = - item.href === undefined - ? nothing - : html``; + const link = item.href?.trim() + ? html`` + : nothing; const error = item.error?.trim() ? html`

${item.error}

` : nothing; const content = item.content?.trim() ? html`
${markdown(item.content)}
` diff --git a/test/browser/chat-thread.test.ts b/test/browser/chat-thread.test.ts index 77a73db..202387d 100644 --- a/test/browser/chat-thread.test.ts +++ b/test/browser/chat-thread.test.ts @@ -807,7 +807,7 @@ describe("chat thread", { timeout: 60_000 }, () => { assert.equal(view.elements, 0); }); - test("a sub-agent's error shows as its text; with no content or error it says so; a link the Markdown wouldn't make is its label", async () => { + test("a sub-agent's error shows as its text; with no content or error it says so; a link the Markdown wouldn't make is its label; a blank href is no link", async () => { const view = await page.evaluate(`(async () => { const thread = document.createElement("sl-chat-thread"); thread.items = [ @@ -815,6 +815,7 @@ describe("chat thread", { timeout: 60_000 }, () => { ${JSON.stringify(result({ id: "sr_n", href: undefined, label: undefined, content: "" }))}, ${JSON.stringify(result({ id: "sr_j", href: "javascript:alert(1)" }))}, ${JSON.stringify(result({ id: "sr_u", label: "" }))}, + ${JSON.stringify(result({ id: "sr_b", href: " ", label: "" }))}, ]; document.querySelector("main").replaceChildren(thread); await thread.updateComplete; @@ -860,6 +861,14 @@ describe("chat thread", { timeout: 60_000 }, () => { markdown: true, empty: null, }, + { + line: "Sub-agent harbor-review finished", + anchors: 0, + link: null, + error: null, + markdown: true, + empty: null, + }, ]); }); From 399768268b66ecc67f00e21188496f8cf7729aed Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 1 Dec 2026 08:20:24 -0500 Subject: [PATCH 7/7] Editor pass: the thread's slot, result item, and user Markdown docs --- docs/components.md | 13 +++++++------ docs/internals.md | 22 ++++++++++++---------- docs/layout.md | 4 ++-- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/docs/components.md b/docs/components.md index 6a1296e..7e8dbac 100644 --- a/docs/components.md +++ b/docs/components.md @@ -146,12 +146,13 @@ the tests measure as they do. `verbose`, reasoning, function calls, and their outputs too, each collapsed in a native details, a reasoning item's summary on its line and its content inside, and a call's arguments and its output that are valid JSON formatted from their own tokens by the foundation's `format.js`. A - `subagent_result` item, the thread's own, `{type, id?, name, status, href?, label?, content?, - error?}`, shows in either mode as a collapsed line, "Sub-agent", its name, and its status as - given, holding its link, `label` or else `href`, and none for a blank `href`, then its error or - its Markdown content; one whose name or status isn't non-empty text, or whose other fields - aren't text where given, is skipped. Children slotted as `after`, such as a form the conversation waits on, sit in the frame - after the items and scroll with them. A thread its consumer holds to a height scrolls inside, + `subagent_result` item, which the thread adds to Open Responses, `{type, id?, name, status, + href?, label?, content?, error?}`, shows in either mode as a collapsed line, "Sub-agent", its + name, and its status as given, holding its link, `label` or else `href`, and none for a blank + `href`, then its error or its Markdown content; one whose name or status isn't non-empty text, + or whose other fields aren't text where given, is skipped. Children slotted as `after`, such as + a form the conversation waits on, sit in the frame after the items and scroll with them. A + thread its consumer holds to a height scrolls inside, opening at its end and following the newest item, its last item's growth, and the slotted children's, only from its end or on a user's message; unheld, it is as tall as its content and follows nothing, so a consumer that wants it followed holds it. It exports its item types and diff --git a/docs/internals.md b/docs/internals.md index ac46799..b02376c 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -48,10 +48,11 @@ each sheet is laid out as it is. - An update follows the newest item when the frame was at its end before it, showed no items yet, or the update adds a user's message, the newest or the one before the reply's first text when the - consumer adds both at once. At its end is measured against the scroll height now and the one last - seen, either: content grown since the last update, the slotted children or an image, that the - observer hasn't yet followed, would otherwise leave a delta arriving before its callback reading - the reader as scrolled up, and the follow would stop. + consumer adds both at once. The frame is at its end when it is at the end of either the scroll + height now or the one last seen. Measured against the height now alone, content that grew since + the last update and that the observer hasn't followed yet, such as the slotted children or an + image, would make a delta arriving before the observer's callback read the reader as scrolled + up, and the thread would stop following. - The last item growing with no update, a details opened in it or an image that loads, is watched by a `ResizeObserver` on the frame's content rather than the details' `toggle` event: it sees every cause and leaves the details toggling natively. Its callback runs after layout, so the reader's @@ -60,15 +61,16 @@ each sheet is laid out as it is. reader short of the new end, measures the next growth of the last item against the end as it now is. The scroll leaves the content's size alone, so it never loops the observer. - The `after` slot sits in a box of its own after the list, which the same observer watches, and - the growth it follows is the last item's and that box's together. The box is hidden while no - element is assigned, set on `slotchange` rather than rendered, so its padding takes no room and - its first child shows through the observer, followed as any growth is. + the growth it follows is the last item's and that box's together. The thread hides the box while + no element is assigned to the slot, setting `hidden` on `slotchange` rather than in its render, + so an empty box's padding takes no room and the first child slotted reaches the observer as a + growth it follows. - Connected again, the frame is measured and observed anew, so the observer's first callback finds the content as the reader does and scrolls nothing on its own. Detached, the frame has no layout to follow or measure. -- A sub-agent result is checked before it renders: its name and status must be non-empty text, and - its id, link, label, content, and error text where given, or it is skipped as an unknown item is. - Its status is text to show, not an `ItemStatus`, so an app passes its own states through. +- A sub-agent result is checked before it renders, and one that fails the check + ([Components](components.md#conversation)) is skipped as an unknown item is. Its status is text + to show, not an `ItemStatus`, so an app passes its own states through. - A reasoning item's summary parts join into one run; a part with no text yet, as one just begun streaming, is no summary. The standalone line puts no whitespace before its kind, which would widen it past the summaries' marker. diff --git a/docs/layout.md b/docs/layout.md index 1784153..042dc67 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -98,8 +98,8 @@ layout each one promises. - A user's message sits at the inline end, short of the full width, on the first elevated surface; the assistant's spans the list. Neither has a border: the thread's frame is the one. A user's - Markdown renders in the bubble as an answer's does, a single paragraph the one the plain text - was, so the bubble keeps its layout. + Markdown renders in the bubble as an answer's does, and a message of one paragraph renders as + its plain text did, so the bubble keeps its layout. - A reasoning item with nothing to expand is a paragraph whose gutter is an inline list item with the summaries' own disclosure marker, undrawn, so its kind lines up with theirs. The gutter is hidden from the accessibility tree, so no marker is read for a disclosure that isn't one.