Compare commits

...
Author SHA1 Message Date
SunicemanandShane Su d2d4105366 Count an errored WebSocket handshake once during reconnect (#11428)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 11:42:52 +00:00
SunicemanandShane Su 37cb22dac8 Allow slow provider discovery to finish in project suggestions (#11438)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 11:13:43 +00:00
taemin HAandCodex 397d1e14d6 fix(app): Keep chats synchronized after online connection replacement (#11029)
* fix(app): Keep chats synchronized after online connection replacement

Initialize each new timeline owner from its bound client's connection
state. An adaptive transport switch can replace the client while the host
stays online, so the connection-state effect does not otherwise rerun.

Cover the online replacement with a real browser/daemon regression and
include before/after QA evidence.

Co-Authored-By: Codex <noreply@openai.com>

* test(app): Harden online connection replacement coverage

Advance the browser clock while awaiting real heartbeat and probe cycles
to avoid minutes of wall-clock waits. Check continuous connectivity,
hidden-chat catch-up, and prompt dismissal of the reconnect indicator.

Keep exact subscription matching as the shared helper default. Record
RED and GREEN evidence from byte-identical final test sources.

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-11-30 11:13:13 +00:00
Nathan McNulty d193e419e9 fix(copilot-usage): allow negative remaining quota on overage (#11006) 2026-11-30 11:12:42 +00:00
Galaxy RoamingandMohamed Boudra bd20e3fe98 fix(app): keep Markdown table <br> line breaks inside their cells (#9587)
* fix(app): keep Markdown table <br> line breaks inside their cells

* fix(app): scan HTML table wrappers in a single forward pass

* fix(app): preserve tag-only line prefixes before wrapped tables

* fix(app): pad <br> U+2028 separator on both sides for flanking emphasis

* build(app): rebuild the Markdown web parser with table cell line breaks

The engine moved into the repository, so the table cell change now lives
once in cpp/parser/MD4CParser.cpp and web gets it from a rebuilt WASM
instead of a second TypeScript pass over the parsed tree. Built with
emsdk 4.0.10; a build of the unchanged sources parses every Markdown file
in the repository the same as the previous artifact.

The parser now autolinks a bare URL after a table cell break, as it does
the first one. Sources without `<br` skip the extra table parse.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>

* fix(app): keep table cell line breaks when copying a table

A table cell can now hold a line break, but the copy paths wrote it as a
newline, which splits the Markdown row. Web selection copy and the native
serializers write it back as `<br>`. The native row accessibility label
joined the two lines into one word, so it now reads them apart.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-30 17:16:48 +07:00
paseo-bot[bot]andminamorl 39eaba6181 fix(server): show Claude Code system notifications instead of dropping them (#11419)
Claude Code reports things the user needs to know through
`{"type":"system","subtype":"notification"}`, for example that a requested
Code Mode did not start. The Claude provider had no branch for that subtype,
so the text only reached a trace-level raw event.

Map it to the existing timeline `notification` item (warning for `high` and
`immediate` priority, info otherwise) and log it as `claude.notification`
at warn or info.

Fixes #11241

Co-authored-by: minamorl <minamorl@users.noreply.github.com>
2026-11-30 10:13:05 +00:00
paseo-bot[bot] 63ede58d7d fix(app): keep long multiline drafts responsive (#11418)
The composer laid out the entire draft in a hidden textarea on every edit. Once complete lines establish the height cap and fullscreen threshold, measure those lines and keep the full text in the editor.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 10:12:40 +00:00
31 changed files with 969 additions and 36 deletions
+2 -2
View File
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
## Engine constraints
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
@@ -0,0 +1,89 @@
# Online client replacement: timeline recovery
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
## Reproduction
1. Open two chats on one host and return to the first.
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
3. Add another direct endpoint for the same daemon.
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
## Before: exact final test source
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
```text
Error: expect(locator).toHaveCount(expected) failed
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
Expected: 0
Received: 1
Timeout: 3000ms
1 failed
```
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
![Before: Reconnecting remains after online replacement](before.jpeg)
## After
Restore the production seed without changing the test files, then run:
```sh
npm run test:e2e --workspace=@getpaseo/app -- \
e2e/browser/viewed-agent-timelines.spec.ts \
--grep 'online connection replacement|visible chat reports updating until reconnect' \
--workers=1
```
```text
✓ an online connection replacement keeps every open chat synchronized (1.6m)
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
2 passed (2.3m)
```
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
![After: hidden history recovers and both chats receive messages](after.png)
## Other checks
```sh
npm run typecheck
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
npm run format
```
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
```text
Packaged desktop smoke: real app renderer and preload bridge loaded
Packaged desktop smoke: renderer-started desktop daemon reported running
Packaged desktop smoke: every built-in plugin started
Packaged desktop smoke: running bundled CLI shim daemon status
Packaged desktop smoke: creating terminal through bundled CLI shim
Packaged desktop smoke: terminal hook command completed
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
CLI shim daemon status and terminal smoke succeeded
```
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
## Coverage limits
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
- iOS, Android, Windows desktop, Linux desktop: not tested.
- External relay transport and a real provider turn: not tested by this regression.
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
- These are local results. No full-suite or GitHub CI pass is claimed.
Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

@@ -0,0 +1,18 @@
{
"production_source_restored": true,
"test_sha256": {
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
},
"red": {
"result": "expected failure",
"assertion": "Reconnecting alert expected 0, received 1",
"timeout_ms": 3000
},
"green": {
"passed": 2,
"online_replacement_duration": "1.6m",
"ordinary_reconnect_duration": "35.9s",
"total_duration": "2.3m"
}
}
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
import { test } from "../support/fixtures";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
}
async function delayActiveDaemonPongs(page: Page, port: string) {
let deliveredPongs = 0;
let inFlightPings = 0;
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
await page.routeWebSocket(
(url) => url.hostname === "localhost" && url.port === port,
(socket) => {
const server = socket.connectToServer();
socket.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
server.send(message);
});
server.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "pong") {
const timer = setTimeout(() => {
delayedPongs.delete(timer);
socket.send(message);
deliveredPongs += 1;
inFlightPings -= 1;
}, 1_000);
delayedPongs.add(timer);
} else {
socket.send(message);
}
});
},
);
return {
delivered: () => deliveredPongs,
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
dispose: () => {
for (const timer of delayedPongs) clearTimeout(timer);
},
};
}
async function readActiveLivenessRtt(page: Page): Promise<number> {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
};
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
}, getServerId());
}
async function readHostConnection(page: Page) {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
};
const snapshot = runtime.getSnapshot(serverId);
return {
generation: snapshot.clientGeneration,
status: snapshot.connectionStatus,
connection: snapshot.activeConnectionId,
};
}, getServerId());
}
async function settleHostProbeCycle(page: Page): Promise<void> {
await page.evaluate(async (serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
runProbeCycleNow(id: string): Promise<void>;
};
// Joins any in-flight cycle through its final replacement handshake.
await runtime.runProbeCycleNow(serverId);
}, getServerId());
}
async function observeContinuousHostConnection(page: Page) {
const observation = await page.evaluateHandle((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
subscribe(id: string, listener: () => void): () => void;
};
const connected: boolean[] = [];
const record = () => {
const snapshot = runtime.getSnapshot(serverId);
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
};
record();
const unsubscribe = runtime.subscribe(serverId, record);
return {
stop() {
unsubscribe();
return connected;
},
};
}, getServerId());
let stopped: Promise<boolean[]> | null = null;
return {
stop() {
stopped ??= observation
.evaluate((recorder) => recorder.stop())
.finally(() => observation.dispose());
return stopped;
},
};
}
async function advanceToOnlineReplacement(
page: Page,
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
beforeGeneration: number,
) {
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
// between hops, including the replacement handshake, without altering production timers.
for (let step = 0; step < 60; step += 1) {
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
await settleHostProbeCycle(page);
const pongsBefore = delayedPongs.delivered();
await page.clock.fastForward(10_000);
await expect
.poll(
async () =>
(await readHostConnection(page)).generation !== beforeGeneration ||
delayedPongs.delivered() > pongsBefore,
{ timeout: 10_000 },
)
.toBe(true);
await settleHostProbeCycle(page);
}
}
test.describe("Viewed agent timelines", () => {
test("an online connection replacement keeps every open chat synchronized", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
await page.clock.install();
const port = getE2EDaemonPort();
const delayedEndpoint = `localhost:${port}`;
const fasterEndpoint = `127.0.0.1:${port}`;
const delayedPongs = await delayActiveDaemonPongs(page, port);
const subscriptions = observeTimelineSubscriptions(page);
const scenario = await seedViewedTimelineScenario();
let connectionObservation:
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
| undefined;
try {
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
await openAgent(page, scenario, scenario.firstAgentId);
await selectAgent(page, "Second viewed chat");
await selectAgent(page, "First viewed chat");
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
await expectReconnectingToastGone(page);
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
await expect
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
.toBeGreaterThanOrEqual(800);
// Add another real route to the same daemon. Delaying only the active route's real
// pong frames gives the ordinary adaptive selector three consistently faster probes.
// No host state is forced offline and no client or timeline owner is replaced by the test.
connectionObservation = await observeContinuousHostConnection(page);
const beforeGeneration = await page.evaluate(
async ({ serverId, endpoint, activeEndpoint }) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
};
const before = runtime.getSnapshot(serverId);
if (
before.connectionStatus !== "online" ||
before.activeConnectionId !== `direct:${activeEndpoint}`
) {
throw new Error("Expected the initial real connection to be online");
}
await runtime.upsertDirectConnection({ serverId, endpoint });
return before.clientGeneration;
},
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
);
subscriptions.reset();
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
await expect
.poll(() => readHostConnection(page), { timeout: 3_000 })
.toEqual({
generation: beforeGeneration + 1,
status: "online",
connection: `direct:${fasterEndpoint}`,
});
expect(await connectionObservation.stop()).not.toContain(false);
await expectReconnectingToastGone(page, { timeout: 3_000 });
await page.screenshot({
path: testInfo.outputPath("after-online-connection-replacement.png"),
});
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
await selectAgent(page, "Second viewed chat");
await expectReconnectingToastGone(page, { timeout: 3_000 });
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
match: "includes",
});
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
} finally {
try {
await connectionObservation?.stop();
} finally {
delayedPongs.dispose();
await scenario.cleanup();
}
}
});
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
test.setTimeout(120_000);
const subscriptions = observeTimelineSubscriptions(page);
@@ -9,6 +9,7 @@ interface SessionMessage {
interface TimelineSubscriptionWaitOptions {
timeout?: number;
match?: "exact" | "includes";
}
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
timeout: options.timeout ?? 15_000,
})
.toEqual(expected);
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
},
};
}
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
expect(content?.html).toContain("<td>Value | detail</td>");
});
it("keeps a table cell's line breaks inside its row", () => {
const message = mountFixture();
message.innerHTML =
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td>&lt;br&gt; stays text</td></tr></tbody></table>";
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
expect(content?.plainText).toBe(
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
);
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
expect(content?.html).toContain("<td>&lt;br&gt; stays text</td>");
});
it("copies a workspace image path instead of its temporary display URL", () => {
const message = mountFixture();
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
});
turndown.use(gfm);
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
// A row is one line, so a cell's line break goes back to `<br>`.
turndown.addRule("escapedGfmTableCell", {
filter: ["th", "td"],
replacement: (content, node) => {
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
const prefix = index === 0 ? "| " : " ";
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
},
});
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
+86 -2
View File
@@ -1,5 +1,7 @@
import { Parser } from "htmlparser2";
import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import { gfmTable } from "micromark-extension-gfm-table";
import { decodeString } from "micromark-util-decode-string";
import type { Nodes } from "mdast";
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
} else if ("children" in node) node.children.forEach(protectCode);
}
protectCode(tree);
// Only `<br>` reads these, so a source without one skips the extra parse.
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => {
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
: /^\s*$/.test(source.slice(0, offset));
previousTag = { name, end: offset + raw.length };
if (EMPHASIS[name]) return EMPHASIS[name];
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
const boundary = layoutBoundary(
name,
source,
raw,
offset,
closing,
startsAfterBoundary,
inTable,
);
if (boundary !== null) return boundary;
if (name === "a") return markdownAnchor(raw, closing, links);
if (name === "img" && !closing) {
@@ -167,8 +180,15 @@ function layoutBoundary(
offset: number,
closing: boolean,
startsAfterBoundary: boolean,
inTable: boolean,
): string | null {
if (name === "br") return closing ? "" : " \n";
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
if (name === "br") {
if (closing) return "";
return inTable ? " \u2028 " : " \n";
}
if (name === "summary") return closing ? "**\n\n" : "**";
if (name === "details")
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
@@ -177,3 +197,67 @@ function layoutBoundary(
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
return null;
}
function hasNonWhitespaceAfterNewline(value: string): boolean {
const lastNewline = value.lastIndexOf("\n");
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
}
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
if (inCode) return false;
if (raw.startsWith("<!--")) return true;
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
}
function collectTableRanges(
source: string,
codeRanges: readonly { start: number; end: number }[],
): { start: number; end: number }[] {
let cursor = 0;
let codeIndex = 0;
let lineHasPrefixText = false;
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
// line breaks introduced by earlier masked tags.
const tableSource = source.replace(HTML, (raw, offset: number) => {
for (let index = cursor; index < offset; index++) {
const code = source.charCodeAt(index);
if (code === 10) lineHasPrefixText = false;
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
}
cursor = offset + raw.length;
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
if (!isTableWrapperTag(raw, inCode)) {
if (inCode || /^<code\b/i.test(raw)) {
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
else if (raw.includes("\n")) lineHasPrefixText = false;
} else if (raw.includes("\n")) {
lineHasPrefixText = false;
}
return raw;
}
const blanked = raw.replace(/[^\n]/g, " ");
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
return `${blanked.slice(0, -1)}\n`;
}
if (blanked.includes("\n")) lineHasPrefixText = false;
return blanked;
});
const tableRanges: { start: number; end: number }[] = [];
function findTables(node: Nodes) {
if (node.type === "table" && node.position) {
const start = node.position.start.offset;
const end = node.position.end.offset;
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
} else if ("children" in node) node.children.forEach(findTables);
}
findTables(
fromMarkdown(tableSource, {
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()],
}),
);
return tableRanges;
}
@@ -838,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
])("normalizes %s without changing code", (source, expected) => {
expect(prepareMarkdownSource(source).render()).toBe(expected);
});
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
const source = [
"| Col<br>One | Col<br />Two |",
"| --- | --- |",
"| First<br>Second<br/>Third | Plain |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const table = tree.children?.find((node) => node.type === "Table");
expect(table).toBeDefined();
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
expect(headRows).toHaveLength(1);
expect(bodyRows).toHaveLength(1);
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
expect(headCells[0].children).toEqual([
{ type: "Text", content: "Col" },
{ type: "LineBreak" },
{ type: "Text", content: "One" },
]);
expect(headCells[1].children).toEqual([
{ type: "Text", content: "Col" },
{ type: "LineBreak" },
{ type: "Text", content: "Two" },
]);
expect(bodyCells[0].children).toEqual([
{ type: "Text", content: "First" },
{ type: "LineBreak" },
{ type: "Text", content: "Second" },
{ type: "LineBreak" },
{ type: "Text", content: "Third" },
]);
});
it.each([
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const table = tree.children?.find((node) => node.type === "Table");
expect(table).toBeDefined();
const body = table?.children?.find((node) => node.type === "TableBody");
expect(body?.children).toHaveLength(1);
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
{ type: "Text", content: "1" },
{ type: "LineBreak" },
{ type: "Text", content: "2" },
]);
});
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
const source = [
"| Paths | Mixed | URLs |",
"| --- | --- | --- |",
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
].join("\n");
const prepared = prepareMarkdownSource(source);
const linked = recognizeTextLinks(
await parseMarkdown(prepared.render(), {
hardSoftBreaks: true,
latexMath: false,
}),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const table = linked.children?.find((node) => node.type === "Table");
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{
type: "Link",
attributes: { url: "src/first.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/first.ts" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "src/second.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/second.ts" }],
},
]);
expect(row?.children?.[1]?.children).toEqual([
{
type: "Link",
attributes: { url: "https://example.com/first" },
children: [{ type: "Text", content: "https://example.com/first" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "src/second.ts", recognizedLink: "true" },
children: [{ type: "Text", content: "src/second.ts" }],
},
]);
expect(row?.children?.[2]?.children).toEqual([
{
type: "Link",
attributes: { url: "https://example.com/first" },
children: [{ type: "Text", content: "https://example.com/first" }],
},
{ type: "LineBreak" },
{
type: "Link",
attributes: { url: "https://example.com/second" },
children: [{ type: "Text", content: "https://example.com/second" }],
},
]);
});
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
const source = [
"before\u2028after `before\u2028after`",
"",
"| Inline | Escaped | Entity |",
"| --- | --- | --- |",
"| `before\u2028after` | \\<br> | &lt;br&gt; `<br>` |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const collectLineBreaks = (node: ASTNode): number =>
(node.type === "LineBreak" ? 1 : 0) +
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
expect(collectLineBreaks(tree)).toBe(0);
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
expect(paragraph?.children).toEqual([
{ type: "Text", content: "before\u2028after " },
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
]);
const row = tree.children
?.find((node) => node.type === "Table")
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
]);
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
expect(row?.children?.[2]?.children).toEqual([
{ type: "Text", content: "<br> " },
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
]);
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
"a \nb",
);
});
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
const source = [
"| A | B |",
"| --- | --- |",
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
].join("\n");
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const row = tree.children
?.find((node) => node.type === "Table")
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(row?.children?.[0]?.children).toEqual([
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
{ type: "LineBreak" },
{ type: "Text", content: "阶梯首充" },
]);
expect(row?.children?.[1]?.children).toEqual([
{
type: "Strong",
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
},
{ type: "LineBreak" },
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
]);
});
});
it("preserves backslashes and decodes entities inside HTML code", () => {
@@ -0,0 +1,67 @@
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
import { createRoot } from "react-dom/client";
import { expect, it } from "vitest";
import { useComposerHeight } from "./height.web";
it("keeps height measurement bounded when editing a long multiline draft", () => {
function Composer() {
const textarea = useRef<HTMLTextAreaElement>(null);
const [renderedLines, setRenderedLines] = useState(1);
const getText = useCallback(() => textarea.current?.value ?? "", []);
const sizing = useComposerHeight({
getText,
textareaRef: textarea,
minHeight: 24,
maxHeight: 96,
onRenderedLinesChange: setRenderedLines,
});
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
const { onTextChange } = sizing;
const edit = useCallback(
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
[onTextChange],
);
const style = useMemo(
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
[sizing.style.height],
);
return (
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
);
}
const container = document.body.appendChild(document.createElement("div"));
const root = createRoot(container);
try {
act(() => root.render(<Composer />));
const editor = container.querySelector("textarea")!;
const draft = "Review the resulting change.\n".repeat(9_000);
function replaceText(text: string) {
act(() => {
editor.value = text;
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
});
}
replaceText(draft);
replaceText(draft + "x");
expect(editor.value).toBe(draft + "x");
expect(editor.style.height).toBe("96px");
expect(editor.dataset.multiline).toBe("true");
const measurement = document.querySelector<HTMLTextAreaElement>(
'textarea[aria-hidden="true"]',
)!;
expect(measurement.value.length).toBeLessThan(400);
replaceText("Short draft");
expect(editor.style.height).toBe("24px");
expect(editor.dataset.multiline).toBe("false");
} finally {
act(() => root.unmount());
container.remove();
}
});
+29 -6
View File
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
"paddingLeft",
] as const;
function prefixThroughHardLines(text: string, lines: number): string {
let lineEnd = -1;
for (let line = 0; line < lines; line += 1) {
lineEnd = text.indexOf("\n", lineEnd + 1);
if (lineEnd === -1) return text;
}
return text.slice(0, lineEnd + 1);
}
export function useComposerHeight({
getText,
textareaRef,
@@ -68,15 +77,29 @@ export function useComposerHeight({
mirror.style[property] = computedStyle[property];
}
mirror.style.width = `${sourceWidth}px`;
mirror.value = text.endsWith("\n") ? `${text} ` : text;
const padding =
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
const lineHeight = parseFloat(computedStyle.lineHeight);
if (lineHeight > 0)
paramsRef.current.onRenderedLinesChange?.(
Math.round((mirror.scrollHeight - padding) / lineHeight),
);
setBoundedHeight(mirror.scrollHeight);
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
// Keep measuring the whole draft when the prefix cannot prove both.
const measuredText =
Number.isFinite(currentMax) && lineHeight > 0
? prefixThroughHardLines(
text,
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
)
: text;
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
let scrollHeight = mirror.scrollHeight;
if (measuredText !== text && scrollHeight < currentMax) {
mirror.value = text.endsWith("\n") ? `${text} ` : text;
scrollHeight = mirror.scrollHeight;
}
if (lineHeight > 0) {
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
}
setBoundedHeight(scrollHeight);
},
[setBoundedHeight, textareaRef],
);
@@ -366,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
viewedTimelineSyncRef.current = sync;
setViewedTimelineSync(serverId, sync);
sync.setActive(getIsAppVisible(appStateRef.current));
// An online client replacement leaves isConnected unchanged, so seed each new owner.
sync.setConnected(client.getConnectionState().status === "connected");
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
sync.replaceOpenTabAgentIds(agentIds),
);
+7
View File
@@ -3,6 +3,13 @@ import { createAssistantMarkdownParser } from "./assistant-markdown-parser";
const markdownRenderer = createAssistantMarkdownParser();
// Disable linkify for selection HTML so text from unwrapped links stays unlinked.
const unlinkedMarkdownRenderer = createAssistantMarkdownParser().set({ linkify: false });
// Selection Markdown escapes every literal `<`, so a bare `<br>` is a table cell's line break.
unlinkedMarkdownRenderer.inline.ruler.after("escape", "cell_line_break", (state, silent) => {
if (!state.src.startsWith("<br>", state.pos)) return false;
if (!silent) state.push("hardbreak", "br", 0);
state.pos += "<br>".length;
return true;
});
type ClipboardMimeType = "text/plain" | "text/html";
@@ -1786,6 +1786,8 @@ export class DaemonClientCore {
// An endpoint security policy close cannot be fixed by retrying.
const securityFailure = describeEndpointSecurityClose(event);
if (securityFailure) this.setReconnectEnabled(false);
// A transport error may already have scheduled this socket's retry before its close.
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
const reason = this.authFailureReasonValue
? new DaemonAuthenticationError(this.authFailureReasonValue).message
: (securityFailure ?? describeTransportClose(event));
@@ -3264,6 +3266,8 @@ export class DaemonClientCore {
listProjectSuggestions(options?: ProjectSuggestionsOptions): Promise<ProjectSuggestionsPayload> {
return this.sendNamespacedCorrelatedSessionRequest<"project.suggestions.response">({
requestId: options?.requestId,
// Provider session discovery can take 90 seconds before the daemon resolves project roots.
timeout: 120_000,
message: {
type: "project.suggestions.request",
...(options?.providers ? { providers: options.providers } : {}),
+62
View File
@@ -3020,6 +3020,34 @@ test("foreground keeps a connect attempt that just started", async () => {
expect(client.getConnectionState().status).toBe("connected");
});
test("a handshake error followed by a close consumes one reconnect attempt", async () => {
useHeartbeatClock();
const [first, failed, recovered] = [
new FakeDaemon(),
new FakeDaemon(),
new FakeDaemon(),
] as const;
const { client, attempts } = connectThroughReplacements("error-and-close", [
first,
failed,
recovered,
]);
const connection = client.connect();
first.openConnection();
await connection;
first.daemonClosesWith("connection lost");
await vi.advanceTimersByTimeAsync(1_500);
expect(attempts()).toBe(2);
failed.triggerError(new Error("read ECONNRESET"));
failed.daemonClosesWith("abnormal closure");
await vi.advanceTimersByTimeAsync(2_999);
expect(attempts()).toBe(2);
await vi.advanceTimersByTimeAsync(1);
expect(attempts()).toBe(3);
recovered.openConnection();
expect(client.getConnectionState().status).toBe("connected");
});
test("foreground resets the retry delay after failed connections in the background", async () => {
useHeartbeatClock();
const daemons = Array.from({ length: 7 }, () => new FakeDaemon());
@@ -9480,6 +9508,40 @@ test("rejects usage requests when the host has neither capability", async () =>
expect(mock.sent).toEqual([]);
});
test("project suggestions accept a slow provider response past the default deadline", async () => {
useHeartbeatClock();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "slow-projects",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connected = client.connect();
mock.triggerOpen();
await connected;
const requestId = "slow-source";
const payload = {
requestId,
suggestions: [
{
rootPath: "/repo",
displayName: "repo",
sessionCount: 1,
providerIds: ["opencode"],
lastActivityAt: "2026-11-01T00:00:00Z",
},
],
providerErrors: [],
};
const result = client.listProjectSuggestions({ requestId }).catch((error: unknown) => error);
await vi.advanceTimersByTimeAsync(65_000);
mock.triggerMessage(wrapSessionMessage({ type: "project.suggestions.response", payload }));
expect(await result).toEqual(payload);
});
test("usage request timeout detaches its update listener", async () => {
vi.useFakeTimers();
try {
@@ -131,7 +131,7 @@ class TableContainerView(
TableCellData(
attributedText = renderCellNode(cell, isHeader, align),
plainText = extractPlainText(cell),
markdownText = MarkdownASTSerializer.serializeChildren(cell),
markdownText = MarkdownASTSerializer.serializeTableCell(cell),
isHeader = isHeader,
alignment = align,
)
@@ -169,7 +169,12 @@ class TableContainerView(
}
}
private fun extractPlainText(node: MarkdownASTNode): String = node.content + node.children.joinToString("") { extractPlainText(it) }
private fun extractPlainText(node: MarkdownASTNode): String =
if (node.type == NodeType.LineBreak) {
" "
} else {
node.content + node.children.joinToString("") { extractPlainText(it) }
}
private fun textAlignmentFromString(align: String?): Layout.Alignment =
when (align) {
@@ -12,12 +12,11 @@ object MarkdownASTSerializer {
return buffer.toString()
}
fun serializeChildren(node: MarkdownASTNode): String {
/** A table row is one line, so a cell's line break goes back to `<br>`. */
fun serializeTableCell(cell: MarkdownASTNode): String {
val buffer = StringBuilder()
for (child in node.children) {
appendNode(child, buffer)
}
return buffer.toString()
appendChildren(cell, buffer)
return buffer.toString().replace("\\\n", "<br>")
}
/**
@@ -184,7 +183,7 @@ object MarkdownASTSerializer {
for (section in node.children) {
for (row in section.children) {
if (row.type != NodeType.TableRow) continue
val cells = row.children.map { serializeChildren(it) }
val cells = row.children.map { serializeTableCell(it) }
buffer.append("| ")
buffer.append(cells.joinToString(" | "))
buffer.append(" |\n")
@@ -24,6 +24,7 @@ import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem
import com.swmansion.enriched.markdown.test.TestAstFactory.text
import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList
import com.swmansion.enriched.markdown.utils.common.serialization.MarkdownASTSerializer
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -200,6 +201,20 @@ class BlockquoteCopyTest {
assertEquals("Inner", clipboardText())
}
@Test fun copyButtonKeepsAQuotedTableCellLineBreakInItsRow() {
val table =
node(
NodeType.Table,
node(NodeType.TableHead, node(NodeType.TableRow, node(NodeType.TableHeaderCell, text("Case")))),
node(
NodeType.TableBody,
node(NodeType.TableRow, node(NodeType.TableCell, text("first"), node(NodeType.LineBreak), text("second"))),
),
)
assertEquals("| Case |\n| --- |\n| first<br>second |", MarkdownASTSerializer.serializeBlockquoteBody(quote(table)))
}
@Test fun admonitionHasNoCopyButton() {
val view = quoteView()
view.applyBlockquoteNode(
@@ -22,6 +22,7 @@ public:
std::string currentText;
const char *inputText = nullptr;
bool inHtmlBlock = false;
bool inTableCell = false;
std::string htmlBlockContent;
static const std::string ATTR_LEVEL;
@@ -46,6 +47,7 @@ public:
currentText.clear();
currentText.reserve(256);
inHtmlBlock = false;
inTableCell = false;
htmlBlockContent.clear();
}
@@ -231,6 +233,7 @@ public:
case MD_BLOCK_TH:
case MD_BLOCK_TD: {
impl->inTableCell = true;
auto node =
std::make_shared<MarkdownASTNode>(type == MD_BLOCK_TH ? NodeType::TableHeaderCell : NodeType::TableCell);
if (detail) {
@@ -286,6 +289,10 @@ public:
return 0;
}
if (type == MD_BLOCK_TH || type == MD_BLOCK_TD) {
impl->inTableCell = false;
}
if (type != MD_BLOCK_DOC && !impl->nodeStack.empty()) {
impl->popNode();
}
@@ -431,6 +438,39 @@ public:
}
// Handle text content (normal text, code text, LaTeX math, etc.)
if (type == MD_TEXT_NORMAL && impl->inTableCell) {
constexpr const char kLineSep[] = "\xE2\x80\xA8";
constexpr MD_SIZE kLineSepLen = 3;
MD_SIZE pos = 0;
while (pos + kLineSepLen <= size) {
MD_SIZE match = size;
for (MD_SIZE i = pos; i + kLineSepLen <= size; ++i) {
if (std::memcmp(text + i, kLineSep, kLineSepLen) == 0) {
match = i;
break;
}
}
if (match == size) {
break;
}
if (match > pos) {
impl->currentText.append(text + pos, match - pos);
}
if (!impl->currentText.empty() && impl->currentText.back() == ' ') {
impl->currentText.pop_back();
}
impl->addInlineNode(std::make_shared<MarkdownASTNode>(NodeType::LineBreak));
pos = match + kLineSepLen;
if (pos < size && text[pos] == ' ') {
++pos;
}
}
if (pos < size) {
impl->currentText.append(text + pos, size - pos);
}
return 0;
}
if (type == MD_TEXT_NORMAL || type == MD_TEXT_CODE || type == MD_TEXT_LATEXMATH) {
impl->currentText.append(text, size);
}
@@ -49,6 +49,8 @@ static NSString *ENRMTablePlainTextFromNode(MarkdownASTNode *node)
{
if (!node)
return @"";
if (node.type == MarkdownNodeTypeLineBreak)
return @" ";
NSMutableString *buffer = [node.content mutableCopy] ?: [NSMutableString string];
for (MarkdownASTNode *child in node.children) {
[buffer appendString:ENRMTablePlainTextFromNode(child)];
@@ -163,7 +165,7 @@ static NSArray<NSArray<TableCellData *> *> *ENRMTableBuildRows(MarkdownASTNode *
cell.isHeader = isSectionHead || (cellNode.type == MarkdownNodeTypeTableHeaderCell);
cell.alignment = ENRMTableTextAlignmentFromString(cellNode.attributes[@"align"]);
cell.plainText = ENRMTablePlainTextFromNode(cellNode);
cell.markdownText = markdownFromASTNodeChildren(cellNode);
cell.markdownText = markdownFromTableCell(cellNode);
StyleConfig *cellConfig = cell.isHeader ? headerCellConfig : bodyCellConfig;
cell.attributedText =
@@ -13,9 +13,9 @@ extern "C" {
/// Handles inline elements: strong, emphasis, strikethrough, underline, code, links, images.
NSString *markdownFromASTNode(MarkdownASTNode *node);
/// Serializes only the children of a node to markdown (skipping the node itself).
/// Useful for extracting the markdown content of a container node (e.g. a table cell).
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node);
/// Serializes a table cell's content to markdown. A row is one line, so a cell's
/// line break goes back to `<br>`.
NSString *markdownFromTableCell(MarkdownASTNode *cell);
/// Serializes the blocks inside a Blockquote to markdown, without the quote's own
/// `> ` prefix. A quote nested inside keeps its prefix.
@@ -142,7 +142,7 @@ static void appendTableMarkdown(MarkdownASTNode *node, NSMutableString *buffer)
continue;
NSMutableArray<NSString *> *cells = [NSMutableArray arrayWithCapacity:row.children.count];
for (MarkdownASTNode *cell in row.children) {
[cells addObject:markdownFromASTNodeChildren(cell)];
[cells addObject:markdownFromTableCell(cell)];
}
[buffer appendFormat:@"| %@ |\n", [cells componentsJoinedByString:@" | "]];
if (!headerDone) {
@@ -321,13 +321,13 @@ NSString *markdownFromASTNode(MarkdownASTNode *node)
return [buffer copy];
}
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node)
NSString *markdownFromTableCell(MarkdownASTNode *cell)
{
if (!node)
if (!cell)
return @"";
NSMutableString *buffer = [NSMutableString string];
serializeChildren(node, buffer);
return [buffer copy];
serializeChildren(cell, buffer);
return [buffer stringByReplacingOccurrencesOfString:@"\\\n" withString:@"<br>"];
}
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4565,6 +4565,55 @@ describe("ClaudeAgentSession context window usage", () => {
}
});
test("shows Claude Code system notifications in the timeline and daemon log", async () => {
const logs: Array<{ level: number; msg: string; key?: string; text?: string }> = [];
const notification = (key: string, text: string, priority: string) => ({
type: "system",
subtype: "notification",
key,
text,
priority,
timeout_ms: 8000,
uuid: `uuid-${key}`,
session_id: "session-1",
});
const client = new ClaudeAgentClient({
logger: pino({}, { write: (line: string) => logs.push(JSON.parse(line)) }),
queryFactory: createQueryFactoryForTurns([
[
notification("code-mode-opt-in", "Code Mode isn't available.", "medium"),
notification("urgent", "Something needs attention.", "immediate"),
createSuccessResult(),
],
]),
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
try {
const events = await collectStreamEvents(session, "turn");
expect(
events.flatMap((event) =>
event.type === "timeline" && event.item.type === "notification" ? [event.item] : [],
),
).toEqual([
{ type: "notification", level: "info", message: "Code Mode isn't available." },
{ type: "notification", level: "warning", message: "Something needs attention." },
]);
expect(
logs
.filter((entry) => entry.msg === "claude.notification")
.map(({ level, key, text }) => ({ level, key, text })),
).toEqual([
{ level: 30, key: "code-mode-opt-in", text: "Code Mode isn't available." },
{ level: 40, key: "urgent", text: "Something needs attention." },
]);
} finally {
await session.close();
}
});
test("an interrupted compaction does not suppress the next compaction marker", async () => {
// The first turn starts compacting and is then interrupted, so it never reaches a
// compact_boundary and the marker it opened is never resolved.
@@ -5511,6 +5511,27 @@ class ClaudeAgentSession implements AgentSession {
if (message.subtype === "task_progress") {
return;
}
if (message.subtype === "notification") {
this.appendNotificationEvents(message, events);
return;
}
}
// Claude Code tells the user things here, such as a requested feature that did not start.
// A timeline row does not expire, so `timeout_ms` and `color` do not apply.
private appendNotificationEvents(
message: Extract<SDKMessage, { type: "system"; subtype: "notification" }>,
events: AgentStreamEvent[],
): void {
const urgent = message.priority === "high" || message.priority === "immediate";
const fields = { key: message.key, priority: message.priority, text: message.text };
if (urgent) this.logger.warn(fields, "claude.notification");
else this.logger.info(fields, "claude.notification");
events.push({
type: "timeline",
provider: "claude",
item: { type: "notification", level: urgent ? "warning" : "info", message: message.text },
});
}
private appendTaskNotificationEvents(
@@ -208,6 +208,35 @@ it.each([
},
);
it("clamps negative remaining counts and percentages when premium quota is exceeded", async () => {
const report = await fetchPremiumQuota({
entitlement: 20000,
remaining: -6,
percent_remaining: -0.03,
unlimited: false,
});
expect(report).toMatchObject({
status: "available",
planLabel: "individual",
windows: [
{
id: "premium_interactions",
label: "Premium requests",
usedPct: 100,
remainingPct: 0,
resetsAt: "2026-12-01T00:00:00.000Z",
},
],
details: expect.arrayContaining([
{
id: "premium_remaining",
label: "Premium requests remaining",
value: "0 / 20000",
},
]),
});
});
it.each([
undefined,
null,
+4 -4
View File
@@ -27,8 +27,8 @@ const CopilotUsageResponseSchema = z.object({
premium_interactions: z
.object({
entitlement: z.number().nonnegative().nullish(),
remaining: z.number().nonnegative().nullish(),
percent_remaining: z.number().min(0).max(100).nullish(),
remaining: z.number().nullish(),
percent_remaining: z.number().nullish(),
unlimited: z.boolean().optional(),
})
.nullish(),
@@ -122,7 +122,7 @@ export async function fetchUsage(
windowFromUsedPct({
id: "premium_interactions",
label: "Premium requests",
utilizationPct: 100 - premium.percent_remaining,
utilizationPct: Math.max(0, Math.min(100, 100 - premium.percent_remaining)),
resetsAt: resp.quota_reset_date_utc || resp.quota_reset_date,
}),
);
@@ -131,7 +131,7 @@ export async function fetchUsage(
details.push({
id: "premium_remaining",
label: "Premium requests remaining",
value: `${premium.remaining} / ${premium.entitlement}`,
value: `${Math.max(0, premium.remaining)} / ${premium.entitlement}`,
});
}
}