Skip to content

fix: bound session history load to a tail window (fixes #509, #555) - #587

Merged
agegr merged 7 commits into
agegr:mainfrom
Nuctori:fix/session-history-tail
Aug 25, 2026
Merged

agegr merged 7 commits into
agegr:mainfrom
Nuctori:fix/session-history-tail

Conversation

@Nuctori

@Nuctori Nuctori commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Bounds how much of a session is loaded when a session detail is opened, so deep/long sessions no longer crash or stall.

  • 对话较大加载刷新较慢 #500 (stack overflow / HTTP 500 on open): BranchNavigator walked the active path with recursion over an arbitrarily deep chain; rewritten as explicit-stack iteration. lib/session-reader already slices the chain, so the SDK recursion that previously overflowed is no longer on the open path.
  • Performance: page session detail history instead of returning the full active branch #555 (full-history transfer / slow open): detail + context APIs returned the entire entry forest. They now return only a tail window of the active branch, and support upward pagination via ?before, so opening a 5000-message linear session transfers ~50 messages instead of 5000.
  • extra crash found via real-browser E2E: long sessions with a string assistant content (not a block array) hit TypeError: message.content.map is not a function in entryToUiMessage. Guarded with an Array.isArray check.
  • Codex review fixes (P1/P2 on the earlier branch state): restore multi-root branch detection in hasBranch (iterative rewrite had dropped the nodes.length > 1 check); expand the rendered window so prepended (older) pages stay visible and the "load earlier" sentinel shows when the initial tail is a truncation.

Reproduce

A session with >3000 messages and no branches (a single linear chain). Open it:

  • before: GET /api/sessions/:id → HTTP 500. List page is fine.
  • after: detail returns 200 with context.messages.length === 50; scrolling up fetches ?before=<oldest> pages without duplicating the boundary.

Changed

  • lib/session-reader.ts: sliceActiveBranch (+excludeLeaf for page dedupe), buildSessionContext gains tail/excludeLeaf; entryToUiMessage guards string content.
  • app/api/sessions/[id]/route.ts, app/api/sessions/[id]/context/route.ts: ?tail (default 50, capped 1000, NaN-safe) and ?before pagination params.
  • hooks/useAgentSession.ts: loadContext(sid, leafId, before?) prepends older pages.
  • components/ChatWindow.tsx: top sentinel triggers loadContext for earlier history; rendered window expands to keep prepended pages visible.
  • components/BranchNavigator.tsx: buildActivePath/hasBranch recursion → explicit stack (with multi-root check).
  • Tests: lib/session-reader.pagination.test.mjs, app/api/sessions/detail-route.test.mjs, app/api/sessions/context-route.test.mjs, components/BranchNavigator.test.mjs (6000-deep chain + multi-root).
  • package.json: version 0.8.9 → 0.8.10.

Verification

  • npm test: with the harness fix from test: fix component-test harness dual React instance (35 -> 9 failures) #588 applied, 604 tests / 592 pass / 9 fail. The 9 remaining failures are platform-conditional (Windows symlink / PATH separator) or pre-existing brittle source-structure assertions — no regression from this change.
  • tsc --noEmit clean; ESLint clean on changed files.
  • Real-browser E2E (5000-message linear session): detail 200 + 50 messages, ?before pages without duplicate, no console/page errors (run manually; the CI E2E job lives in the CI PR).

Note

Closes #509. Closes #555.

…egr#555)

- slice branch chain to a tail window in buildSessionContext; add ?tail/&before pagination to detail + context APIs

- BranchNavigator recursion -> iterative (deep linear chains no longer overflow the stack)

- guard entryToUiMessage against string assistant content (real long sessions 500'd on content.map)

- ChatWindow sentinel + useAgentSession.loadContext prepend older pages

- e2e (playwright) + pagination tests
… data layers

- detail + context route tests assert ?tail parsing (default 50, NaN-safe, capped 1000) and ?before excludeLeaf wiring

- session-reader pagination tests add excludeLeaf page dedupe, string-assistant-content guard, and large-tail chain

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9780da2228

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread hooks/useAgentSession.ts
Comment on lines +537 to +540
if (before) {
// Older page: prepend so scroll position stays anchored.
setMessages((prev) => [...d.context.messages, ...prev]);
setEntryIds((prev) => [...d.context.entryIds, ...prev]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reveal prepended history pages

When before is set, this prepends the older page but ChatWindow still renders only getVisibleRenderWindow(rendered.length, visibleCount), with visibleCount left at the initial page size. For a long session, the prepended entries land before startIndex and are immediately sliced away, so scrolling up never exposes history older than the default tail (and an initial exactly-50-entry tail does not render the sentinel at all). The pagination path needs to expand/track the visible window or otherwise render the newly loaded page.

Useful? React with 👍 / 👎.

Comment on lines +107 to 110
const stack: SessionTreeNode[] = [...nodes];
while (stack.length > 0) {
const node = stack.pop()!;
if (node.children.length > 1) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve multiple root branches in the navigator

This iterative rewrite no longer treats nodes.length > 1 as a branch. Sessions branched from the first message have multiple root nodes (and selectTopLevelBranches still returns those roots), but hasBranch now returns false when each root has at most one child, causing the UI to show the no-branches state and hide the branch choices. Re-add the top-level nodes.length > 1 check before walking the stack.

Useful? React with 👍 / 👎.

Comment thread package.json Outdated
"katex": "^0.16.47",
"mammoth": "^1.12.0",
"mermaid": "^11.16.1",
"playwright": "^1.48.0",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the lockfile for Playwright

Adding playwright only to package.json leaves package-lock.json out of sync: the lockfile root still has no devDependencies.playwright entry and no node_modules/playwright package. Lockfile-based installs will not reproduce this dependency (or will fail while reconciling it), so the new top-level e2e scripts that import playwright cannot be run from a clean locked install. Please regenerate and commit the lockfile with this dependency and version bump.

Useful? React with 👍 / 👎.

@Nuctori

Nuctori commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Update: this branch now also fixes the component-test harness (see #586). React, react-dom/server, and the i18n provider are loaded through the same jiti instance the components use, and useI18n is imported via the @/ alias so I18nContext resolves to a single module — previously two React instances made every component test throw 'useI18n must be used inside I18nProvider'.

Suite: 603 tests, 591 pass, 9 fail (was 565/35). Remaining 9 = platform-conditional (symlink, Windows PATH separator) + pre-existing brittle source-structure assertions, not regressions. No product code changed by the harness fix.

@Nuctori
Nuctori force-pushed the fix/session-history-tail branch from b028e5f to 9780da2 Compare August 23, 2026 19:58
@Nuctori

Nuctori commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Split out the test-harness fix into its own PR (#588) to keep this one scoped to #509/#555. Reverted the harness commit from this branch.

…isibility, drop playwright dep)

- BranchNavigator.hasBranch: restore the multiple-root check (nodes.length > 1) that the iterative rewrite dropped; sessions branched from the first message have multiple roots and were misreported as branchless.

- ChatWindow: expand the rendered window to at least the loaded message count so prepended (older) pages stay visible instead of being sliced off the top, and show the 'load earlier' sentinel when the window is full (the initial tail is a truncation).

- package.json: remove the playwright devDependency that was added for local E2E probing; it does not belong to this fix and left package-lock.json out of sync.

- test: cover hasBranch for multiple-root trees.
@Nuctori

Nuctori commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all three P2 items in 7c9b27f:

  1. Reveal prepended history pages — fixed. ChatWindow now keeps the rendered window at least as large as the loaded message count (Math.max(visibleCount, messages.length)), so prepended older pages are no longer sliced off the top. Also shows the 'load earlier' sentinel when the window is full (the initial tail is a truncation), so the first page can always be fetched.
  2. Preserve multiple root branches — fixed. hasBranch iterative rewrite had dropped the
    odes.length > 1 check; restored it. Sessions branched from the first message (multiple roots) are now correctly reported as branched. Added a test for this case.
  3. Lockfile for Playwright — removed. playwright was only added locally for E2E probing and does not belong to this fix; dropped it from package.json (it was never in the upstream lockfile, so there is nothing to regenerate).

…ripts from the PR

- a previous edit accidentally replaced the mermaid devDependency with a duplicate postcss entry; restored mermaid and removed the duplicate.

- e2e_browser.mjs/e2e_click.mjs/e2e_trace.mjs were temporary local probes and should not be in this PR; removed from the tree (kept locally, gitignored).
@Nuctori

Nuctori commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

PR cleaned up: restored the mermaid devDependency (a previous edit had accidentally replaced it with a duplicate postcss entry) and dropped the temporary local e2e probe scripts (�2e_browser.mjs etc.) from the tree. Body now states the dependency on #588 for the component tests to pass on a clean checkout.

@agegr
agegr merged commit 68cd261 into agegr:main Aug 25, 2026
magnum-pr pushed a commit to magnum-pr/pi-web that referenced this pull request Sep 27, 2026
…egr#555) (agegr#587)

* fix: bound session history load to a tail window (fixes agegr#509, agegr#555)

- slice branch chain to a tail window in buildSessionContext; add ?tail/&before pagination to detail + context APIs

- BranchNavigator recursion -> iterative (deep linear chains no longer overflow the stack)

- guard entryToUiMessage against string assistant content (real long sessions 500'd on content.map)

- ChatWindow sentinel + useAgentSession.loadContext prepend older pages

- e2e (playwright) + pagination tests

* chore: bump version to 0.8.10

* test: cover tail/before pagination and 1000-tail cap at the route and data layers

- detail + context route tests assert ?tail parsing (default 50, NaN-safe, capped 1000) and ?before excludeLeaf wiring

- session-reader pagination tests add excludeLeaf page dedupe, string-assistant-content guard, and large-tail chain

* fix: address Codex review on pagination branch (multi-root, prepend visibility, drop playwright dep)

- BranchNavigator.hasBranch: restore the multiple-root check (nodes.length > 1) that the iterative rewrite dropped; sessions branched from the first message have multiple roots and were misreported as branchless.

- ChatWindow: expand the rendered window to at least the loaded message count so prepended (older) pages stay visible instead of being sliced off the top, and show the 'load earlier' sentinel when the window is full (the initial tail is a truncation).

- package.json: remove the playwright devDependency that was added for local E2E probing; it does not belong to this fix and left package-lock.json out of sync.

- test: cover hasBranch for multiple-root trees.

* fix: restore package.json mermaid dep and drop temporary e2e probe scripts from the PR

- a previous edit accidentally replaced the mermaid devDependency with a duplicate postcss entry; restored mermaid and removed the duplicate.

- e2e_browser.mjs/e2e_click.mjs/e2e_trace.mjs were temporary local probes and should not be in this PR; removed from the tree (kept locally, gitignored).

* fix: complete bounded session pagination

---------

Co-authored-by: Nuctori <Nuctori@users.noreply.github.com>
Co-authored-by: Alex Yang <agegcn@gmail.com>
agegr added a commit that referenced this pull request Oct 9, 2026
…ion switches (#988, #1031, #877, #896) (#1114)

* fix(chat): clear the retry banner once the retried run starts (#988)

pi emits a successful auto_retry_end only at the retry's first complete
assistant message, so the banner said "Retrying" through the whole retried
reply. pi's TUI drops its retry indicator when that run starts; clear it on
the run's agent_start the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): read context usage when the event stream connects (#1031)

Opening a session's event stream is what resumes a wrapper the idle timeout
reaped, so the mount's state read often finds no runtime and leaves the
context percentage blank. Since #1058 a run fills it in after its first
reply; read it on `connected` too, through the same ordered usage read, so
it shows as soon as the runtime is back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep a streaming reply's t/s start across session switches (#877)

The start of the tokens-per-second measurement lived in the message view,
which a session switch remounts. Back on a running session, the new view
took its start at the remount and divided every token streamed so far by
half a second, showing thousands of t/s. Keep the start per reply (provider,
model and request timestamp) outside the view; a reply joined with no record
(a reload) times only the tokens that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): reveal loaded rows the history window still hides (#896)

The window keeps as many rows as messages are loaded, but a turn's answer
and its thinking render as two rows, so a thinking-heavy session hides its
oldest loaded rows behind "Load earlier messages". Since #587 the sentinel
only fetched from the server, so with no older page there, reaching it did
nothing. Widen the window in that case again, renew the observer when it
grows, and observe the sentinel whenever it mounts, not only when the
history cursor changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
dreadster3 added a commit to dreadster3/pi-web that referenced this pull request Oct 11, 2026
* fix(build): keep .claude worktrees out of Tailwind's source scan

Tailwind's automatic detection scanned .claude/worktrees, so webpack
snapshotted those directories too. A worktree whose node_modules is a
symlink to another worktree's node_modules yields a context entry with
no hash, and `next build --webpack` crashed in WasmHash.update with
"Cannot read properties of undefined (reading 'length')".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(markdown): stop clipping two-digit ordered list numbers

The bold outside marker of "10." and up is wider than the list's 22px
padding, and .markdown-body's overflow-x: hidden cut off its left side.
Ordered lists now size their padding from the digit count of their
largest number (at least two), which MarkdownBody passes as
--ol-marker-digits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): let the compaction error above the composer be dismissed (#784) (#1109)

A failed or refused compaction ("Nothing to compact (session too small)")
left its red banner above the input until the next compaction started, with
no way to close it. The banner now has the same close button as other inline
errors.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): hide display:false custom messages; anchor turns on pi-subagents' completion notice (#1043, #1075) (#1110)

* fix(chat): hide custom messages sent with display:false (#1043)

pi's TUI renders a custom message only when `display` is set; extensions
use display:false for context meant for the model alone. pi-web drew each
one as a collapsed "hidden extension message" card, and an extension that
sends one on every session_start added a card on every idle restart.

They stay in the history, so entry ids stay aligned, but render nothing,
are not counted in Process details and never anchor a turn. The collapsed
card and its two strings go with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): anchor a turn on @tintinweb/pi-subagents' completion notice (#1075)

@tintinweb/pi-subagents reports a finished background agent as a displayed
custom message of bare type `subagent-notification`, sent as a follow-up
that triggers a new run, exactly like pi-web's own
`pi-web:subagent-notification`. It was not an anchor, so the reply to it
became the turn's final answer and the earlier complete answer folded
into Process details.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(models): list models in pi's /model order, not by name (#783) (#1111)

The route and ModelSelector both sorted models by display name, so a
models.json provider lost the order its file gives. pi's TUI selector
never sorts by name: a scope keeps its enabledModels order, and the full
list is sorted by provider id only, keeping the registry (file) order
within each provider. The name sort came in as a side change of #80.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(models): keep capability metadata from Fetch models (#856) (#1112)

Fetch models kept only id and name, so a gateway's published context
length, output limit and reasoning support never reached models.json and
the added models fell back to pi's defaults with no thinking levels.
Map only fields whose meaning does not vary between gateways onto
contextWindow, maxTokens and reasoning, and an advertised effort list
naming pi's levels onto thinkingLevelMap (other levels null, off left
alone). max_tokens and default_effort stay out as ambiguous; junk
values are dropped, and a list without metadata parses as before.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(models): show Kimi For Coding usage quota (#848) (#1113)

PROVIDER_USAGE_IDS gains kimi-coding with an adapter for
GET https://api.kimi.com/coding/v1/usages, on the same origin as the
provider's base URL. The overall quota and each rate-limit window become
count buckets with their reset time; the parallel-request limit and
membership level become metrics. Both an API key and a Kimi Code OAuth
credential reach the endpoint as a Bearer token through the existing
query path. The mapping follows the response sample in the issue; it
was not checked against the live endpoint.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): retry banner, context %, t/s and history window after session switches (#988, #1031, #877, #896) (#1114)

* fix(chat): clear the retry banner once the retried run starts (#988)

pi emits a successful auto_retry_end only at the retry's first complete
assistant message, so the banner said "Retrying" through the whole retried
reply. pi's TUI drops its retry indicator when that run starts; clear it on
the run's agent_start the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): read context usage when the event stream connects (#1031)

Opening a session's event stream is what resumes a wrapper the idle timeout
reaped, so the mount's state read often finds no runtime and leaves the
context percentage blank. Since #1058 a run fills it in after its first
reply; read it on `connected` too, through the same ordered usage read, so
it shows as soon as the runtime is back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep a streaming reply's t/s start across session switches (#877)

The start of the tokens-per-second measurement lived in the message view,
which a session switch remounts. Back on a running session, the new view
took its start at the remount and divided every token streamed so far by
half a second, showing thousands of t/s. Keep the start per reply (provider,
model and request timestamp) outside the view; a reply joined with no record
(a reload) times only the tokens that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): reveal loaded rows the history window still hides (#896)

The window keeps as many rows as messages are loaded, but a turn's answer
and its thinking render as two rows, so a thinking-heavy session hides its
oldest loaded rows behind "Load earlier messages". Since #587 the sentinel
only fetched from the server, so with no older page there, reaching it did
nothing. Widen the window in that case again, renew the observer when it
grows, and observe the sentinel whenever it mounts, not only when the
history cursor changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(subagents): admit tools extensions register at session_start (#883) (#1115)

A child got a `tools` allowlist of the extension tools registered when it
was built. The SDK fixes that list at session creation, so a tool an
extension registers at session_start or later (pi's dynamic-tools example)
was never callable, even with extensions loaded.

A child that loads extensions without `ext:` selectors now gets no
allowlist: `noTools: "builtin"`, its built-ins as `+name` entries, and the
other built-ins and the reserved subagent tools excluded, so an extension
still cannot switch on a built-in the profile leaves out. The snapshot
records this so reload and reopen behave the same. `ext:` selectors keep
the name allowlist: the SDK admits tools by name only and offers no
source-aware hook.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(worktrees): group a bare clone's worktrees under the clone (#1049) (#1116)

A worktree's project root was the parent of its common git dir. For a
bare clone (`parent/repo.git`) that parent is the folder holding every
clone, so the worktrees of all repos there fell into one project (and
that folder became an allowed file root), while the clone itself was a
project of its own with none of its sessions. New worktrees were added
from that parent too, which is no repository.

A bare clone is now its own root, unless a `.git` file beside it points
at it (the `project/.bare` layout keeps the enclosing folder). Removed
worktrees under `repo.git-worktrees/` are still inferred back into it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(markdown): keep links to common desktop apps (obsidian://, vscode://, zoommtg://) (#1108) (#1118)

The sanitize schema allowed only web, mail and file: links, so links such as
obsidian://open?vault=... lost their href and rendered as dead text in chat
and in the file preview. A fixed list of note, editor and meeting app schemes
now passes both the schema and the URL transform. It is an allowlist rather
than "anything but javascript:" because the text comes from the model and
from repository files, and OS handlers such as ms-msdt: and search-ms: have
been exploited through clicked links.

These links open in a new tab with noopener/noreferrer like other external
chat links. The file preview now does the same for its web and app links,
which used to replace Pi Web in the current tab; relative, in-page and local
file links are unchanged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* perf(server): start the pi SDK import at startup, not on the first request (#964) (#1117)

Next preloads route chunks at start, but evaluates a route's code, and with
it the externalized pi SDK, only on the route's first request. The first
/api/sessions therefore paid for importing ~1600 SDK modules (seconds on
Windows with antivirus scanning). register() now starts that import without
awaiting it, so it overlaps the browser opening and routes reuse the cached
module.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): clear errors for a deleted project folder and Chat only's extension models (#1061, #804) (#1119)

* fix(chat): refuse prompts in a deleted project folder with a clear message (#1061)

A session whose cwd was deleted outside pi-web still starts its wrapper
(selecting it opens the event stream), and a prompt then went on to the
model, whose tools all fail there; pi's write tool would even recreate
the folder. The pi CLI does not resume such a session. The wrapper now
refuses the prompt with "Directory does not exist: <cwd>", the text
/api/agent/new already answers for a fresh composer, and the composer
keeps the draft.

That answer never reached the user either: ensureNewSession() threw a
bare "HTTP 400". It now passes the server's error on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): say when Chat only cannot load an extension's model (#804)

Chat only loads no extensions, so providers they register are missing from
the session while the model selector's listing still offers them. Picking
one failed with a bare "Model not found", a chosen model was silently
replaced at start, and a session left with no model at all failed with
pi's "No API key found".

The session now names the model as an extension's that Chat only cannot
load: set_model and a start with the chosen model refuse it, and a prompt
in a session that could start on no model names the one it wanted. The
composer shows the server's reason when creating the session fails. Chat
only still loads no extensions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep terminal QR codes in extension notices intact (#755) (#1120)

pi-wechat-assistant's /wechat login sends a qrcode-terminal QR code (█ ▀ ▄
and runs of spaces) through ctx.ui.notify(). The toast's pre-line collapsed
the runs of spaces, its UI font gave spaces and blocks different widths and
its 1.5 line height opened gaps between rows, so the code came out garbled.
Lines drawn with block characters now render as pi's TUI shows them: spaces
kept, rows touching, one monospace font for spaces and blocks.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): stop re-rendering every answer on each custom panel keystroke (#1005) (#1121)

Each key typed into an extension's custom panel round-trips to the server
in a few ms, but the render it sends back re-renders ChatWindow, and a
grouped turn handed MessageView fresh copies of its final message and a
fresh written-files list on every render. That defeated MessageView's memo,
so every visible answer ran its markdown again per keystroke (and per
streamed chunk or notice). The copies and the list are now kept per stored
message, so an unchanged transcript re-renders no MessageView: in a dev
build with a 400-message session the key-to-paint time went from ~71 ms
to ~20 ms, and real answers with code and math save far more.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(chat): collapse the compaction summary by default, as pi's TUI does (#1026) (#1123)

The compaction card always rendered the whole summary, which can run to
pages. pi's TUI shows it collapsed to "Compacted from N tokens" and
expands it on click; the card now does the same: the header, the title
and the token count stay, and the title is a button (aria-expanded) that
reveals the description, the summary and the file lists. Session search
never targets a compaction entry, so nothing needs to force it open.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(chat): attach any file from the composer's button, not only images (#1101) (#1122)

On a phone there is no drag and drop, so the only way to give the chat a
PDF or a log was the attach button, which took images only. The button's
file input now has no accept list and hands the whole selection to
ChatWindow, which runs it through the chat drop handler: images attach to
the prompt as before (limits, compression, the image-support warning),
other files are uploaded into the working directory with conflict=skip
and mentioned, with the same notices, including the one when there is no
working directory. No capture attribute, so phones still offer photos and
the camera.

The button reads "Attach files", and the no-directory notice says
"adding" rather than "dropping" since it now covers both.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): stop prepending the same older page twice (#1149)

Scrolling up a long session could show a page of older messages twice.
The page lands, and loadingOlderRef clears, a moment before React renders
the next cursor; a sentinel report in between (a renewed observer's first
one) still held the old cursor and fetched the same page again. #1122's
e2e failed on it (before=e4850 requested twice). The cursor asked for is
now kept until another one renders, and the observer skips it; a page that
failed, or a cursor a reload brings back, can still be asked for.

Repeating the e2e's pagination steps in headless Chromium at 6x CPU
throttling: main requested a page twice and showed 50-150 duplicate rows
in 3 of 10 runs; this branch in 0 of 30.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep Process details open when a turn ends in an error (#906) (#1124)

A turn of [text + trailing tool call] followed by empty error replies
has no answer to show: the final answer lookup falls back to the last
error, whose notice made the turn count as answered, so Process details
started collapsed and hid the only text the turn wrote. They now start
collapsed only when the shown answer has text or an image
(collapsesProcessDetails); an error or truncation notice alone keeps
them open. The notice itself renders as before.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): rename a project's display name from its group menu (#1047) (#1125)

* feat(sidebar): rename a project's display name from its group menu (#1047)

Deep project paths make poor labels. A project group's menu now offers
Rename… (the header becomes the session row's inline field: Enter or blur
saves, Escape cancels) and Reset name while one is set. The name is a
label only, kept in pi-web-session-state.json as projectNames, keyed by
projectKey like the pins: it never touches the folder, the sessions, the
order, pins or expansion, and never selects the project.

One shared rule (projectDisplayName) serves the request parser, the
optimistic apply and the file: trimmed, one line, at most 80 code points;
empty or null clears. The names keep to 1000 entries and 256 KiB as JSON;
a new name with no room left is not stored and the route answers 409
"full". Old files load unchanged; a malformed field reads as none.

The name replaces the folder name in group headers, the drag ghost,
pinned rows and the archive's group headers, and the path in the project
pickers' box (files tab and the new-session bar); their menus show it
with the folder as the note. The full path stays the tooltip, so the
filter matches name, folder and path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sidebar): a named project shows its name alone in the project pickers

The pickers' menus no longer note a named project's folder, on a desktop
or a phone: the name stands alone, the full path stays the tooltip (and
the filter still matches it). On a desktop the name takes the paths' code
type in the menu, and in the box everywhere, as the path it replaces did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(files): restore file tabs when returning to a workspace (#1107)

* fix(files): restore tabs when returning to a workspace

Preserve project isolation from PR #281 while parking each workspace's tabs instead of discarding them.

* fix(files): route a parked viewer's last state to its own workspace

The unmount save looked the tab id up in every parked workspace and also
in the live tabs, so with the same file open in two projects one project's
mode/wrap/scroll overwrote the other's. Tag each report with the workspace
generation the viewer rendered in (also part of its key), keep only left
workspaces in the parked map, and note the behaviour in sessions.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* minimap: add lock toggle that disables the hover preview (#1128)

* minimap: add lock toggle that disables the hover preview

* minimap: center the lock button, enlarge it, and make it gold when locked

* minimap: remember the lock and keep the last node clear of the lock button

- The lock lived in component state, and ChatWindow remounts per session,
  so it reset on every session switch and reload. Keep it in localStorage
  (best-effort, lib/minimap-preview-lock.ts) with a test.
- With many turns the last node sat at the bottom 12px of the rail, under
  the 30px lock button, so a click meant for the latest turn toggled the
  lock instead. Reserve the button's height below the nodes.
- aria-pressed carries the state, so the accessible name stays constant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(subagents): add opt-in codemode support (#1097)

* feat(subagents): add opt-in codemode support

* fix(subagents): keep Code mode on children without ext: selectors, and unselected MCP tools out of scripts

Since #883 a child that loads extensions without `ext:` selectors gets
`noTools: "builtin"` with its built-ins as `+name` entries. `codemode`
registers inactive, so it never came on there; it is now named too.

A child with an allowlist kept every MCP tool the list did not name
registered: pi keeps them for codemode scripts and tool_search, as with
`--tools`. A codemode script could then call an `mcp__*` tool from an
extension the profile did not select. Such an allowlist now excludes
the MCP tools it does not name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(subagents): trim the subagent Code mode wiring

- `createSubagentCodemodeExtension()` replaces the general
  `createPiWebCodemodeExtension()`: normal sessions keep their original
  `builtin:codemode` entry, and the eager settings read that no caller
  reached is gone. It throws when the sandbox is unavailable.
- Scripts keep codemode's `models` API, as in pi and normal sessions: it
  is not a tool and grants nothing the profile's tools limit.
- The PUT route no longer repeats the codemode check
  `saveSubagentProfile()` already makes before writing.
- docs: inherit, the MCP exclusion and the trimmed wiring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sessions): discover external session files without manual refresh (#1100)

* fix(sessions): discover external session files without manual refresh

* fix(sessions): reconcile file membership across watch event types

* fix(sessions): find external sessions from the running poll instead of fs.watch

Replace the recursive session-directory watcher with a filename check
started from getSessionListVersion(), which the sidebar's running poll
calls every 2.5 s. The check lists sessions/<cwd>/*.jsonl (directory reads
only) at most once a second, one at a time, and invalidates the list only
when the set differs from what the last scan listed. Appends never change
a filename, so running sessions cause no rescans. A scan that records its
listing while a check reads wins over that check, so a stale read never
bumps the version.

A recursive fs.watch on Linux is Node's JS layer: one inotify watch per
file, a synchronous walk of the whole tree when it starts, and a silently
partial watch at the inotify limit; on macOS it reports appends as rename.

Keeps the contributor's real-route integration test (an independent SDK
writer creating, appending and deleting) and adds unit tests for the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: arkk <llggg2323@163.com>
Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(http): apply settings' httpIdleTimeoutMs to the Web UI (#1127)

* fix(http): apply settings' httpIdleTimeoutMs to the Web UI

`registerNodeInstrumentation` called `configureHttpDispatcher()` with no timeout, so the Web UI always used the built-in five minutes and ignored the user's `httpIdleTimeoutMs`. A provider stream that stayed quiet for longer was aborted with a bare `terminated`, while the same setting applied correctly to CLI sessions.

Read the agent directory's `settings.json` the way the CLI does and pass the value to the dispatcher, so both surfaces honor one setting.

* fix(http): resolve PI_CODING_AGENT_DIR exactly as pi's getAgentDir()

The local resolver trimmed the value, expanded ~\ on every platform, and
skipped pi's Windows shell-path and file: URL handling, so some values
pointed the settings read at a different directory than the SDK uses.
Port normalizePath()'s steps and check them against getAgentDir().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): centre a one-line notice in its card (#1130)

* fix(chat): centre a one-line notice in its card

A notice's card is 60px tall - what its entrance and exit keyframes pin it to -
while the text inside padded 14px above and below its 21px line box. Under
flex-start there is nowhere for the 9px the min-height leaves over to go but
below the text, so a one-line notice (an extension's ctx.ui.notify, "Default
model: ...", a completed upload) drew its line 4.5px above the middle of the
card: 15px above that line, 24px below it.

The text's padding is what centres it now. Two 18.5px paddings and the 21px
line box, between the card's two 1px borders, add up to exactly the 60px the
keyframes pin, so the line lands dead centre; the type dot keeps its offset
from the text's first line (padding + (21px line box - 7px dot) / 2) and goes
with it.

- Wrapped notices keep the dot on their first line and stay top-aligned; their
  padding grows by the same 4.5px per side, so their room above the first line
  and below the last is symmetric too (a three-line notice is 9px taller).
- NOTICE_TEXT_MAX_HEIGHT_PX follows that padding, so the text area still fits
  the 500px card.
- demo/components/ChatWindow.tsx carries the same NoticeShelf; kept in sync.

Measured on the component in a dev render, with the pre-fix inline styles
applied for the "before" row, one line: before - card 60px, 15px above the line
and 24px below it, line centre 25.5 against the card's 30; after - card 60px,
19.5px / 19.5px, line, card and dot centres all 30.

Tests: components/ChatWindow.notices.test.mjs adds the centring invariant
(padding twice + line box + the two borders = the height globals.css pins, so
the two cannot drift apart) and the dot's offset. Its existing span assertion
read [^}]* up to overflowY, which the now-interpolated padding closes early, so
it skips the braces lazily now.

* fix(chat): let a long notice's text use the card's whole 500px cap

Every box is border-box, so the text's max-height already holds its own
padding; subtracting the padding again capped the card at 463px. Pin the
21px line box to the card's font size and line height in the test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: leonjlfeng <leonjlfeng@tencent.com>
Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(files): show CSV/TSV files as a table in the file viewer (#1150)

* feat(files): show CSV/TSV files as a table in the file viewer

A .csv or .tsv file now opens in the viewer's Preview mode as a table,
the way markdown and HTML open rendered; Source stays one click away.

- lib/delimited-table.ts: a small RFC 4180 parser (quoted delimiters,
  doubled quotes, line breaks inside quotes, LF/CRLF, BOM, blank lines
  skipped; lenient with stray quotes and ragged rows). .tsv splits on
  tabs; .csv detects ; / tab / | from its first records, else comma.
- The gutter shows the file line each record starts on, so multi-line
  records do not shift the numbering.
- Large files: the table also previews a truncated first chunk, leaving
  out the cut last record until "Load more" brings the rest.
- Fixed-height rows, only those around the viewport rendered, inside the
  viewer's own scroll box (scroll position saved like the source view).
  No new dependencies.

Adapted from the table part of #1136.

Co-authored-by: Brynne Taylor <7542439+brynne8@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(agents): record the CSV/TSV table view

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brynne Taylor <7542439+brynne8@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(chat): number minimap turns from the session's first turn (#791) (#1151)

The minimap numbered turns by their index in the loaded page, so loading
older history renumbered every node and nothing showed that earlier turns
existed. Each context page now carries `turnsBefore`, the turn anchors on
the branch above its oldest entry (counted with isMessageGroupAnchor()),
and the minimap numbers loaded turns from it. While turns are unloaded the
rail shows a dotted stub above its first node and the preview's first row
says how many, scrolling the chat to the top when clicked.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep Stop clear of the slot compaction lands in (#1131)

* fix(chat): keep Stop clear of the slot compaction lands in

The bottom bar rebuilt itself at every run boundary: idle was
`[reasoning][tools][compact][sound]`, streaming dropped tools and compact for
`[reasoning][Stop][sound]`. Compact is wider than Stop and both anchored to the
sound toggle's left edge, so the second click of a double click on Stop landed on
Compact and rewrote the session context with nothing to confirm it. Stop is the
cheap, recoverable action; compaction is the consequential one, and it had
inherited the hot position.

- Stop moves to the composer's right end, where Send and the queue controls already
  swap. Steer and Follow-up become one split button keyed to the defaults the
  keyboard already uses — Enter steers, Alt/Option+Enter follows up — so the row the
  eye is on holds one primary action plus the emergency square. Phones get the
  bigger win: Stop was inside the More controls popup during a run, two taps away.
- The bottom bar no longer reflows. Tools and compact keep their slots and go inert
  while the run holds them, and a disabled button's wrapper carries the tooltip a
  disabled button cannot show.
- The compaction control still aborts compaction rather than the prompt when a turn
  auto-compacts, which is the trap the old gate existed for.
- Both hints name the delivery point pi actually reaches in `agent-loop.js`: the
  steering poll after the current reply's tool batch, and the follow-up drain where
  the loop would otherwise stop. The wording avoids "turn", which readers do not
  parse.
- `docs/agents/sessions.md` gains the invariant — nothing may move under the pointer
  at a run boundary — with the two tests that fail if a refactor reintroduces the
  collision, since no note owned the composer's action row before.

* fix(chat): ignore stray clicks on Compact right after a run ends (#1131)

Stop and Compact both sit just left of the sound toggle, and Compact is
wider than Stop, so when a run ends Compact covers Stop's whole slot. The
second click of a double click on Stop (or a click aimed at Stop as the
run ends on its own) started a compaction nobody confirmed.

Keep the composer's layout and controls as they are and ignore pointer
clicks on Compact and the tools button for 600 ms after a run ends.
Keyboard activation (click detail 0) and Stop compaction are unaffected.
The same handlers serve the phone's More controls popup, which stays
open across the run end and had the same hazard.

This replaces the composer redesign of the earlier commit: its split
Steer/Follow-up button, the moved Stop and its i18n and docs changes are
reverted to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(chat): collapse a custom message from its header (#1133)

* feat(chat): collapse a custom message from its header

A displayed custom message with no `details` could never be collapsed. One button
served both roles: it toggled the body only for a hidden message and the details
otherwise, and it appeared only when `details` existed — so every
`display: true` notice with no details was stuck expanded for the whole transcript.

- The header is the toggle (`aria-expanded`, a chevron like a tool card's), so the
  collapsed preview line is reachable for any message with text.
- The footer button is about details only (`hasDetails && !isHiddenDisplay`), which
  is what its label says.
- A test in `components/MessageView.test.mjs` pins the header toggle and the
  details-only footer.

* docs(agents): record how custom messages collapse

`sessions.md` gains the collapsing rule: the header is the toggle, the footer
button is for details only, and why the old single button left some messages
impossible to collapse. `AGENTS.md` points at the note.

* style(chat): put the custom message's chevron at the far right of its header

It sat right after the title while every tool card puts the toggle last, with the
duration just before it. The timestamp moves inside the header button so the
chevron can stay the final element.

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): show a session parked on an extension dialog as awaiting input (#1145)

* feat(sessions): report a run parked on an extension dialog

A run blocked on an extension's ui.select/confirm/input/editor (or an open
custom overlay) is still isRunning(), so the sidebar showed it as running
forever: the spinner never stopped, and nothing said the session was waiting
for a person. The pending requests were already in the wrapper; only the poll
never mentioned them.

AgentSessionWrapper.isAwaitingInput() gates on isRunning() and then asks the
protocol's own classification (isBlockingExtensionUiRequest), so no extension
has to adopt a pi-web convention, and notify/setStatus/setWidget/setTitle never
read as awaiting. A custom overlay that outlives its turn is not a parked run.
/api/agent/running and /api/sessions carry awaitingInputSessionIds beside
runningSessionIds, the sidebar's two sources for the running set.

The classification moves to lib/extension-ui-queue.ts, where the dialog queues
live, and browser-notifications.ts re-exports it: the attention notification
and the sidebar badge share one rule.

* feat(sidebar): show a parked run with an amber breathing dot

The right column says the one thing worth knowing, and for a parked run that is
"this needs you", not "this is working". The row takes the unread dot's shape
and 1.6s breath in warning amber (#d97706) and puts it in the spinner's slot:
same size, same animation, so only the colour and the meaning change. The label
is "Agent waiting for your input" in en, zh-CN and zh-TW, and the keyframes
rename to session-tree-status-pulse, which both dots now share.

It stays a running row everywhere else: is-running still keeps the meta beside
the hover actions, still withholds the archive button, and the group and
pinned-header counts still count it, while the archive predicate is untouched.
Both sources of the running set (the 2.5s poll and the session-list fallback)
carry the awaiting ids through the same sameIdsOr, so rows never rebuild just
because a session started waiting.

* docs(agents): note the awaiting-input poll and the amber row dot

sessions.md gains the rule behind the poll's awaitingInputSessionIds: which
methods count, the isRunning gate, why the wrapper's own pending requests are
the source, and that a background session's own event stream has no listener.
The row's right column now names the amber dot first.

* refactor(sidebar): make awaitingIds optional so unrelated tests stay untouched

The tree input's awaitingIds is now optional (absent means none), and
familiesToArchive() no longer names it. That reverts the incidental edits
to fork-route, useGroupDrag, SessionSidebar, SessionTree, session-tree and
sidebar-actions tests and the unused isAwaitingInput fakes; only the fake a
running poll actually calls keeps it. Also realigns the AGENTS.md file-map
entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Mangome <7655737+Mangome@users.noreply.github.com>
Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(subagents): answer a removed worktree from the repo it branched from (#1137)

* fix(subagents): answer a removed worktree from the repo it branched from

A subagent run isolated in a worktree records that worktree as its session's cwd,
and `cleanupWorktree()` removes the directory once the run reaches a terminal
status. The session file outlives the directory, so opening a finished subagent
asked two project-scoped questions about a folder that is no longer there:

- `GET /api/models` stat'd it and answered 400 "Directory does not exist", which
  `useAgentSession` surfaces as a model error. The model was fine.
- `GET /api/project-trust` refused it as 403 "Access denied", because
  `validateMcpProject()` authorizes a folder by resolving it
  (`isExistingFilePathAllowed()`), and a path that is gone resolves to nothing
  whichever root it sits under. It was not outside the roots:
  `getAllowedFileRoots()` derives a root from every session's own cwd, so the
  refusal came from the missing directory, not from the containment test.

Both routes now answer for the repo the worktree branched from, reusing the
`inferRemovedWorktree()` the session list already groups these sessions under:
the models route reads that repo's model list and the trust GET its trust
status, so a finished subagent resolves what a non-isolated one would and the
trust banner stops logging a refusal it could not act on.

That inference names exactly one folder — the cwd's parent with a `-worktrees`
suffix stripped, where `addWorktree()` puts worktrees, and only when that
sibling is a repository. It cannot be `git worktree list`: `git worktree remove`
deletes the directory *and* its admin entry, so nothing is left to ask. Each
route then authorizes the repo it landed on with the check it applies to any
cwd, so the fallback answers for no project the caller could not already name,
and never for a folder that is not an allowed root.

Only the trust read falls back. POST still refuses a folder that is gone, since
trusting records a decision about a directory that has to exist.
`validateMcpProject()` is untouched: its "a folder outside the roots answers the
same whether or not it exists" rule is what keeps `/api/mcp` and its test and
sign-in routes from turning a status code into a probe for which paths exist.

`app/api/models/route.test.mjs` is new — the route had no test, and the repo the
fallback answers from, a repo it must not answer from, and a missing folder that
is not a removed worktree are three different answers.

* fix(project-trust): keep the trust read on the folder asked about

Answering GET /api/project-trust for the repo a removed worktree branched
from reported another folder's trust (trust is per path, and the repo does
not contain `<repo>-worktrees/`). When that repo needs trust and is not
trusted, the composer then offered a Trust button whose POST, still asked
about the removed folder, is refused with 403 cwd-denied. On main the GET's
403 shows nothing, so the trust fallback is dropped; /api/models keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(subagents): let the profile decide the spawn parameters (#1138)

* fix(subagents): let the profile decide the spawn parameters

The `Agent` tool offered eleven parameters, but a model can choose only six of
them correctly, and it never saw what a profile had configured: the tool
description lists each profile's name, description, tools and model, while
`max_turns`, `thinking`, `inherit_context` and `input_files` were accepted with
no mention at all. The runtime resolved every one as `request ?? profile`, so a
guess beat a configured profile — a guessed `max_turns: 8` replaced the turn
budget the profile had set, and a guessed `thinking: "high"` short-circuited the
`??` chain before the parent's level was ever read. `input_files` inlined whole
files into the delegated task although a subagent's default tools already
include `read` and `bash`.

- The tool offers only `subagent_type`, `prompt`, `description`,
  `run_in_background`, `resume` and `isolation`, the last narrowed to a
  `"worktree"` literal since `"none"` was already dropped silently.
- The runtime reads `model`, `thinking` (falling back to the parent's level),
  `max_turns` and `inherit_context` from the profile alone; resume still rejects
  the one remaining creation option.
- The Agents panel and the profile file format are untouched: they remain the
  only place any of these values is edited.

* fix(subagents): let a call override the subagent's model

Withdrawing `model` with the other spawn parameters made a per-run model
impossible: a profile pinned to one model had no way to send a single task to a
different one, which is a real request — a cheap model for mechanical work, a
stronger one for a review.

- Restores exactly what that change took away, for `model` alone: the parameter
  on the `Agent` tool, the field on `StartSubagentRequest`, the pass-through to
  `runtime.start`, and `request.model ?? profile.model` in the runtime. The
  profile still decides when the call names no model, and the tool description
  already lists each profile's model, so the override is chosen with the
  information in hand.
- `thinking`, `max_turns`, `inherit_context` and `input_files` stay withdrawn: a
  model's guess there only ever discarded what the profile had configured.
- A resume keeps the session it continues, so `model` joins `isolation` in the
  creation options rejected before dispatch, through the same list the old code
  used.

* fix(subagents): keep input_files as a per-call Agent parameter

input_files is input preparation, not a profile setting, and stays on the
Agent tool: restore lib/subagent-input.ts, its test, the schema entry and
its resume rejection. Keep isolation a plain string so a model that fills
optional fields with "" can still start or resume a subagent, as the resume
contract documented. Pin that profile thinking, inherit_context and input
files reach a real child session, and that calls still carrying the
withdrawn keys validate. Revert the ADR 0002 note, update the subagents
note and the demo's captured Agent schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(pwa): configure installed app name at runtime (#1147) (#1148)

Co-authored-by: TossPig <claw@tossp.com>

* feat(agents): view sub-agent work in a right-panel tab (#1129)

* feat(agents): view sub-agent work in a right-panel tab

Sub-agent runs were only observable after the fact; opening one
hijacked the main chat. The Agent tool card now opens the sub-agent's
live transcript as a read-only tab stacked beside file previews and
terminals:

- SubagentViewer renders the sub-agent session through MessageView with
  its own cwd, a status badge, manual refresh, and upward pagination
- Live updates poll GET /api/sessions/[id]/context every 2s while the
  sub-agent runs; the route reads the running wrapper's in-memory
  entries and never spawns an AgentSession for a viewer tab
- AppShell keys tabs by agent:<sessionId> (deduped, bot icon, label),
  folds the panel when the last tab closes, and drops them on project
  switches together with file tabs
- onOpenSession prop renamed to onOpenSubagent(sessionId, label); the
  card button opens the side tab instead of switching the main chat

# Conflicts:
#	components/AppShell.tsx
#	components/ChatWindow.tsx
#	components/MessageView.tsx

* fix(agents): subagent tab close fallback, paging and status in the viewer

- Closing a file tab while another file tab stayed open crashed AppShell:
  `a ?? b ?? agentTabs.at(-1) ? `agent:…` : null` parses as a ternary over
  the whole ?? chain and read `.sessionId` of a missing agent tab (same in
  the terminal and agent close paths). lastAgentTabId() replaces it.
- A new session in another project (handleNewSession) now drops subagent
  tabs too, as the other two project switches do.
- Polls replaced the transcript with the newest page, discarding pages the
  user loaded with "Load more", and a page landing after a poll could be
  prepended over a gap. Polls now fold into the loaded pages
  (mergeTailPage), an older page is prepended only onto the cursor it was
  asked for (prependOlderPage), polls never overlap, and a prepended page
  keeps the scroll position.
- The status badge stayed "Running" after the run ended (session info was
  fetched once); it is refetched when the running flag changes.
- MessageView gets the session id, so deferred thinking blocks load
  instead of showing "thinking unavailable".
- AGENTS.md file map and docs/agents/subagents.md describe the viewer tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): send a new session's first prompt even after switching away (#1146) (#1152)

Switching sessions while a fresh composer waited for its event stream's
`connected` handshake closed the stream, so the send failed before the
prompt was posted, and recovery drops an abandoned composer's draft: the
text was lost and the session never appeared in the sidebar. Once the hook
is unmounted, skip the stream wait and post the prompt anyway, as a switch
during session creation already did; no stream is opened for an unmounted
composer either.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(files): reload the file tree while a run writes and on window focus (#1144) (#1153)

The tree reloaded only when a run ended or on the refresh button, so files
the agent wrote mid-run, or changed in an editor or terminal, stayed hidden.
Now any top-level tool but read/grep/find/ls schedules a reload (at most one
a second), and the explorer reloads when the window gets focus. No watcher,
no polling.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): add version, update, status, stop and open commands (#1139) (#1154)

* feat(cli): add version, update, status, stop and open commands (#1139)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): never signal a recycled pid; stop the whole tree on Windows

A run record outlives a crash or reboot, and its pid may then belong to an
unrelated process: stop would SIGTERM it. A record now counts as running only
while its URL answers over HTTP (any status); a live pid that does not answer
is skipped, and its record kept until the pid dies. On Windows process.kill()
ended the launcher alone and left Next.js serving the port, so stop ends the
launcher's process tree with taskkill there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): check run-record processes; stop orphaned Next.js; records in the agent dir

- A recycled pid passed the old check whenever something answered on the
  record's port, so stop could SIGTERM an unrelated process. A record now
  counts only while its pid still is pi-web: the launcher's command line names
  pi-web, the server's is "next-server (vX)" (/proc on Linux, ps elsewhere,
  the node image name on Windows). When nothing can tell, the URL check
  decides as before.
- A launcher killed with SIGKILL left Next.js serving the port while status
  said nothing ran. The record keeps nextPid; status lists such a server as
  "launcher gone", stop signals it directly and update refuses.
- Records were keyed by port, so a second server on the same port with
  another hostname overwrote the first's. They are keyed by launcher pid now.
- Records move from ~/.pi-web/run to <agentDir>/pi-web-run (default
  ~/.pi/agent/pi-web-run), where pi-web keeps its other state; pi-web wrote
  nothing under ~/.pi-web before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): files below the sessions on desktop, section-style project headers

The multi-project tree was hard to scan: a project's name (12px, weight 500,
muted) was smaller and lighter than the session titles under it. And the
file browser, used as often as the sessions, sat behind a tab of its own.

- Project headers read as section headers: a 14px folder icon (the current
  project's in the accent), the name at 13px/600, session rows and "show
  more" aligned with the name at 24px. The pinned and archive headers share
  the look. Row heights are unchanged.
- The group that stops being current stays open for the page only. It used
  to be saved, so every project ever visited came back expanded. Saved
  choices move to pi-web:sidebar-groups-v2, keeping only the old collapses.
- Desktop shows the files below the sessions by default: a resizable,
  keyboard-operable separator and a foldable "Files · N" section header with
  its own file search. The height is kept per browser; a short window shows
  less without saving it (useResizablePanel persistClamp: false), and the
  files section gives way before the sessions' minimum.
- Settings › General › Sidebar › File browser: "Below sessions" or "Separate
  tab" (hooks/useFilesPlacement.ts). Phones always use tabs. Both layouts
  render one element tree, so switching never remounts the explorer, the
  tree or the picker; focus on a control that goes away moves to the toolbar.
- The file tree remembers its open directories per cwd (page memory, 20
  folders), so clicking a session in another project and back keeps it.

Tests cover the merge and migration helpers, the prefs, the placement store,
the resize hook's new option and the expansion memory; e2e checks both
layouts and that the explorer survives a switch. Docs: sessions.md,
files-and-access.md, settings-ui.md, AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(sidebar): restore the old sidebar's visual rules in the new layout

Next to the sidebar before c7178c3d4 the new one looked flat and busy:
two extra greys made the session titles paler than the project names, a
folder on every project made the tree read like a second file tree, the
chevrons trailed names of every length, the selected row barely showed,
and the files section spent four bands before its first file.

- Text takes three tokens only: content --text (titles 12px, 13px on
  phones), labels --text-muted (project names 12px/600, the current one
  --text), meta --text-dim at 11px. "Pinned" and "Files" are section
  labels: 11px/600, uppercase, spaced.
- Chevrons lead in one 12px column (x 11) and every label and title starts
  at x 26; the project, pin and files folder icons are gone. The left inset
  is fixed, so a classic scrollbar only narrows the right side, where the
  time column, the file keys and the picker boxes end on one edge.
- The selected session gets a 3px accent bar; the accent marks nothing else.
- Project groups sit directly on each other, expanded or not; only the
  pinned section and the footer keep an 8px gap. The drop line follows the
  real gap.
- With the files below the sessions: the toolbar shows the "Pi Web" brand
  with the old click-to-show-versions scramble (components/PiWebTitle.tsx,
  plain swap under reduced motion); the files header row holds the fold
  toggle, a changed-files chip and six keys (search, terminal, file
  manager, upload, refresh, ignored files); the project and worktree boxes
  share one row. The tabs layout keeps its tabs, head and key row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(sidebar): 28px rows, files keys in the tab's order, fold and archive motion

- Rows: sessions are 28px on desktop like the group, pinned, empty and
  footer rows (phones: sessions stay 44px, headers become 44px too).
- The files header row lists its keys in the files tab's order (terminal,
  file manager, upload, refresh, ignored files, changes) with search last;
  the changes key replaces the count chip and the count is back as
  "Files · N", so no key ever moves. Keys are 22px; focus on the changes
  key moves to its neighbour when it turns disabled.
- A folder outside any git repository shows no worktree box in either
  layout (a repo's subdirectory keeps its disabled hint); folders found not
  to be git are remembered per browser so the box does not flash again.
- The file tree starts 4px under the picker (and under the tab's head line).
- New has its own left line in both layouts, so New and search read as two
  cells next to the brand.
- Folding the files section animates its height, entering and leaving the
  archive slides and fades (hooks/useSidebarMotion.ts, 180ms, nothing moves
  under prefers-reduced-motion). The archive view is stacked above the tree
  (position: relative; z-index: 1): unpositioned, it lost to the tree's
  positioned rows in the frame its entrance ended, which flashed the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sidebar): selecting a revealed session no longer shows an older one

After "show more", picking the last revealed session in a group showed the
next, older session below it. The window was a budget recounted on every
render, and families that show anyway (running, unread, selected) did not use
it up: the picked row turned selected, freed its slot, and the next family
took it. A row turning unread or running did the same.

The window is now a position, decided at the click: the more row offers
`nextShown` (the window that SHOW_MORE_STEP more hidden families need, with
the flags of that moment), handleShowMore() stores it, and the tree shows
every family before it plus the flagged ones after it. Each click still adds
20 hidden rows; later flag changes never move the window. The pinned section
shares the code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): folding a group drops its "show more" window

A group opened again kept the rows "show more" had revealed before it was
folded. Every explicit choice that folds a group (a toggle, Alt+click,
collapse others) goes through saveGroupChoices(), which now forgets the
folded groups' windows (forgetShownMoreOfFolded()); folding the pinned
section forgets its own. Reopened, a group shows its first rows plus the
running, unread or selected ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(new-session): brand above, project and worktree right over the composer

The empty new-session header put the logo, "Pi Web", the update link, the
project path box, the worktree box and two version lines floated right into
one 40px row, held together by a float, inline boxes, line-height 0 and a
calc() width; the path was cut in the middle of a hash and "main 主分支 3"
said the same thing twice.

- The brand stands alone, left-aligned: the logo (40px, 32px on phones) and
  "Pi Web" over one dim line, "web v<app> → v<latest> ↗ · pi v<pi>" (the
  update part only when a newer release exists; the pi version is the one
  cut when narrow). Nothing on the right.
- The project and worktree become one row right above the composer, its
  folder icon on the logo's and the card's left edge: the project's name
  (its display name, a dim "parent/" only for twins, the parent cut first;
  the full path as the tooltip) and the branch cut at its left, with no
  "main" note and no count; the worktree gives way first on a narrow row.
  The menus, focus after a move and the carried draft are unchanged; the
  row hides while a phone's keyboard is up, the brand stays.
- The old float, 40px boxes, calc() width and their compensating margins
  are gone; the update link's hover, focus and touch target no longer move
  the line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(sidebar): larger files header keys, 13px icons

The seven keys in the files section's header row (files below the
sessions) were 22px with 14px icons. They now share what the toggle's
content leaves, 18 to 26px wide and 26px high, with 13px icons: about 24px
at the default 260px beside "文件 · 2", 26px from about 300px. The toggle
keeps its label and count until the keys are at 18px, then lets them go
whole, down to the chevron. The files tab's row and coarse pointers' 32px
keys are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Release v0.11.1

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(release): push the tag by name, check prerequisites, note npm propagation

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* perf: streaming markdown, session list payload, push title, SSE image echo (#1176)

* perf(push): title the completion push from the live session

Each finished run with a push subscription called SessionManager.listAll()
to look up one session's name: it parses every session file. On a 146 MB
sessions folder that is 372 ms of CPU and about 250 MB more memory per run.
The wrapper's own SessionManager has the same name (its newest
session_info), so the run-complete listener now passes it along.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(sessions): cap the first message the session list carries

GET /api/sessions sent every session's whole first message: an expanded
skill or a pasted document made one row 325 KB and the list 3.2 MB
(1.0 MB gzipped), and each tab fetches it again two or three times after
every run. The row title shows 50 characters; the subagent filter needs
no more than a few hundred.

catalogFirstMessage() sends a skill expansion as its /skill: command,
as the row shows it, and cuts other text to 500 code units without
splitting a surrogate pair, for persisted and live rows alike. The list
is now 385 KB (93 KB gzipped) on the same folder. Fork naming reads the
source file itself and keeps the whole text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(sse): send only the role of a non-assistant message_start

The agent loop announces a tool result (and a delivered user message)
with message_start and message_end back to back. The browser builds only
an assistant reply from a start and reads nothing else of the others but
the role, so an image read's base64 crossed the event stream twice.
A non-assistant message_start now goes as { role } only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(chat): parse a streaming reply block by block

Every streamed chunk parsed the whole reply's markdown again, so a long
reply cost quadratic time. At 4x CPU throttling a 14k-character reply
spent 8.8 s in react-markdown and its commits grew from 4.7 to 15.6 ms;
the main thread was busy 40% of the run, with long tasks up to 350 ms.

While streaming, MarkdownBody cuts the text with splitMarkdownBlocks()
and renders a memo'd block per piece: finished blocks keep their parse
and only the last one is parsed again. A cut goes only after a blank
line, before a column-0 line that is not a list item, never inside a
fence or $$ block, and not at all after raw HTML or in front matter. A
finished message is one block, rendered exactly as before; MarkdownBody
itself is memo'd too.

Same prompt after the change: Markdown 1.5 s, commits a flat 2-3 ms.
Every prefix of a mixed test document parses the same split as whole,
as do the 60 longest replies of a real session folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(files): preview HTML files larger than one 256 KB chunk (#1155)

* feat(files): preview HTML files larger than one 256 KB chunk

* fix(files): keep the previous HTML preview up while a change refetches

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(files): no Load more bar over a whole-file HTML preview

The preview shows the full file, so the chunk counter misled and each
click refetched the whole page. Source keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Hu Chen <huchen@sw593996.dhcp.swmed.org>
Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(terminal): keep input alive when the phone keyboard collapses the panel (#1160)

Opening the soft keyboard on a phone shrinks --app-viewport-height, so xterm's
fit can momentarily resize the terminal to one row. The resize API rejected
rows < 2 with 400 "Invalid terminal command", and the writer's fail-closed
rule then disabled input for good. Clamp rows to 2 on both the client and the
route instead of rejecting.

* feat(terminal): add Termux-style extra keys on portrait touch screens (#1166)

* feat(terminal): add Termux-style extra keys on portrait touch screens

Phones held in portrait get two rows of keys under the terminal:
ESC / - HOME UP END PGUP and TAB CTRL ALT LEFT DOWN RIGHT PGDN. The row is
part of the panel's grid, so the terminal refits above it instead of being
covered, and tapping a key keeps the soft keyboard open.

Keys send the same sequences as a physical keyboard, following xterm's
application cursor mode. CTRL and ALT are one-shot and also apply to the next
character typed on the soft keyboard. The arrows use Noto Sans Mono's up and
down glyphs, rotated for left and right, so all four match.

* test(terminal): pin the extra keys' sequences against xterm's

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sessions): open sidebar sessions in a new browser tab (#1169)

* feat(sessions): open sidebar sessions in a new browser tab

A saved session's title in the sidebar is now a real link (?session=<id>),
so middle-click and Ctrl/Cmd-click open it in a new browser tab while the
current tab keeps its session. A plain click and Enter still select it in
place without a page load. The row's own click handler is unchanged.

The row menu (right-click and ⋯) gets "Open in new tab" (T), just before
Delete; never first, since a menu's first item takes focus when it opens.
Transient sessions keep their button and get no link.

When focus is put back into a row it now goes to its first a[href] or
button, so a keyboard Fork focuses the copy's link, not its archive button.

Closes #1167

* docs(sessions): describe row focus controls

* test(e2e): open new tabs with Ctrl or Cmd, as the platform does

On macOS Ctrl-click is a secondary click, so the Ctrl-only steps waited
for a tab that never opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(e2e): open the row menu from ⋯, not Shift+F10

Shift+F10 opens no context menu in Chrome on macOS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sessions): guard the remaining in-flight-turn invalidation paths (#1173)

* fix(sessions): guard the remaining in-flight-turn invalidation paths

Reuses the existing isSessionRunningForReplacement() pattern (already
used by clone/fork in rpc-manager.ts) for the paths that can still
invalidate a live extension ctx mid-turn:

- `reload` via the extension command API and the extension ctx callback
  object (rpc-manager.ts) - previously unguarded, unlike clone/fork
- the cwd-scoped sweep destroyRpcSessionsForCwd() shut down every
  session in the target cwd, including running ones
- DELETE /api/sessions/[id] shut down the deleted session's subagent
  descendants and the target even while they were mid-turn
- a background subagent outlives its parent's turn, so the parent
  session could be idle-evicted while the run was still active;
  register a session-liveness provider for the parent for the run's
  lifetime (start()/resume() in subagent-runtime.ts), released when the
  run's promise settles

Also updates the source-assertion test for the DELETE route to the
guarded shutdown form.

Verified against a locally built 0.11.1: a reload aimed at a session
with an in-flight turn is now rejected and the turn completes; idle
sessions still reload/delete normally; a parent holding a long
background subagent survives the idle window and receives the
completion notification without a stale-ctx failure.

Refs #1172

* fix(sessions): keep the reload guard, drop the other teardown changes

- An extension command runs inside its own prompt, so the
  isSessionRunningForReplacement() guard made every command that calls
  ctx.reload() fail even on an idle session. ctx.reload() now checks only
  streaming and compacting, as pi's TUI does, and warns instead of throwing.
- The reload refusal uses pi's text.
- DELETE: deleting a running session must still stop it; skipping the
  shutdown left the wrapper running and appending to the unlinked file.
- destroyRpcSessionsForCwd: its only caller refuses a busy cwd first.
- Background subagents: an evicted parent is reopened by notifyParent, and
  the child run completes after the parent is disposed, so the liveness
  provider is not needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Yang <agegcn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* perf(sessions): rebuild the list once per finished run (#1177)

A run's agent_end already invalidates the server's session list before
the event reaches any browser. Three client reloads around it did more:

- the tab showing the session reloaded with force=1 (refreshKey), which
  invalidated again and started a second rescan;
- the same tab's hydrateSelectedSession fetched the whole list once more
  for one row, starting a rescan the force then threw away;
- every other visible tab, seeing the run finish in the background,
  reloaded with force=1 as well: one more rescan each, and a version bump
  that made all the other tabs reload again.

With two tabs that was 5 list requests and 3 rebuilds per run (each
40-110 ms, including ~36 ms of synchronous subagent reads). These reloads
are now plain loadSessions() calls, and handleAgentEnd no longer fetches:
the sidebar's reload reaches the selected session through
handleSessionsChange -> mergeCatalogRow(), which also clears a fresh
session's transient flag. Measured after: 1 rebuild per run, 3-4
requests of which all but the first are cache hits. The fi…
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 6, 2026
…ion switches (agegr#988, agegr#1031, agegr#877, agegr#896) (agegr#1114)

* fix(chat): clear the retry banner once the retried run starts (agegr#988)

pi emits a successful auto_retry_end only at the retry's first complete
assistant message, so the banner said "Retrying" through the whole retried
reply. pi's TUI drops its retry indicator when that run starts; clear it on
the run's agent_start the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): read context usage when the event stream connects (agegr#1031)

Opening a session's event stream is what resumes a wrapper the idle timeout
reaped, so the mount's state read often finds no runtime and leaves the
context percentage blank. Since agegr#1058 a run fills it in after its first
reply; read it on `connected` too, through the same ordered usage read, so
it shows as soon as the runtime is back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep a streaming reply's t/s start across session switches (agegr#877)

The start of the tokens-per-second measurement lived in the message view,
which a session switch remounts. Back on a running session, the new view
took its start at the remount and divided every token streamed so far by
half a second, showing thousands of t/s. Keep the start per reply (provider,
model and request timestamp) outside the view; a reply joined with no record
(a reload) times only the tokens that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): reveal loaded rows the history window still hides (agegr#896)

The window keeps as many rows as messages are loaded, but a turn's answer
and its thinking render as two rows, so a thinking-heavy session hides its
oldest loaded rows behind "Load earlier messages". Since agegr#587 the sentinel
only fetched from the server, so with no older page there, reaching it did
nothing. Widen the window in that case again, renew the observer when it
grows, and observe the sentinel whenever it mounts, not only when the
history cursor changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 8, 2026
…egr#555) (agegr#587)

* fix: bound session history load to a tail window (fixes agegr#509, agegr#555)

- slice branch chain to a tail window in buildSessionContext; add ?tail/&before pagination to detail + context APIs

- BranchNavigator recursion -> iterative (deep linear chains no longer overflow the stack)

- guard entryToUiMessage against string assistant content (real long sessions 500'd on content.map)

- ChatWindow sentinel + useAgentSession.loadContext prepend older pages

- e2e (playwright) + pagination tests

* chore: bump version to 0.8.10

* test: cover tail/before pagination and 1000-tail cap at the route and data layers

- detail + context route tests assert ?tail parsing (default 50, NaN-safe, capped 1000) and ?before excludeLeaf wiring

- session-reader pagination tests add excludeLeaf page dedupe, string-assistant-content guard, and large-tail chain

* fix: address Codex review on pagination branch (multi-root, prepend visibility, drop playwright dep)

- BranchNavigator.hasBranch: restore the multiple-root check (nodes.length > 1) that the iterative rewrite dropped; sessions branched from the first message have multiple roots and were misreported as branchless.

- ChatWindow: expand the rendered window to at least the loaded message count so prepended (older) pages stay visible instead of being sliced off the top, and show the 'load earlier' sentinel when the window is full (the initial tail is a truncation).

- package.json: remove the playwright devDependency that was added for local E2E probing; it does not belong to this fix and left package-lock.json out of sync.

- test: cover hasBranch for multiple-root trees.

* fix: restore package.json mermaid dep and drop temporary e2e probe scripts from the PR

- a previous edit accidentally replaced the mermaid devDependency with a duplicate postcss entry; restored mermaid and removed the duplicate.

- e2e_browser.mjs/e2e_click.mjs/e2e_trace.mjs were temporary local probes and should not be in this PR; removed from the tree (kept locally, gitignored).

* fix: complete bounded session pagination

---------

Co-authored-by: Nuctori <Nuctori@users.noreply.github.com>
Co-authored-by: Alex Yang <agegcn@gmail.com>
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 8, 2026
…ion switches (agegr#988, agegr#1031, agegr#877, agegr#896) (agegr#1114)

* fix(chat): clear the retry banner once the retried run starts (agegr#988)

pi emits a successful auto_retry_end only at the retry's first complete
assistant message, so the banner said "Retrying" through the whole retried
reply. pi's TUI drops its retry indicator when that run starts; clear it on
the run's agent_start the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): read context usage when the event stream connects (agegr#1031)

Opening a session's event stream is what resumes a wrapper the idle timeout
reaped, so the mount's state read often finds no runtime and leaves the
context percentage blank. Since agegr#1058 a run fills it in after its first
reply; read it on `connected` too, through the same ordered usage read, so
it shows as soon as the runtime is back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): keep a streaming reply's t/s start across session switches (agegr#877)

The start of the tokens-per-second measurement lived in the message view,
which a session switch remounts. Back on a running session, the new view
took its start at the remount and divided every token streamed so far by
half a second, showing thousands of t/s. Keep the start per reply (provider,
model and request timestamp) outside the view; a reply joined with no record
(a reload) times only the tokens that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(chat): reveal loaded rows the history window still hides (agegr#896)

The window keeps as many rows as messages are loaded, but a turn's answer
and its thinking render as two rows, so a thinking-heavy session hides its
oldest loaded rows behind "Load earlier messages". Since agegr#587 the sentinel
only fetched from the server, so with no older page there, reaching it did
nothing. Widen the window in that case again, renew the observer when it
grows, and observe the sentinel whenever it mounts, not only when the
history cursor changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants