Compare commits

..
2 Commits
Author SHA1 Message Date
Mohamed Boudra 57bdc689cc chore(release): cut 0.18.1 2026-11-27 18:09:29 +01:00
Mohamed Boudra 062fd4d5a9 docs: prepare v0.18.1 changelog 2026-11-27 18:04:26 +01:00
35 changed files with 124 additions and 1023 deletions
-1
View File
@@ -15,7 +15,6 @@
"*.lock",
"**/*.gen.ts",
"**/*.gen.tsx",
"**/*.icon/**",
"packages/react-native-enriched-markdown/**"
]
}
+1 -27
View File
@@ -1,6 +1,6 @@
# Brand assets
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets for the icons across the app, desktop client, website, docs, and Hub.
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
## Brand architecture
@@ -37,10 +37,6 @@ All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink h
```text
assets/brand/
build.mjs Regenerates all marks and lockups
build-app-icons.mjs Regenerates the desktop and mobile app icons
app-icons/
paseo-lit.png
paseo-dev-lit.png
fonts/
PlusJakartaSans-SemiBold.ttf
OFL.txt
@@ -65,25 +61,3 @@ assets/brand/
```sh
node assets/brand/build.mjs
```
## App icons
`build-app-icons.mjs` renders every desktop and mobile app icon from `marks/paseo-white.svg`: the white butterfly on a black tile, and a blueprint tile for desktop development builds. Regenerate them after changing the butterfly:
```sh
node assets/brand/build-app-icons.mjs
```
The icons that ship are flat. Each platform masks and lights its own icons, so lit artwork ends up lit twice. `app-icons/` keeps a lit version of the two desktop icons, a baked approximation of macOS Liquid Glass. Nothing uses them.
The packaged Mac app takes its icon from `packages/desktop/assets/icon.icon`, an Icon Composer document the script also writes. macOS draws Liquid Glass on it and derives the dark, tinted, and clear variants. electron-builder compiles the document with `actool`, so packaging the Mac app needs Xcode 26 or later. The Nix build has no Xcode and uses `icon.icns`.
To see what macOS draws from the document without packaging the app, export it with Icon Composer's command line tool on a Mac:
```sh
"/Applications/Xcode.app/Contents/Applications/Icon Composer.app/Contents/Executables/ictool" \
packages/desktop/assets/icon.icon --export-image --output-file icon.png \
--platform macOS --rendition Default --width 1024 --height 1024 --scale 1
```
`--rendition` also takes `Dark`, `TintedLight`, `TintedDark`, `ClearLight`, and `ClearDark`.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

-464
View File
@@ -1,464 +0,0 @@
// Generates every Paseo app icon from the canonical butterfly mark.
//
// node assets/brand/build-app-icons.mjs
//
// The artwork is the white butterfly on a black tile. A desktop development build gets the same
// tile drawn as a blueprint, so it is never mistaken for an installed app.
//
// The icons that ship are flat. Each platform masks and lights its own icons, and artwork that
// arrives already lit ends up lit twice. The lit finish is a baked approximation of the Liquid
// Glass material macOS draws for Icon Composer icons. It is written to app-icons/ so it stays
// available, and nothing consumes it.
//
// A packaged Mac app gets its icon from the Icon Composer document in the desktop assets, which
// macOS masks and lights itself. macOS draws a dev build's Dock icon and an .icns exactly as
// supplied, so those carry the system's tile in the artwork. Its geometry is measured from the icon
// macOS 27 draws for that document: the tile covers 824 of the 1024 canvas pixels and its corners
// are continuous curves with a radius of 26.4% of the tile.
//
// sharp is not a declared dependency. It resolves from the workspace root, the way opentype.js
// does for build.mjs.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";
const brandDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(brandDir, "../..");
const brandMarkPath = path.join(brandDir, "marks/paseo-white.svg");
const CANVAS = 1024;
const MACOS_TILE_ON_CANVAS = 824 / CANVAS;
// Windows and Linux have no icon grid, and a tile with the macOS margin looks small next to their
// other icons.
const WINDOWS_LINUX_TILE_ON_CANVAS = 928 / CANVAS;
// Artwork is drawn in the brand mark's own 700-unit box, which the tile fills.
const TILE = 700;
const TILE_RADIUS = 185;
const MARK_INK = 527;
// Scaled down, the mark keeps clear of the tile's corners and covers as much of the tile as the
// glyphs in Apple's icons do.
const MARK_SCALE = 0.9;
const MARK_INK_ON_TILE = (MARK_INK * MARK_SCALE) / TILE;
// Android shows the middle 72 of an adaptive icon's 108 units.
const ANDROID_ADAPTIVE_VISIBLE = 72 / 108;
const NOTIFICATION_MARK_INK = 0.75;
// Apple's continuous corner. Each pair is a distance back along the incoming edge and a distance
// along the outgoing edge, in units of the corner radius.
const CORNER_SEGMENTS = [
["C", [1.08849296, 0], [0.86840694, 0], [0.66993427, 0.065496]],
["L", [0.63149399, 0.074911]],
["C", [0.37282392, 0.16905899], [0.16905899, 0.37282392], [0.074911, 0.63149399]],
["L", [0.065496, 0.66993427]],
["C", [0, 0.86840694], [0, 1.08849296], [0, 1.52866483]],
];
const CORNER_START = [1.52866483, 0];
function continuousSquarePath(inset) {
const near = inset;
const far = TILE - inset;
const radius = TILE_RADIUS - inset;
const corners = [
{ at: [far, near], incoming: [1, 0], outgoing: [0, 1] },
{ at: [far, far], incoming: [0, 1], outgoing: [-1, 0] },
{ at: [near, far], incoming: [-1, 0], outgoing: [0, -1] },
{ at: [near, near], incoming: [0, -1], outgoing: [1, 0] },
];
const commands = corners.map(({ at, incoming, outgoing }, cornerIndex) => {
const point = ([back, along]) =>
[0, 1]
.map((axis) => at[axis] - incoming[axis] * back * radius + outgoing[axis] * along * radius)
.map((value) => Number(value.toFixed(2)))
.join(" ");
const segments = CORNER_SEGMENTS.map(
([command, ...points]) => `${command}${points.map(point).join(" ")}`,
);
return `${cornerIndex === 0 ? "M" : "L"}${point(CORNER_START)}${segments.join("")}`;
});
return `${commands.join("")}Z`;
}
const TILE_SHAPE = `<path d="${continuousSquarePath(0)}" />`;
const FILL_TILE = `<rect width="${TILE}" height="${TILE}" fill="url(#surface)" />`;
const PRODUCTION = {
flat: {
defs: `<linearGradient id="surface"><stop stop-color="#000000" /></linearGradient>`,
surface: FILL_TILE,
},
lit: {
defs: `
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#202022" />
<stop offset="1" stop-color="#0E0E10" />
</linearGradient>`,
surface: FILL_TILE,
tileEdge: { color: "#000000", opacity: 0.75 },
markEdge: { color: "#4A5568", opacity: 0.45 },
markShadow: { color: "#000000", opacity: 0.5 },
},
};
const GRID_DIVISIONS = 8;
const GRID_MAJOR_EVERY = 2;
const OUTLINE_INSET = 28;
function gridLines(isIncluded) {
const step = TILE / GRID_DIVISIONS;
const segments = [];
for (let index = 1; index < GRID_DIVISIONS; index += 1) {
if (!isIncluded(index)) continue;
const at = index * step;
segments.push(`M${at} 0V${TILE}`, `M0 ${at}H${TILE}`);
}
return segments.join("");
}
const isMajorLine = (index) => index % GRID_MAJOR_EVERY === 0;
const BLUEPRINT_SHEET = {
defs: `
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#05C2FE" />
<stop offset="0.5" stop-color="#0191FD" />
<stop offset="1" stop-color="#026CFA" />
</linearGradient>`,
surface: `
${FILL_TILE}
<g fill="none" stroke="#FFFFFF">
<path d="${gridLines((index) => !isMajorLine(index))}" stroke-opacity="0.16" stroke-width="1.5" />
<path d="${gridLines(isMajorLine)}" stroke-opacity="0.34" stroke-width="2" />
<circle cx="${TILE / 2}" cy="${TILE / 2}" r="${TILE / 2 - OUTLINE_INSET}" stroke-opacity="0.45" stroke-width="2" stroke-dasharray="10 8" />
<path d="${continuousSquarePath(OUTLINE_INSET)}" stroke-opacity="0.34" stroke-width="2" />
</g>`,
};
const BLUEPRINT = {
flat: BLUEPRINT_SHEET,
lit: {
...BLUEPRINT_SHEET,
tileEdge: { color: "#0034B4", opacity: 0.55 },
markEdge: { color: "#1E5FD0", opacity: 0.5 },
markShadow: { color: "#00308F", opacity: 0.4 },
},
};
// The lit finish, tuned against Apple's own renders. The light comes from straight above: a
// layer's upward-facing edge gets a bright highlight, its downward-facing edge a fainter one, and
// its side edges darken.
//
// An edge highlight is the part of the layer that a vertically shifted copy does not cover. A
// vertical blur of the shifted copy makes the highlight brightest at the edge and absent on
// vertical edges. A wider, round blur of the same band dims it where the edge turns away from
// the light, which is what keeps the tile's corners quieter than its top.
function glassFilter({ id, edge, edgeWidth, lightWidth, upperLight, lowerLight, shadow }) {
const light = (name, direction, opacity) => `
<feOffset in="SourceAlpha" dy="${direction * lightWidth}" />
<feGaussianBlur stdDeviation="0 ${lightWidth}" result="${name}Shifted" />
<feComposite in="SourceAlpha" in2="${name}Shifted" operator="out" result="${name}Edge" />
<feOffset in="SourceAlpha" dy="${direction * lightWidth * 2}" result="${name}Far" />
<feComposite in="SourceAlpha" in2="${name}Far" operator="out" />
<feGaussianBlur stdDeviation="${lightWidth * 3}" />
<feComponentTransfer><feFuncA type="gamma" exponent="3" amplitude="65" /></feComponentTransfer>
<feComposite in2="${name}Edge" operator="arithmetic" k1="1" result="${name}Shape" />
<feFlood flood-color="#FFFFFF" flood-opacity="${opacity}" />
<feComposite in2="${name}Shape" operator="in" result="${name}" />`;
const dropShadow = shadow
? `
<feGaussianBlur in="SourceAlpha" stdDeviation="${shadow.blur}" />
<feOffset dy="${shadow.offset}" result="shadowShape" />
<feFlood flood-color="${shadow.color}" flood-opacity="${shadow.opacity}" />
<feComposite in2="shadowShape" operator="in" result="shadow" />`
: "";
return `
<filter id="${id}" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB">${dropShadow}
<feMorphology in="SourceAlpha" operator="erode" radius="${edgeWidth * 0.6}" />
<feGaussianBlur stdDeviation="${edgeWidth}" result="core" />
<feFlood flood-color="${edge.color}" flood-opacity="${edge.opacity}" />
<feComposite in2="core" operator="out" />
<feComposite in2="SourceAlpha" operator="in" result="edge" />
${light("upper", 1, upperLight)}
${light("lower", -1, lowerLight)}
<feMerge>
${shadow ? '<feMergeNode in="shadow" />' : ""}
<feMergeNode in="SourceGraphic" />
<feMergeNode in="edge" />
<feMergeNode in="upper" />
<feMergeNode in="lower" />
</feMerge>
</filter>`;
}
function litDefs({ tileEdge, markEdge, markShadow }) {
const markBody = `
<linearGradient id="markBody" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#FFFFFF" />
<stop offset="0.4" stop-color="#FFFFFF" />
<stop offset="1" stop-color="#D9DFE9" />
</linearGradient>`;
const tileGlass = glassFilter({
id: "tileGlass",
edge: tileEdge,
edgeWidth: 3,
lightWidth: 3.6,
upperLight: 0.82,
lowerLight: 0.45,
});
const markGlass = glassFilter({
id: "markGlass",
edge: markEdge,
edgeWidth: 1.2,
lightWidth: 1.6,
upperLight: 1,
lowerLight: 0.6,
shadow: { ...markShadow, blur: 9, offset: 8 },
});
return `${markBody}${tileGlass}${markGlass}`;
}
function brandMark(stroke) {
const svg = readFileSync(brandMarkPath, "utf8");
const outline = svg.match(/\bd="([^"]+)"/);
const strokeWidth = svg.match(/\bstroke-width="([^"]+)"/);
if (!outline || !strokeWidth) {
throw new Error(`No stroked mark path in ${brandMarkPath}`);
}
// The path carries its own `fill="none"`: Icon Composer ignores the one on the <svg> element and
// draws a hairline from the end of the stroke back to its start.
return `<path d="${outline[1]}" fill="none" stroke="${stroke}" stroke-width="${strokeWidth[1]}" stroke-linecap="round" stroke-linejoin="round" />`;
}
function scaledAboutCentre(scale, content) {
const centre = TILE / 2;
return `<g transform="translate(${centre} ${centre}) scale(${scale}) translate(${-centre} ${-centre})">${content}</g>`;
}
// A square canvas with the 700-unit artwork box centred on it and covering `boxOnCanvas` of its
// width.
function canvasSvg(boxOnCanvas, content) {
const canvasUnits = TILE / boxOnCanvas;
const origin = (TILE - canvasUnits) / 2;
return [
`<svg width="${CANVAS}" height="${CANVAS}" viewBox="${origin} ${origin} ${canvasUnits} ${canvasUnits}" fill="none" xmlns="http://www.w3.org/2000/svg">`,
content,
"</svg>",
].join("\n");
}
// The tile with the mark on it. A masked tile has the continuous corners cut into the artwork. A
// square tile is for platforms that apply their own mask.
function tileIconSvg({ artwork, finish, tileOnCanvas, corners }) {
const look = artwork[finish];
const isLit = finish === "lit";
const filtered = (id, content) => (isLit ? `<g filter="url(#${id})">${content}</g>` : content);
const tile =
corners === "continuous" ? `<g clip-path="url(#tile)">${look.surface}</g>` : look.surface;
const mark = scaledAboutCentre(MARK_SCALE, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
return canvasSvg(
tileOnCanvas,
[
`<defs><clipPath id="tile">${TILE_SHAPE}</clipPath>${look.defs}${isLit ? litDefs(look) : ""}</defs>`,
filtered("tileGlass", tile),
filtered("markGlass", mark),
].join("\n"),
);
}
// The white mark alone on a transparent canvas, its ink covering `inkOnCanvas` of the width.
function markOnlySvg(inkOnCanvas) {
return canvasSvg((inkOnCanvas * TILE) / MARK_INK, brandMark("#FFFFFF"));
}
function rasterizer(svg) {
const source = Buffer.from(svg);
const sized = (size) => sharp(source).resize(size, size);
return {
png: (size) => sized(size).png({ compressionLevel: 9 }).toBuffer(),
opaquePng: (size) => sized(size).removeAlpha().png({ compressionLevel: 9 }).toBuffer(),
rgba: (size) => sized(size).ensureAlpha().raw().toBuffer(),
};
}
// ICO: a directory of PNG-encoded entries. A size byte of 0 means 256.
function encodeIco(entries) {
const header = Buffer.alloc(6);
header.writeUInt16LE(1, 2);
header.writeUInt16LE(entries.length, 4);
let offset = header.length + entries.length * 16;
const directory = entries.map(({ size, png }) => {
const entry = Buffer.alloc(16);
entry.writeUInt8(size % 256, 0);
entry.writeUInt8(size % 256, 1);
entry.writeUInt16LE(1, 4);
entry.writeUInt16LE(32, 6);
entry.writeUInt32LE(png.length, 8);
entry.writeUInt32LE(offset, 12);
offset += png.length;
return entry;
});
return Buffer.concat([header, ...directory, ...entries.map((entry) => entry.png)]);
}
function icnsElement(type, data) {
const header = Buffer.alloc(8);
header.write(type, 0, "latin1");
header.writeUInt32BE(header.length + data.length, 4);
return Buffer.concat([header, data]);
}
// The 16 and 32 pixel ICNS slots predate PNG: three run-length-encoded colour planes plus a
// separate 8-bit alpha mask. A control byte below 128 copies the next (byte + 1) values, so
// literal-only chunks are a valid encoding.
function icnsLegacyElements(colorType, maskType, rgba) {
const pixels = rgba.length / 4;
const chunks = [];
for (let channel = 0; channel < 3; channel += 1) {
for (let start = 0; start < pixels; start += 128) {
const length = Math.min(128, pixels - start);
const chunk = Buffer.alloc(length + 1);
chunk[0] = length - 1;
for (let index = 0; index < length; index += 1) {
chunk[index + 1] = rgba[(start + index) * 4 + channel];
}
chunks.push(chunk);
}
}
const mask = Buffer.alloc(pixels);
for (let index = 0; index < pixels; index += 1) {
mask[index] = rgba[index * 4 + 3];
}
return [icnsElement(colorType, Buffer.concat(chunks)), icnsElement(maskType, mask)];
}
async function encodeIcns(icon) {
const pngSlots = [
["ic07", 128],
["ic08", 256],
["ic09", 512],
["ic10", 1024],
["ic11", 32],
["ic12", 64],
["ic13", 256],
["ic14", 512],
];
const elements = [
...icnsLegacyElements("is32", "s8mk", await icon.rgba(16)),
...icnsLegacyElements("il32", "l8mk", await icon.rgba(32)),
];
for (const [type, size] of pngSlots) {
elements.push(icnsElement(type, await icon.png(size)));
}
const body = Buffer.concat(elements);
const header = Buffer.alloc(8);
header.write("icns", 0, "latin1");
header.writeUInt32BE(header.length + body.length, 4);
return Buffer.concat([header, body]);
}
// The Icon Composer document macOS 26 and later build the app icon from. The canvas is the whole
// tile: macOS adds the mask, the margin, and the lighting. The mark stays opaque so it reads as
// solid white on the black tile.
function iconComposerFiles() {
const layer = "butterfly.svg";
const document = {
fill: { solid: "srgb:0.00000,0.00000,0.00000,1.00000" },
groups: [
{
layers: [{ "image-name": layer, name: "butterfly" }],
shadow: { kind: "neutral", opacity: 0.5 },
translucency: { enabled: false, value: 0.5 },
},
],
"supported-platforms": { squares: ["macOS"] },
};
return [
["icon.json", `${JSON.stringify(document, null, 2)}\n`],
[`Assets/${layer}`, `${markOnlySvg(MARK_INK_ON_TILE)}\n`],
];
}
function write(file, data) {
const target = path.join(repoRoot, file);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, data);
}
function desktopIcon(artwork, finish, tileOnCanvas) {
return rasterizer(tileIconSvg({ artwork, finish, tileOnCanvas, corners: "continuous" }));
}
async function buildDesktopIcons() {
const production = desktopIcon(PRODUCTION, "flat", WINDOWS_LINUX_TILE_ON_CANVAS);
const assets = "packages/desktop/assets";
const pngFiles = [
["icon.png", 512],
["32x32.png", 32],
["64x64.png", 64],
["128x128.png", 128],
["128x128@2x.png", 256],
];
for (const [file, size] of pngFiles) {
write(`${assets}/${file}`, await production.png(size));
}
const icoEntries = [];
for (const size of [32, 16, 24, 48, 64, 256]) {
icoEntries.push({ size, png: await production.png(size) });
}
write(`${assets}/icon.ico`, encodeIco(icoEntries));
write(
`${assets}/icon.icns`,
await encodeIcns(desktopIcon(PRODUCTION, "flat", MACOS_TILE_ON_CANVAS)),
);
for (const [file, content] of iconComposerFiles()) {
write(`${assets}/icon.icon/${file}`, content);
}
write(
`${assets}/icon-dev.png`,
await desktopIcon(BLUEPRINT, "flat", MACOS_TILE_ON_CANVAS).png(CANVAS),
);
}
async function buildMobileIcons() {
const flat = (corners) =>
rasterizer(tileIconSvg({ artwork: PRODUCTION, finish: "flat", tileOnCanvas: 1, corners }));
// iOS masks these itself, and Expo flattens any transparency in the app icon onto white.
const square = flat("square");
// Shown as supplied, so the corners are part of the artwork.
const masked = flat("continuous");
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_VISIBLE * MARK_INK_ON_TILE));
const notification = rasterizer(markOnlySvg(NOTIFICATION_MARK_INK));
write("packages/app/assets/images/icon.png", await square.opaquePng(1024));
write("packages/app/public/apple-touch-icon.png", await square.opaquePng(180));
write(
"packages/app/assets/images/android-icon-foreground.png",
await adaptiveForeground.png(1024),
);
write("packages/app/assets/images/notification-icon.png", await notification.png(96));
write("packages/app/assets/images/splash-icon.png", await masked.png(1024));
write("packages/app/public/pwa-icon-192.png", await masked.png(192));
write("packages/app/public/pwa-icon-512.png", await masked.png(512));
write("fastlane/metadata/android/en-US/images/icon.png", await masked.png(512));
}
async function buildLitIcons() {
for (const [file, artwork] of [
["paseo-lit.png", PRODUCTION],
["paseo-dev-lit.png", BLUEPRINT],
]) {
const icon = desktopIcon(artwork, "lit", MACOS_TILE_ON_CANVAS);
write(`assets/brand/app-icons/${file}`, await icon.png(CANVAS));
}
}
await buildDesktopIcons();
await buildMobileIcons();
await buildLitIcons();
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

+1 -4
View File
@@ -128,8 +128,6 @@ buildNpmPackage {
cd packages/desktop
# The Nix output is not a distributable DMG, so leave it unsigned and
# disable the hardened runtime that requires a matching signature.
# Compiling the Icon Composer document needs Xcode, which the build
# does not have, so use the prebuilt icns.
CSC_IDENTITY_AUTO_DISCOVERY=false \
npm exec --offline -- electron-builder \
--config electron-builder.yml \
@@ -140,8 +138,7 @@ buildNpmPackage {
--config.buildVersion=${lib.escapeShellArg buildVersion} \
--config.mac.identity=null \
--config.mac.hardenedRuntime=false \
--config.mac.notarize=false \
--config.mac.icon=assets/icon.icns
--config.mac.notarize=false
)
''}
+1 -1
View File
@@ -1 +1 @@
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
sha256-SZV3WTKLb+JhxWNo/jWyx+2sipzfL93YbbqQSihd3Wo=
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 32 KiB

@@ -196,18 +196,6 @@ function makeStreamReducerEvent(
};
}
function receiveSteer() {
return processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeAssistantTimelineEvent("with the uncommit", "m1"), 2),
makeStreamReducerEvent(makeTimelineEvent("keep going", "user_message"), 3),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 1 },
});
}
function makeAssistantItem(
text: string,
id = `assistant-${text.length}`,
@@ -1792,52 +1780,6 @@ describe("processTimelineResponse", () => {
]);
});
it.each([
{ source: "live prefix", text: "with the uncommit", seq: 2 },
{ source: "earlier projected page", text: "with the uncommitted changes.", seq: 4 },
])("reuses the assistant row from the $source across a steer", ({ text, seq }) => {
const live = receiveSteer();
const result = processTimelineResponse({
...baseTimelineInput,
currentTail: [
{
...makeAssistantItem(text, "m1"),
messageId: "m1",
timelineCursor: { epoch: "epoch-1", seq },
},
...live.tail.slice(1),
],
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
payload: {
...baseTimelineInput.payload,
direction: "after",
epoch: "epoch-1",
startCursor: { seq: 4 },
endCursor: { seq: 4 },
entries: [
{
...makeTimelineEntry(2, "with the uncommitted changes.", "assistant_message", 4),
sourceSeqRanges: [
{ startSeq: 2, endSeq: 2 },
{ startSeq: 4, endSeq: 4 },
],
item: {
type: "assistant_message",
text: "with the uncommitted changes.",
messageId: "m1",
},
},
],
},
});
expect([...result.tail, ...result.head]).toMatchObject([
{ kind: "assistant_message", text: "with the uncommitted changes.", messageId: "m1" },
{ kind: "user_message", text: "keep going" },
]);
});
it("keeps a tail submitted prompt before a reconciled live assistant head", () => {
const prompt = makeSubmittedUserMessage("new prompt", "submitted-new-prompt");
@@ -4035,22 +3977,6 @@ describe("processAgentStreamEvent", () => {
});
describe("processAgentStreamEvents", () => {
it("keeps a live reply in one row across a steer", () => {
const live = receiveSteer();
const result = processAgentStreamEvents({
events: [makeStreamReducerEvent(makeAssistantTimelineEvent("ted changes.", "m1"), 4)],
currentTail: live.tail,
currentHead: live.head,
currentCursor: live.cursor ?? undefined,
});
expect(result.tail).toEqual([]);
expect(result.head).toMatchObject([
{ kind: "assistant_message", text: "with the uncommitted changes.", messageId: "m1" },
{ kind: "user_message", text: "keep going" },
]);
});
it("coalesces contiguous assistant stream events into one head update and final cursor", () => {
const result = processAgentStreamEvents({
events: [
@@ -791,38 +791,21 @@ function reconcileOverlappingProjectedAssistant(params: {
epoch: string;
currentEndSeq: number;
}): { tail: StreamItem[]; head: StreamItem[]; reconciled: boolean } {
const { unit, currentEndSeq, epoch } = params;
const unchanged = { tail: params.tail, head: params.head, reconciled: false };
if (unit.event.type !== "timeline" || unit.event.item.type !== "assistant_message") {
return unchanged;
const { unit } = params;
if (
unit.event.type !== "timeline" ||
unit.event.item.type !== "assistant_message" ||
!unit.sourceSeqRanges.some(
(range) => range.startSeq <= params.currentEndSeq && range.endSeq > params.currentEndSeq,
)
) {
return { tail: params.tail, head: params.head, reconciled: false };
}
const projectedText = unit.event.item.text;
const projectedMessageId = unit.event.item.messageId;
const crossesCursor = unit.sourceSeqRanges.some(
(range) => range.startSeq <= currentEndSeq && range.endSeq > currentEndSeq,
);
// A steer occupies the gap between source ranges. Match that projected reply
// by its source positions because a tool call can split rows with the same id.
const coversItem = (item: AssistantMessageItem) => {
const cursor = item.timelineCursor;
return (
cursor?.epoch === epoch &&
unit.sourceSeqRanges.some(
(range) => range.startSeq <= cursor.seq && cursor.seq <= range.endSeq,
)
);
};
const bridgesSteer =
unit.sourceSeqRanges.length > 1 &&
projectedMessageId !== undefined &&
unit.seqEnd > currentEndSeq &&
unit.sourceSeqRanges.some((range) => range.endSeq <= currentEndSeq);
if (!crossesCursor && !bridgesSteer) return unchanged;
const matches = (item: StreamItem) => {
if (item.kind !== "assistant_message") return false;
if (bridgesSteer) return item.messageId === projectedMessageId && coversItem(item);
if (projectedMessageId && item.messageId) return item.messageId === projectedMessageId;
return projectedText.startsWith(item.text);
};
@@ -834,13 +817,15 @@ function reconcileOverlappingProjectedAssistant(params: {
const headMatch = findMatch(params.head);
const tailMatch = findMatch(params.tail);
// Keep a cached reply before the steer even if a live suffix also exists.
const match = bridgesSteer ? (tailMatch ?? headMatch) : (headMatch ?? tailMatch);
if (!match) return unchanged;
const match = headMatch ?? tailMatch;
if (!match) {
return { tail: params.tail, head: params.head, reconciled: false };
}
const messageId = projectedMessageId ?? match.current.messageId;
const replacement: AssistantMessageItem = {
...match.current,
kind: "assistant_message",
id: match.current.id,
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
@@ -852,26 +837,21 @@ function reconcileOverlappingProjectedAssistant(params: {
return next;
};
const removeMatch = (items: StreamItem[], index: number) => [
...items.slice(0, index),
...items.slice(index + 1),
];
if (bridgesSteer && tailMatch) {
return {
tail: replaceMatch(params.tail, tailMatch.index),
head: headMatch ? removeMatch(params.head, headMatch.index) : params.head,
reconciled: true,
};
}
if (headMatch) {
const tailCursor = tailMatch?.current.timelineCursor;
const replacesCachedPrefix =
tailMatch !== null &&
tailCursor?.epoch === params.epoch &&
unit.sourceSeqRanges.some(
(range) => range.startSeq <= tailCursor.seq && tailCursor.seq <= range.endSeq,
);
return {
// Live chunks can arrive before catch-up while their cached prefix is still painted.
// The projected reply owns both copies; keeping the prefix would duplicate it and
// cause completion to discard the updated head as an already-committed item.
tail:
tailMatch && coversItem(tailMatch.current)
? removeMatch(params.tail, tailMatch.index)
: params.tail,
tail: replacesCachedPrefix
? [...params.tail.slice(0, tailMatch.index), ...params.tail.slice(tailMatch.index + 1)]
: params.tail,
head: replaceMatch(params.head, headMatch.index),
reconciled: true,
};
+45 -68
View File
@@ -959,24 +959,6 @@ function appendUserMessage(
return upsertUserMessage(state, nextItem);
}
function findSteeredAssistantIndex(
items: StreamItem[],
messageId: string,
turnId: string | undefined,
): number {
let index = items.length - 1;
while (items[index]?.kind === "user_message") {
index -= 1;
}
const candidate = items[index];
return index < items.length - 1 &&
candidate?.kind === "assistant_message" &&
candidate.messageId === messageId &&
candidate.turnId === turnId
? index
: -1;
}
function appendAssistantMessage(
state: StreamItem[],
text: string,
@@ -985,41 +967,43 @@ function appendAssistantMessage(
messageId?: string,
reservedItemIds?: ReadonlySet<string>,
timelineCursor?: TimelinePosition,
turnId?: string,
): StreamItem[] {
const { chunk, hasContent } = normalizeChunk(text);
if (!chunk) {
return state;
}
const lastIndex = state.length - 1;
const last = state[lastIndex];
let index = -1;
if (
last?.kind === "assistant_message" &&
(messageId === undefined || last.messageId === messageId)
) {
index = lastIndex;
} else if (source === "live") {
if (messageId !== undefined) {
index = findSteeredAssistantIndex(state, messageId, turnId);
} else if (
last?.kind === "user_message" &&
state[lastIndex - 1]?.kind === "assistant_message"
) {
index = lastIndex - 1;
}
}
const previous = state[index];
if (previous?.kind === "assistant_message") {
const last = state[state.length - 1];
const shouldAppendToLast =
last &&
last.kind === "assistant_message" &&
(messageId === undefined || last.messageId === messageId);
if (shouldAppendToLast) {
const updated: AssistantMessageItem = {
...previous,
text: `${previous.text}${chunk}`,
...last,
text: `${last.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, index), updated, ...state.slice(index + 1)];
return [...state.slice(0, -1), updated];
}
// A submitted user row can follow the streaming assistant during interrupt.
// In that case, look one row further back for the assistant to extend.
const secondLast = state[state.length - 2];
if (
source === "live" &&
last?.kind === "user_message" &&
secondLast?.kind === "assistant_message" &&
(messageId === undefined || secondLast.messageId === messageId)
) {
const updated: AssistantMessageItem = {
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -2), updated, last];
}
if (!hasContent) {
@@ -1589,7 +1573,6 @@ function reduceTimelineEvent(
item.messageId,
reservedItemIds,
timelineCursor,
event.turnId,
);
case "reasoning":
return appendThought(state, item.text, timestamp, timelineCursor, event.turnId);
@@ -1827,27 +1810,23 @@ function getActiveAssistantHeadIndex(head: StreamItem[]): number {
return -1;
}
function getTailAssistantResumeIndex(params: {
function getTailAssistantToResume(params: {
incomingKind: StreamItem["kind"] | null;
event: AgentStreamEventPayload;
nextHead: StreamItem[];
tail: StreamItem[];
source: StreamUpdateSource;
}): number {
const { incomingKind, event, nextHead, tail, source } = params;
if (incomingKind !== "assistant_message" || nextHead.length !== 0) return -1;
const messageId = getIncomingAssistantMessageId(event);
const last = tail.at(-1);
if (
last?.kind === "assistant_message" &&
(messageId === undefined || last.messageId === messageId)
) {
return tail.length - 1;
tailAssistant: StreamItem | undefined;
}): AssistantMessageItem | null {
if (params.incomingKind !== "assistant_message" || params.nextHead.length !== 0) {
return null;
}
return source === "live" && event.type === "timeline" && messageId !== undefined
? findSteeredAssistantIndex(tail, messageId, event.turnId)
: -1;
if (params.tailAssistant?.kind !== "assistant_message") {
return null;
}
const incomingMessageId = getIncomingAssistantMessageId(params.event);
if (incomingMessageId !== undefined && params.tailAssistant.messageId !== incomingMessageId) {
return null;
}
return params.tailAssistant;
}
/**
@@ -2076,17 +2055,15 @@ export function applyStreamEvent(params: {
flushHead();
}
const resumeIndex = getTailAssistantResumeIndex({
const tailAssistant = getTailAssistantToResume({
incomingKind,
event,
nextHead,
tail: nextTail,
source,
tailAssistant: nextTail.at(-1),
});
if (resumeIndex >= 0) {
// Move any steers with the reply so the reply stays above them as it streams.
nextHead = nextTail.slice(resumeIndex);
nextTail = nextTail.slice(0, resumeIndex);
if (tailAssistant) {
nextTail = nextTail.slice(0, -1);
nextHead = [tailAssistant];
changedTail = true;
changedHead = true;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 994 B

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 863 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 27 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.9 KiB

@@ -1,28 +0,0 @@
{
"fill": {
"solid": "srgb:0.00000,0.00000,0.00000,1.00000"
},
"groups": [
{
"layers": [
{
"image-name": "butterfly.svg",
"name": "butterfly"
}
],
"shadow": {
"kind": "neutral",
"opacity": 0.5
},
"translucency": {
"enabled": false,
"value": 0.5
}
}
],
"supported-platforms": {
"squares": [
"macOS"
]
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 31 KiB

+1 -5
View File
@@ -43,8 +43,7 @@ mac:
artifactName: "Paseo-${version}-${arch}.${ext}"
minimumSystemVersion: "13.0.0"
category: public.app-category.developer-tools
# An Icon Composer document, compiled by Xcode's actool (26 or later) at build time.
icon: assets/icon.icon
icon: assets/icon.icns
hardenedRuntime: true
notarize: true
entitlements: build/entitlements.mac.plist
@@ -57,9 +56,6 @@ mac:
target:
- dmg
- zip
dmg:
# actool also derives an .icns from the document, but only up to 256 px.
icon: assets/icon.icns
linux:
category: Development
icon: assets
@@ -1,5 +1,5 @@
import { Duplex, PassThrough } from "node:stream";
import { describe, expect, test, vi } from "vitest";
import { describe, expect, test } from "vitest";
import {
decodeNetworkTunnelFrame,
encodeNetworkTunnelFrame,
@@ -278,30 +278,20 @@ describe("TunnelMuxClient", () => {
});
test("sends heartbeat pings and closes a silent half-open wire after heartbeatTimeoutMs", async () => {
// The clock is faked: on a slow machine the first real interval tick can land after the
// timeout, and then the wire closes before any ping goes out.
vi.useFakeTimers();
try {
const fake = createFakeWire();
const mux = new TunnelMuxClient(fake.wire, {
heartbeatIntervalMs: 25,
heartbeatTimeoutMs: 65,
});
let closeErr: Error | undefined;
mux.onClose((err) => {
closeErr = err;
});
const fake = createFakeWire();
const mux = new TunnelMuxClient(fake.wire, {
heartbeatIntervalMs: 25,
heartbeatTimeoutMs: 65,
});
await vi.advanceTimersByTimeAsync(50);
expect(fake.sentFrames.filter((f) => f.type === "ping")).toHaveLength(2);
expect(mux.isClosed()).toBe(false);
const closed = new Promise<Error | undefined>((resolve) => {
mux.onClose((err) => resolve(err));
});
await vi.advanceTimersByTimeAsync(25);
expect(mux.isClosed()).toBe(true);
expect(closeErr?.message).toMatch(/heartbeat/i);
} finally {
vi.useRealTimers();
}
const closeErr = await closed;
expect(mux.isClosed()).toBe(true);
expect(fake.sentFrames.some((f) => f.type === "ping")).toBe(true);
expect(closeErr?.message).toMatch(/heartbeat/i);
});
test("closes an unresponsive wire when openStream times out with zero inbound frames", async () => {
@@ -4,8 +4,7 @@ import path from "node:path";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
// Stamped icons are cached under this version. Bump it when the stamp or the base icon art changes.
const STAMP_CACHE_VERSION = "v3";
const STAMP_CACHE_VERSION = "v2";
export const MONOSPACE_FONT_CANDIDATES = [
"Menlo-Bold",
@@ -1481,74 +1481,6 @@ test("a steer the provider names without echoing it can be rewound to", async ()
}
});
test("keeps one assistant message whole when a steer lands between its chunks", async () => {
const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() });
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-split-"));
const manager = new AgentManager({
clients: {
codex: new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})(),
},
// Zero window: every streamed chunk flushes on the coalescer's leading edge,
// so the timeline reaches its next state without waiting on a timer.
agentStreamCoalesceWindowMs: 0,
logger,
});
let agentId: string | null = null;
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
agentId = agent.id;
const run = manager.streamAgent(agent.id, "initial");
void (async () => {
for await (const _event of run) {
}
})();
await manager.waitForAgentRunStart(agent.id);
const conversation = () =>
manager
.fetchTimeline(agent.id, { limit: 0 })
.rows.filter(
(row) => row.item.type === "assistant_message" || row.item.type === "user_message",
)
.map((row) => row.item);
session.pushEvent({
type: "timeline",
provider: "codex",
turnId: "active-turn-1",
item: { type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
});
await expect
.poll(conversation)
.toMatchObject([
{ type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
]);
await expect(
manager.steerAgentRun(agent.id, "keep going", { clientMessageId: "keep-going-client" }),
).resolves.toEqual({ status: "accepted" });
session.pushEvent({
type: "timeline",
provider: "codex",
turnId: "active-turn-1",
item: { type: "assistant_message", text: "ted changes.", messageId: "msg-1" },
});
await expect.poll(conversation).toMatchObject([
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
{ type: "user_message", text: "keep going" },
]);
} finally {
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("orders a concurrent replacement after a pending accepted steer", async () => {
const entered = deferred<void>();
const release = deferred<void>();
@@ -7,62 +7,6 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
describe("InMemoryAgentTimelineStore", () => {
it("keeps a streaming assistant message whole when a steering prompt is recorded mid-stream", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1");
store.append("agent-1", {
type: "assistant_message",
text: "with the uncommit",
messageId: "msg-1",
});
store.append("agent-1", { type: "user_message", text: "keep going" });
store.append("agent-1", {
type: "assistant_message",
text: "ted changes.",
messageId: "msg-1",
});
expect(store.getItems("agent-1")).toEqual([
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
{ type: "user_message", text: "keep going" },
]);
});
it("keeps text written after a tool call below it when both share a message id", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1");
store.append("agent-1", { type: "assistant_message", text: "Let me check.", messageId: "m1" });
store.append("agent-1", {
type: "tool_call",
callId: "c1",
name: "shell",
status: "completed",
detail: { type: "unknown", input: null, output: null },
error: null,
});
store.append("agent-1", { type: "assistant_message", text: "Found it.", messageId: "m1" });
expect(store.getItems("agent-1").map((item) => item.type)).toEqual([
"assistant_message",
"tool_call",
"assistant_message",
]);
});
it("keeps chunks without a message id apart when a user message is recorded between them", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1");
store.append("agent-1", { type: "assistant_message", text: "First." });
store.append("agent-1", { type: "user_message", text: "keep going" });
store.append("agent-1", { type: "assistant_message", text: "Second." });
expect(store.getItems("agent-1")).toEqual([
{ type: "assistant_message", text: "First." },
{ type: "user_message", text: "keep going" },
{ type: "assistant_message", text: "Second." },
]);
});
it("resets stale forward cursors to complete available turns", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "current" });
@@ -416,34 +360,6 @@ describe("turn metrics", () => {
expect(rows[1]).toMatchObject({ item: { text: "Done" }, turnMetrics: metrics });
});
it("keeps the stats on a steered message whose chunks carry a message id", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
store.initialize("a", {
rows: [
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
{ seq: 2, timestamp: at, item: { type: "assistant_message", text: "Do", messageId: "m1" } },
{ seq: 3, timestamp: at, item: { type: "assistant_message", text: "n", messageId: "m1" } },
{ seq: 4, timestamp: at, item: { type: "user_message", text: "keep going" } },
{
seq: 5,
timestamp: at,
item: { type: "assistant_message", text: "e", messageId: "m1" },
turnMetrics: metrics,
},
],
});
const rows = store.fetch("a").rows;
expect(rows.map((row) => row.item)).toEqual([
{ type: "user_message", text: "go" },
{ type: "assistant_message", text: "Done", messageId: "m1" },
{ type: "user_message", text: "keep going" },
]);
expect(rows[1]).toMatchObject({ turnMetrics: metrics });
});
it("keeps the stats on a tool card whose updates the projection merges", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
@@ -64,68 +64,6 @@ describe("projectTimelineRows", () => {
});
});
test("keeps one assistant message whole when a steering user message lands mid-stream", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: { type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: { type: "user_message", text: "keep going" },
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: { type: "assistant_message", text: "ted changes.", messageId: "msg-1" },
},
];
const projected = projectTimelineRows({ rows, mode: "projected" });
expect(projected.map((entry) => entry.item)).toEqual([
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
{ type: "user_message", text: "keep going" },
]);
});
test("keeps text written after a tool call below it when both share a message id", () => {
const rows: AgentTimelineRow[] = [
{
seq: 1,
timestamp: "2026-02-13T00:00:00.000Z",
item: { type: "assistant_message", text: "Let me check.", messageId: "msg-1" },
},
{
seq: 2,
timestamp: "2026-02-13T00:00:00.100Z",
item: {
type: "tool_call",
callId: "c1",
name: "shell",
status: "completed",
detail: { type: "unknown", input: null, output: null },
error: null,
},
},
{
seq: 3,
timestamp: "2026-02-13T00:00:00.200Z",
item: { type: "assistant_message", text: "Found it.", messageId: "msg-1" },
},
];
const projected = projectTimelineRows({ rows, mode: "projected" });
expect(projected.map((entry) => entry.item.type)).toEqual([
"assistant_message",
"tool_call",
"assistant_message",
]);
});
test("keeps adjacent assistant chunks with different message ids separate in projected mode", () => {
const rows: AgentTimelineRow[] = [
{
@@ -261,69 +261,46 @@ export function continuesAssistantMessage(
);
}
/**
* The index of the row in `rows` that `entry` continues, or null when `entry` starts a new
* row. A chunk continues the assistant message right before it. A chunk that carries a
* provider message id also continues its message across user rows recorded mid-stream, as
* a steer is. Any other row in between, such as a tool call, keeps the provider's order.
*/
function assistantContinuationIndex(
rows: readonly WorkingEntry[],
entry: WorkingEntry,
): number | null {
if (entry.item.type !== "assistant_message") return null;
let index = rows.length - 1;
let coveredThrough = rows[index]?.seqEnd ?? Number.NEGATIVE_INFINITY;
while (index >= 0 && rows[index].item.type === "user_message") {
index -= 1;
coveredThrough = Math.max(coveredThrough, rows[index]?.seqEnd ?? coveredThrough);
}
const previous = rows[index];
if (!previous || !continuesAssistantMessage(previous, entry)) return null;
const skipsUserRows = index < rows.length - 1;
if (skipsUserRows && entry.item.messageId === undefined) return null;
return coveredThrough + 1 === entry.seqStart ? index : null;
}
function mergeAssistantEntries(previous: WorkingEntry, entry: WorkingEntry): WorkingEntry {
const previousAssistant = previous.item as Extract<
AgentTimelineItem,
{ type: "assistant_message" }
>;
const entryAssistant = entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>;
const collapsedKinds = new Set<TimelineProjectionKind>([
...previous.collapsed,
...entry.collapsed,
"assistant_merge",
]);
return {
...previous,
item: {
type: "assistant_message",
text: `${previousAssistant.text}${entryAssistant.text}`,
...(previousAssistant.messageId ? { messageId: previousAssistant.messageId } : {}),
},
timestamp: entry.timestamp,
seqEnd: Math.max(previous.seqEnd, entry.seqEnd),
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
collapsed: Array.from(collapsedKinds),
// The turn's stats ride on its last row, which is the later chunk of a merged message.
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] {
const output: WorkingEntry[] = [];
for (const entry of entries) {
const index = assistantContinuationIndex(output, entry);
if (index === null) {
const previous = output[output.length - 1];
const shouldMerge =
previous &&
previous.seqEnd + 1 === entry.seqStart &&
continuesAssistantMessage(previous, entry);
if (!shouldMerge || !previous) {
output.push(entry);
continue;
}
output[index] = mergeAssistantEntries(output[index], entry);
const previousAssistant = previous.item as Extract<
AgentTimelineItem,
{ type: "assistant_message" }
>;
const entryAssistant = entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>;
const collapsedKinds = new Set<TimelineProjectionKind>([
...previous.collapsed,
...entry.collapsed,
"assistant_merge",
]);
output[output.length - 1] = {
...previous,
item: {
type: "assistant_message",
text: `${previousAssistant.text}${entryAssistant.text}`,
...(previousAssistant.messageId ? { messageId: previousAssistant.messageId } : {}),
},
timestamp: entry.timestamp,
seqEnd: entry.seqEnd,
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
collapsed: Array.from(collapsedKinds),
// The turn's stats ride on its last row, which is the later chunk of a merged message.
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
return output;
@@ -381,15 +358,10 @@ export class TimelineProjection {
this.extendSpan(index);
return index;
}
const continued = assistantContinuationIndex(this.rows, entry);
if (continued !== null) {
const mergedText = mergeAssistantEntries(this.rows[continued], entry);
this.rows[continued] = { ...mergedText, seq: mergedText.seqEnd };
this.extendSpan(continued);
return continued;
}
const previous = this.rows.at(-1);
const adjacent = previous ? mergeReasoningChunks([previous, entry]) : [entry];
const adjacent = previous
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
: [entry];
if (previous && adjacent.length === 1) {
const mergedText = adjacent[0];
this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd };