Commit Graph
1745 Commits
Author SHA1 Message Date
218d99cddf feat(android): render mermaid fences as offline diagrams (#2161)
* feat(android): render chat markdown math with offline KaTeX

Port the web math pipeline to Android chat markdown. A new
MarkdownMath pre-pass in :core:protocol extracts math with web
semantics (remark-math singleDollarTextMath:false + remark-latex-
bracket-math): $$ display flows, $$ text math only when the closer
run equals the opener and stays inside the paragraph, single $
never triggers math (currency stays prose), \(..\)/\[..\] bracket
pairs, backslash-escaped delimiters stay literal, and code spans,
fences, links and link reference definitions are fully protected.
Matches are lifted behind private-use placeholder tokens and
re-inserted as MathInlineNode/MathBlockNode custom nodes, hoisting
display math out of paragraphs while blockquote/list containers
survive the reparse. 37 JVM tests mirror the web suite's cases.

Rendering is a shared offline WebView (ui/markdown/MathWebView.kt)
fed a self-built HTML document (MathDocument.kt) against bundled
assets/katex/ (KaTeX 0.16.45, same version as web). The view is
network-blocked (blockNetworkLoads + shouldInterceptRequest
refuses http/https/ws/wss) with file/content access disabled;
asset URLs still resolve through the file:///android_asset/katex/
base URL. Theme color and font size are injected per render and
the document reports its height through a JS bridge
(ResizeObserver + onPageFinished re-measure). KaTeX failures
follow the web's three-tier semantics, degrading to monospace
raw TeX.

Inline \(..\) and single-paragraph $$ math degrades to monospace
TeX for v1: AnnotatedString cannot host a WebView and one WebView
per fragment is too costly in chat lists. The parser still emits
MathInlineNode so a future renderer can upgrade inline rendering
without touching the extraction layer.

Co-Authored-By: Claude Code <noreply@anthropic.com>
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): convert CSS pixels correctly at the math WebView boundary

The JS bridge reports scrollHeight in CSS pixels, but KaTeXMathBlock
treated the value as Android physical pixels and divided it by the
screen density when sizing the modifier: on a density-3 device a
reported 90 CSS px block collapsed to 30dp instead of ~90dp. The font
conversion had the opposite mismatch — 16sp chat text went through
TextUnit.toPx() (physical pixels) and was injected as `font-size: 48px`
CSS, making formulas render ~3x too large on the same screen.

Define the two boundary conversions explicitly as pure functions next
to the document builder and unit-test them:

- spFontToCssPx: CSS px and sp are both density-independent, so only
  the user's font-scale preference crosses the boundary; density never
  enters (16sp stays 16 CSS px at any density, 21 at fontScale 1.3).
- cssPxToDp: reported CSS px map 1:1 to dp at the default WebView
  scale, multiplied by WebView.scale when the view is zoomed.

The document now also pins the viewport with
`width=device-width, initial-scale=1`, making the 1 CSS px = 1 dp
default scale an explicit property of the document rather than a
WebView default, with a regression test asserting the meta tag.

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

* fix(android): refresh the math WebView height callback across spec changes

KaTeXMathBlock keyed its height state with remember(spec) but assigned
MathWebView.onHeightChanged inside AndroidView.factory, which runs only
when the Android view is created. The callback therefore captured the
initial spec's state object: when LaTeX, theme color or font size
changed, remember(spec) minted a new state while AndroidView retained
the existing view and its stale callback, so every measurement from the
reloaded document updated the orphaned state and the current block
stayed at its 22dp minimum.

Keep one stable holder (MathViewHeightState) remembered unkeyed for the
mounted view, reset it explicitly in onRender when the spec changes, and
re-point the view's callback plus reset the height inside
AndroidView.update before rendering — the creation-time callback then
always feeds live state. JVM tests drive the holder through spec
changes on one mounted view (the pre-fix wiring cannot compile against
this shape: the factory-captured remember(spec) state is exactly the
orphan the holder removes).

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

* fix(protocol): bound dollar flow math closing to the enclosing container

findFlowClose kept scanning after the opening line left its container
and accepted an unprefixed closing run, so `> $$\n> x\n\nOrdinary
prose\n\n$$\ny\n$$` paired the quoted opener with the later top-level
`$$`: the prose was swallowed into the formula and the final `$$` lost
its own opener. remark-math (verified against micromark-extension-math,
whose math flow is `concrete` and dies with its container) renders the
quote's math, the prose and a separate top-level equation instead.

Bound matching to the opening container, distinguishing container
shapes: a closer is only accepted from a line that still carries the
container prefix; a blank line ends a blockquote (a following `> $$`
opens a NEW quote, while a `>`-only line is an in-quote blank the
container survives); a list item may resume after blank lines (loose
lists), so blanks are skipped and the next content line decides; an
unrecognized prefix is plain <= 3 space indentation, not a container,
and keeps the unbounded scan (blank lines and fences stay math content).

Regression tests: the quoted example (prose stays prose, the later
equation keeps its own opener), a list-container variant, a
blank-line/new-quote guard, plus two in-container close locks — the
first three fail on the pre-fix scan.

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

* feat(android): render mermaid fences as offline diagrams

Port the web MermaidDiagram component to Android chat markdown. A fence
whose language is exactly `mermaid` (case-sensitive, like the web's
MARKDOWN_COMPONENTS_BY_LANGUAGE key) now dispatches to MermaidDiagramView
instead of the plain code block; every other fence keeps the CodeBlock
path.

Rendering runs in a hardened offline WebView fed a self-built HTML
document against bundled assets/mermaid/mermaid.min.js (Mermaid 11.14.0,
curl-fetched, sha256-identical to the web app's locked dependency). That
dist file is a self-contained classic script assigning globalThis
mermaid - no imports, no runtime fetches - so no ES-module/CORS
workaround is needed. The view shares the KaTeX skeleton: network stack
blocked, file/content access off, asset URLs through the
file:///android_asset/mermaid/ base URL (OfflineMathWebViewClient
generalized to OfflineMarkdownWebViewClient, no behavior change).

Behavior mirrors the web component line by line: initialize with
startOnLoad:false, securityLevel:'strict', suppressErrorRendering:true
and the web's dark/light themeVariables palettes verbatim (theme flips
re-render); the validate-then-render gate parses with suppressErrors
first and never calls render() after a failed validation, re-parsing
once without suppression only to surface a human-readable reason; svg
element ids are per-instance (`mermaid-<n>`, web useId) so the scoped
styles mermaid emits cannot collide across diagrams in one message;
wide diagrams scroll horizontally inside the document while the svg is
centered at max-width:100% and height:auto.

The code header (language chip + copy) stays above the body like the
web's retained DefaultCodeBlock header; until the diagram renders - and
on failure - the raw source is shown below it (the block's source exit),
with the failure notice appearing only for actual errors so the loading
window never flashes a render-error line. mermaidFallbackUi maps state
to those surfaces as a pure function.

15 JVM tests cover dispatch, offline-ness, palettes, security flags,
the validation gate structure, id uniqueness, generation filtering,
script-breakout safety and the fallback mapping; the driver's runtime
semantics were additionally validated against the real bundle in jsdom
(flowchart/sequence render, invalid source surfaces the parse reason,
hostile labels are rejected/sanitized under strict).

Co-Authored-By: Claude Code <noreply@anthropic.com>
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): convert CSS pixel heights correctly in the mermaid WebView

Both height reporters feeding MermaidDiagramView — the document bridge's
report() (documentElement/body scrollHeight) and
OfflineMarkdownWebViewClient's onPageFinished re-measure — return CSS
pixels, but the rendered branch ran the value through
with(density) { heightPx.toDp() }, which treats it as Android physical
pixels and divides by display density: on a 3x display a diagram
measuring 180 CSS px received a 60dp box and was clipped into an
unnecessarily scrolling WebView.

Fix it exactly like the KaTeX base now does: the document pins
`width=device-width, initial-scale=1` (making 1 CSS px = 1 dp at the
default WebView scale an explicit property of the document rather than a
WebView default), and the reported value crosses the boundary through
the shared density-independent cssPxToDp helper — extracted as the pure
mermaidRenderedHeightDp so the composable no longer holds any density
conversion at all, keeping both markdown renderers on one boundary
contract. (The KaTeXMathBlock repeat of the same bug is fixed by the
rebased base; MathWebView.kt arrives converted already.)

JVM tests: the viewport pin is asserted against the built document
(demonstrated failing on the pre-fix template) and the conversion math
is driven through the pure helper — 180 CSS px stays 180dp because the
boundary carries no density parameter, mirroring the base's
MathDocumentTest contract.

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

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: HAPI <noreply@hapi.run>
2026-11-02 18:23:35 +08:00
fb035051c2 feat(android): context-remaining indicator in composer (#2201)
* Add per-message metadata details popup to chat

Messages that carry usage signal (model, token counters, round cost or
duration) now expose an info entry under the message card; tapping it
opens a dialog listing model/tier, token totals, cached-input share,
USD cost, and round duration/turn count.

- protocol: decode result summaries into turn-summary events; native
  turn durations and token counts gate on top-level scope and merge
  per turn id onto the trailing block group
- protocol: response-group aggregation sums per-turn usage across a
  run of assistant blocks (adjacent-turn dedup, first-seen model
  order, synthesized round durations from the activity window)
- protocol: label builders render the popup lines with pinned number
  formatting (grouped totals, compact k/m counts, USD tiers,
  sub-minute durations); tests mirror the full label contract
- app: entry shows only when the message has labels, dialog follows
  the existing alert idiom, strings in en/ru/zh with aligned key order

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

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Add pure context-usage math for the chat status strip

Token-count abbreviation (plain below 1k, whole k, one-decimal M),
window-share percentages that always complement to 100, an unrounded
warning band (neutral, amber from 70%, red from 90%), a full readout
with cache-read and a clamped remainder, and the window estimate
table: a window reported alongside the usage wins, then per-flavor
defaults minus a 10k headroom (codex 258.4k, pi/claude 200k, claude
1M for [1m] and fable model ids, cursor names carrying an inline
context= segment). Sessions without an estimate keep a size-only
readout. Unit tests cover the thresholds, mid-point rounding, and the
missing-model / missing-usage edges of every flavor branch.

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

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Show context-remaining indicator above the composer

The composer status strip gains a compact readout of the session
context: the window budget with the free share while the window is
known (ctx 258k, 65% left), otherwise just the current size. The
color escalates neutral, amber, red as the window fills; the text
stays the same in every band. State derives from the session-level
usage projection in ChatUiState and stays hidden until the thread
reports usage. Strings ship in en/ru/zh with aligned key order.

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

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): salvage single-turn tool-group metadata in aggregation

One assistant message whose groupable tool calls form a single tool group
lost its details entry: aggregation emitted nothing for a one-turn group
without a round summary, and messageMetadataForBlock maps ToolGroupBlock
to null, so once the transcript projection strips the member tools the
usage/model they carried became unreachable.

A group that starts with a ToolGroupBlock now salvages its (deduped)
turn metadata into the aggregate map, keyed by the group block so the
stripped row still resolves it. Groups led by other block kinds keep
their own fields; silent groups salvage nothing. Covers shared-source
members with and without CLI-stamped local ids, the stripped-projection
readback, and the multi-turn aggregation path through a group.

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

* fix(android): give the elevated context band a semantic amber

ELEVATED used MaterialTheme.colorScheme.tertiary, which the static themes
define as teal and dynamic color derives from the wallpaper, so the amber
caution band the PR promised was anything but. Add a `warning` token to
HapiExtendedColors (amber-700 on light, amber-400 on dark/OLED — outside
the M3 scheme, so wallpaper-derived tertiaries cannot reach it) and map
the band through a pure contextUsageColor() helper.

Unit tests pin the mapping (never the scheme tertiary, stays amber under
teal/wallpaper-like tertiaries) and verify WCAG-AA contrast of the amber
against the light, dark and OLED surfaces.

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

* fix(android): align the Claude window fallback with the web presets

The copied preset set treated bare sonnet/opus as 200k models and omitted
haiku entirely, so a preset session without a reported window got a 190k
budget (200k of usage read as 0% left) or none at all. Resolve windows
through ClaudeModels.PRESETS mirroring web/src/chat/modelConfig.ts: the
picker aliases (opus/fable/sonnet/haiku) are 1M-window models, claude-
prefixed ids keep the 200k default, and [1m]-suffixed / claude-fable ids
are large.

A device test also pins the chip readout across light/dark/dynamic
themes: known vs unknown windows, all three warning bands, and no
indicator until measurable usage exists.

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

---------

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 18:23:23 +08:00
be5f37b9bf feat(android): generalize generated media blocks to video/audio/file (#2162)
* feat(android): render chat markdown math with offline KaTeX

Port the web math pipeline to Android chat markdown. A new
MarkdownMath pre-pass in :core:protocol extracts math with web
semantics (remark-math singleDollarTextMath:false + remark-latex-
bracket-math): $$ display flows, $$ text math only when the closer
run equals the opener and stays inside the paragraph, single $
never triggers math (currency stays prose), \(..\)/\[..\] bracket
pairs, backslash-escaped delimiters stay literal, and code spans,
fences, links and link reference definitions are fully protected.
Matches are lifted behind private-use placeholder tokens and
re-inserted as MathInlineNode/MathBlockNode custom nodes, hoisting
display math out of paragraphs while blockquote/list containers
survive the reparse. 37 JVM tests mirror the web suite's cases.

Rendering is a shared offline WebView (ui/markdown/MathWebView.kt)
fed a self-built HTML document (MathDocument.kt) against bundled
assets/katex/ (KaTeX 0.16.45, same version as web). The view is
network-blocked (blockNetworkLoads + shouldInterceptRequest
refuses http/https/ws/wss) with file/content access disabled;
asset URLs still resolve through the file:///android_asset/katex/
base URL. Theme color and font size are injected per render and
the document reports its height through a JS bridge
(ResizeObserver + onPageFinished re-measure). KaTeX failures
follow the web's three-tier semantics, degrading to monospace
raw TeX.

Inline \(..\) and single-paragraph $$ math degrades to monospace
TeX for v1: AnnotatedString cannot host a WebView and one WebView
per fragment is too costly in chat lists. The parser still emits
MathInlineNode so a future renderer can upgrade inline rendering
without touching the extraction layer.

Co-Authored-By: Claude Code <noreply@anthropic.com>
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): convert CSS pixels correctly at the math WebView boundary

The JS bridge reports scrollHeight in CSS pixels, but KaTeXMathBlock
treated the value as Android physical pixels and divided it by the
screen density when sizing the modifier: on a density-3 device a
reported 90 CSS px block collapsed to 30dp instead of ~90dp. The font
conversion had the opposite mismatch — 16sp chat text went through
TextUnit.toPx() (physical pixels) and was injected as `font-size: 48px`
CSS, making formulas render ~3x too large on the same screen.

Define the two boundary conversions explicitly as pure functions next
to the document builder and unit-test them:

- spFontToCssPx: CSS px and sp are both density-independent, so only
  the user's font-scale preference crosses the boundary; density never
  enters (16sp stays 16 CSS px at any density, 21 at fontScale 1.3).
- cssPxToDp: reported CSS px map 1:1 to dp at the default WebView
  scale, multiplied by WebView.scale when the view is zoomed.

The document now also pins the viewport with
`width=device-width, initial-scale=1`, making the 1 CSS px = 1 dp
default scale an explicit property of the document rather than a
WebView default, with a regression test asserting the meta tag.

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

* fix(android): refresh the math WebView height callback across spec changes

KaTeXMathBlock keyed its height state with remember(spec) but assigned
MathWebView.onHeightChanged inside AndroidView.factory, which runs only
when the Android view is created. The callback therefore captured the
initial spec's state object: when LaTeX, theme color or font size
changed, remember(spec) minted a new state while AndroidView retained
the existing view and its stale callback, so every measurement from the
reloaded document updated the orphaned state and the current block
stayed at its 22dp minimum.

Keep one stable holder (MathViewHeightState) remembered unkeyed for the
mounted view, reset it explicitly in onRender when the spec changes, and
re-point the view's callback plus reset the height inside
AndroidView.update before rendering — the creation-time callback then
always feeds live state. JVM tests drive the holder through spec
changes on one mounted view (the pre-fix wiring cannot compile against
this shape: the factory-captured remember(spec) state is exactly the
orphan the holder removes).

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

* fix(protocol): bound dollar flow math closing to the enclosing container

findFlowClose kept scanning after the opening line left its container
and accepted an unprefixed closing run, so `> $$\n> x\n\nOrdinary
prose\n\n$$\ny\n$$` paired the quoted opener with the later top-level
`$$`: the prose was swallowed into the formula and the final `$$` lost
its own opener. remark-math (verified against micromark-extension-math,
whose math flow is `concrete` and dies with its container) renders the
quote's math, the prose and a separate top-level equation instead.

Bound matching to the opening container, distinguishing container
shapes: a closer is only accepted from a line that still carries the
container prefix; a blank line ends a blockquote (a following `> $$`
opens a NEW quote, while a `>`-only line is an in-quote blank the
container survives); a list item may resume after blank lines (loose
lists), so blanks are skipped and the next content line decides; an
unrecognized prefix is plain <= 3 space indentation, not a container,
and keeps the unbounded scan (blank lines and fences stay math content).

Regression tests: the quoted example (prose stays prose, the later
equation keeps its own opener), a list-container variant, a
blank-line/new-quote guard, plus two in-container close locks — the
first three fail on the pre-fix scan.

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

* feat(android): render mermaid fences as offline diagrams

Port the web MermaidDiagram component to Android chat markdown. A fence
whose language is exactly `mermaid` (case-sensitive, like the web's
MARKDOWN_COMPONENTS_BY_LANGUAGE key) now dispatches to MermaidDiagramView
instead of the plain code block; every other fence keeps the CodeBlock
path.

Rendering runs in a hardened offline WebView fed a self-built HTML
document against bundled assets/mermaid/mermaid.min.js (Mermaid 11.14.0,
curl-fetched, sha256-identical to the web app's locked dependency). That
dist file is a self-contained classic script assigning globalThis
mermaid - no imports, no runtime fetches - so no ES-module/CORS
workaround is needed. The view shares the KaTeX skeleton: network stack
blocked, file/content access off, asset URLs through the
file:///android_asset/mermaid/ base URL (OfflineMathWebViewClient
generalized to OfflineMarkdownWebViewClient, no behavior change).

Behavior mirrors the web component line by line: initialize with
startOnLoad:false, securityLevel:'strict', suppressErrorRendering:true
and the web's dark/light themeVariables palettes verbatim (theme flips
re-render); the validate-then-render gate parses with suppressErrors
first and never calls render() after a failed validation, re-parsing
once without suppression only to surface a human-readable reason; svg
element ids are per-instance (`mermaid-<n>`, web useId) so the scoped
styles mermaid emits cannot collide across diagrams in one message;
wide diagrams scroll horizontally inside the document while the svg is
centered at max-width:100% and height:auto.

The code header (language chip + copy) stays above the body like the
web's retained DefaultCodeBlock header; until the diagram renders - and
on failure - the raw source is shown below it (the block's source exit),
with the failure notice appearing only for actual errors so the loading
window never flashes a render-error line. mermaidFallbackUi maps state
to those surfaces as a pure function.

15 JVM tests cover dispatch, offline-ness, palettes, security flags,
the validation gate structure, id uniqueness, generation filtering,
script-breakout safety and the fallback mapping; the driver's runtime
semantics were additionally validated against the real bundle in jsdom
(flowchart/sequence render, invalid source surfaces the parse reason,
hostile labels are rejected/sanitized under strict).

Co-Authored-By: Claude Code <noreply@anthropic.com>
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): convert CSS pixel heights correctly in the mermaid WebView

Both height reporters feeding MermaidDiagramView — the document bridge's
report() (documentElement/body scrollHeight) and
OfflineMarkdownWebViewClient's onPageFinished re-measure — return CSS
pixels, but the rendered branch ran the value through
with(density) { heightPx.toDp() }, which treats it as Android physical
pixels and divides by display density: on a 3x display a diagram
measuring 180 CSS px received a 60dp box and was clipped into an
unnecessarily scrolling WebView.

Fix it exactly like the KaTeX base now does: the document pins
`width=device-width, initial-scale=1` (making 1 CSS px = 1 dp at the
default WebView scale an explicit property of the document rather than a
WebView default), and the reported value crosses the boundary through
the shared density-independent cssPxToDp helper — extracted as the pure
mermaidRenderedHeightDp so the composable no longer holds any density
conversion at all, keeping both markdown renderers on one boundary
contract. (The KaTeXMathBlock repeat of the same bug is fixed by the
rebased base; MathWebView.kt arrives converted already.)

JVM tests: the viewport pin is asserted against the built document
(demonstrated failing on the pre-fix template) and the conversion math
is driven through the pure helper — 180 CSS px stays 180dp because the
boundary carries no density parameter, mirroring the base's
MathDocumentTest contract.

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

* feat(android): generalize generated media blocks to video/audio/file

The hub's /generated-images/:id endpoint already serves any mime type
(video, audio, arbitrary files arrive as the same generated-image wire
block with a mimeType), but the Android chat rendered every block as an
image. This ports the web GeneratedImageCard generalization so the card
routes by display intent, exactly like web generatedInlineMedia.ts:

- mimeType routing is the web's literal prefix check: video/… gets a
  player, audio/… an audio player, image/… or null keep the existing
  image treatment (unchanged AsyncImage thumbnail + tap-to-zoom dialog),
  everything else is a file card (no separate "unsupported" class —
  unknown mimes ARE the file UI, matching web G3/G8).
- non-image media never downloads on its own: "Load video" / "Load
  audio" / "Prepare download" gate buttons (web's explicit-intent rule
  G4; English labels verbatim from the web card), pulsing skeleton
  while fetching (G7), and the shared "{label} is unavailable. {error}"
  error line (G8). The wire carries no tiny/poster fields, so video
  renders bare — nothing to special-case.
- every kind now sits in the web's G14 card shell with the localized
  "{label}: {fileName}" hint header; images additionally surface the
  error line on Coil failure instead of a silent empty hole.
- downloads go through the same authed OkHttp client Coil uses (JWT +
  silent 401 re-auth + ETag disk cache), staged into a temp file and
  atomically renamed under cache/generated-media/; a completed file
  short-circuits later fetches (immutable, ETag-stable content) and
  non-2xx maps to "HTTP <code>" exactly like the web's ApiError.
- video plays in-app via framework VideoView + MediaController (no new
  media dependencies: Media3 is not on the classpath and pulling it in
  for this card is not worth the MB); audio is a compact
  play/pause + scrub + m:ss row over MediaPlayer (web's native <audio>
  chrome degraded: volume/speed omitted, no waveform — web has none);
  files get Open (ACTION_VIEW over the existing FileProvider, new
  generated-media cache path) and Save (ACTION_CREATE_DOCUMENT picker)
  outlets in place of the browser download link.
- ChatMedia gains a nullable fetchGeneratedMedia field (default null:
  previews/tests degrade to the unavailable line, so stack-only call
  sites merge unchanged).

17 new strings added to en/ru/zh-CN in one commit, mirroring en key
order (KEYSYNC clean; zh count equal — its pre-existing regional order
drift is untouched). 10 JVM tests cover routing (including case
sensitivity and null-mime), mount-gating, label/action mapping, cache
file name sanitizing (path traversal), the MockWebServer round-trip
with status mapping + cached-file short-circuit, and the time
formatter. Gate: :app:testDebugUnitTest :core:data:test
:core:protocol:test :app:lintDebug :app:compileDebugAndroidTestKotlin
BUILD SUCCESSFUL.

Co-Authored-By: Claude Code <noreply@anthropic.com>
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>

* fix(android): refine generic file MIME types from the filename

The file card passed the wire mimeType straight through to ACTION_VIEW,
substituting application/octet-stream only when the wire type was null
(r4370795783). Passing octet-stream explicitly defeats Android's viewer
matching: a PDF viewer registered for application/pdf is not matched by
an intent whose type says application/octet-stream, so PDFs (and every
other ordinary file whose hub type was octet-stream or missing) opened
with no eligible activity.

resolveFileMimeType now passes a specific wire type through untouched,
but when the wire type is missing, empty, or octet-stream (compared
case-insensitively) it re-derives the type from the original filename's
extension through an injected resolver — android.webkit.MimeTypeMap at
the call site, following the established AttachmentPreparer /
AndroidShareIntake pattern (lowercased extension, slash/wildcard sanity
check on the resolved value). Unknown extensions keep the generic
octet-stream fallback. The resolved type feeds both outlets: the Open
ACTION_VIEW intent and the Save ACTION_CREATE_DOCUMENT contract.

The resolver is a required parameter rather than a default, which keeps
GeneratedMedia.kt free of android.* imports and forces the seam: 3 JVM
tests drive it with a fake table (pdf->application/pdf via extension for
null/octet-stream/empty wire types; unknown extension and no extension
-> octet-stream fallback; specific wire types pass through untouched
even when the extension would map elsewhere). All three fail on the
pre-fix code by construction — resolveFileMimeType did not exist and the
null-wire PDF case asserted the old octet-stream handoff.

Gate: :app:testDebugUnitTest --tests GeneratedMediaTest BUILD SUCCESSFUL
(13 tests, 0 failures).

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

* fix(android): bound generated media cache names by UTF-8 bytes

sanitizedGeneratedMediaFileName capped the stem at 96 UTF-16 chars and
relied on that alone (r4370795787). Android filename limits are byte
limits (NAME_MAX 255): 80 hanzi + ".pdf" is a 122-char / 281-byte
component once the UUID imageId prefix is attached (verified against the
pre-fix logic: 36-byte id + 1 + 240 + 4 = 281 bytes), so long Chinese
names failed the atomic cache rename outright.

The complete component — id prefix + stem + extension — is now assembled
under a 255-byte UTF-8 budget, with pathological ids and extensions
capped at 64/32 bytes so the stem always keeps room. The stem keeps its
historical 96-char cap (ASCII names keep their exact prior shape), bytes
beyond the budget are cut from the stem only, on code-point boundaries,
and the extension always survives intact. The char-level whitelist
already drops surrogate halves (a lone half is never a letter), so every
surviving char is one complete BMP code point; the truncation helpers
are additionally pair-safe for any future code-point-aware whitelist.

JVM tests: the reviewer's UUID + 80-hanzi ".pdf" case lands at <= 255
bytes with the extension and id prefix preserved (red on the pre-fix
logic, which produced exactly 281); ".tar.gz"-style extensions survive
stem truncation; a battery of multibyte names re-decode byte-identically
under the cap; ASCII names keep their historical shapes ("i-" + 96 a's,
"img-1-media", "id-x.bin", "i-截图01.png").

Gate: :app:testDebugUnitTest --tests GeneratedMediaTest BUILD SUCCESSFUL
(16 tests, 0 failures).

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

* test(android): cover audio playback wiring and the file outlets' types

The play/pause/seek decisions and the MediaPlayer lifecycle lived inline
in the audio composable, which made them unreachable from JVM tests (no
emulator here; androidTest only compile-checks). Extract them into
GeneratedAudioSession over a GeneratedAudioPlayer seam — the app side
adapts android.media.MediaPlayer, tests pass a scriptable fake — and the
card now collects the session's flows, with DisposableEffect.onDispose
forwarding to session.release().

JVM coverage through the fake:
 - prepare wires the data source + prepareAsync and reports duration on
   the prepared callback; pre-preparation toggles/seeks stay inert;
 - the toggle maps to start/pause (turbine on the playing flow) and
   natural completion parks the row;
 - seekToFraction lands fraction*duration and clamps to [0, duration],
   reading the position back afterwards;
 - pollPosition only reads while playing (the 250 ms LaunchedEffect);
 - release — the dispose hook — releases the framework player exactly
   once across double-dispose, stops playback, and every later control
   call is inert (a released MediaPlayer throws);
 - player errors and a failing data source both map to the failed line
   and the row goes dead.

The file card's Open/Save construction moves behind generatedFileOutlets
so a JVM test pins that ACTION_VIEW and ACTION_CREATE_DOCUMENT both
carry the *resolved* MIME type (inferred pdf, generic fallback, specific
wire passthrough) plus the suggested save name — android.content.Intent
is not on the unit-test classpath. A MockWebServer fetch with the
reviewer's 80-hanzi + UUID name proves the byte-bounded component really
round-trips the local filesystem: under 255 bytes, extension kept, no
staging litter beside the final file.

These tests fail on the pre-change code by construction: the session,
seam, and outlets did not exist and the logic was not reachable from
the JVM. Explicit loading (loadsOnMount gate), authenticated caching
(hubGraph.session.imageClient: JWT + silent 401 re-auth + ETag cache),
and download cleanup (staged temp deleted on failure, atomic rename on
success) are untouched — only their test surface grew.

Gate: :app:testDebugUnitTest --tests GeneratedMediaTest BUILD SUCCESSFUL
(24 tests, 0 failures).

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

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: HAPI <noreply@hapi.run>
2026-11-02 18:09:49 +08:00
AnanovoandGitHub 3208199f99 fix(files): optimize exact path and directory search (#1778)
* fix(files): optimize exact path and directory search

* fix(web): preserve incremental file mention search

* fix(cli): contain recursive file search within workspace

* perf(cli): reuse canonical workspace path

* fix(cli): classify archived workspace file stats
2026-11-02 18:08:32 +08:00
AnanovoandGitHub 55f0f7b11d fix(web): dismiss fullscreen image previews on browser Back (#2191) 2026-11-02 18:07:10 +08:00
AnanovoandGitHub d4039081cd fix(web): collapse expanded composer immediately on submit (#1728) 2026-11-02 18:05:01 +08:00
AnanovoandGitHub 50b5e76e70 fix(web): allow retrying failed attachment uploads (#1722)
* fix(web): allow retrying failed attachment uploads

* fix(web): address attachment retry review feedback

* fix(web): respect attachment adapter retryability

* fix(web): preserve attachment order on retry

* fix(web): finish attachment retry review fixes

* chore: sync upstream main at a259ad3

* fix(web): preserve order across overlapping attachment retries

* fix(web): cancel and guard overlapping attachment retries
2026-11-02 18:04:45 +08:00
AnanovoandGitHub fe25c24d4e feat(web): add mobile attachment source picker (#1713)
* feat(web): add mobile attachment source picker

* fix(web): gate mobile attachment picker by adapter

* chore(web): trigger PR checks

* fix(web): start mobile attachment uploads concurrently
2026-11-02 18:04:26 +08:00
AnanovoandGitHub 8c602eb7a1 fix(cli,hub): prevent premature archive failures on Windows (#2126)
* fix(cli,hub): prevent premature archive failures on Windows

* fix(cli): preserve tree-wide forced shutdown escalation

* fix(cli): stop disconnected survivor subtrees completely

* test(hub): assert structured archive cleanup uncertainty

* fix(cli): use invariant Windows process markers

* fix(cli): attempt Windows termination when CIM fails
2026-11-02 18:03:26 +08:00
480a476e9b feat(web): give every harness the same effort control (#2261)
Effort looked and behaved differently per harness. Codex and OpenCode
had no toolbar button and called it "Reasoning effort", Claude called the
unset choice "Auto" while others said "Default", Chinese used both 思考强度
and 推理强度, and the status bar and header showed effort only for
Codex, OpenCode and Pi.

- Codex/OpenCode get the same toolbar effort button as Claude; it opens
  the same anchored Effort section.
- Every effort picker is titled Effort (推理强度), and the unset choice is
  Default everywhere. An unset toolbar button reads "Default effort".
- The status bar, header, shared-turn metadata and Codex agent tool cards
  use one "effort <level>" label. Claude and Grok now show their effort,
  with "default" when unset; Pi and AGY show it only when set, since
  their models may not take one.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:01:39 +08:00
bb4b136f60 feat(cli): switch Claude effort without restarting the process (#2262)
* feat(cli): switch Claude effort without restarting the process

Changing effort in a remote Claude session made the next prompt restart
Claude with --resume and a new --effort flag, so the switch cost a
process start and a slower first reply. Claude Code's apply_flag_settings
control request changes the session effort in place (null restores the
model default), the same way set_permission_mode already changes modes.

The launcher now applies an effort-only change to the running process
before delivering the prompt. Any other process-level change, a refused
request, or no reply within 5 seconds keeps the existing restart path,
so Claude Code builds without the request still work.

via [HAPI](https://hapi.run)

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

* fix(cli): keep the prompt when Claude exits during a live effort change

The launcher awaited the effort control request with the dequeued batch
held only in a local. If Claude exited before replying, the attempt
ended, and the late continuation handed the batch to the closed
claudeRemote, which dropped it.

Park the batch in `pending` before awaiting and take it back only when
Claude applied the change and its process is still open. Otherwise the
next attempt delivers it, starting with the new effort.

via [HAPI](https://hapi.run)

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

---------

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:00:53 +08:00
weishu 1fcce105df fix(native): hide empty reasoning blocks 2026-11-02 14:37:17 +08:00
7f5d6b17f3 feat(peer): spawn-peer remit + rename-proof Parent UUID stamps (#1922)
* feat(cli): spawn-peer with required remit and MCP spawn_peer

Machine spawn creates an empty composer; stuffing message into that
JSON is stripped. Add hapi spawn-peer and MCP spawn_peer that spawn,
rename, deliver via the ping-peer path, and fail closed unless the
remit is on the new session. Reject message/prompt/text on machine
spawn with 400. Do not auto-approve spawn_peer in default/read-only.

Fixes #1509

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): reject overlong spawn-peer names before spawn

Hub rename max is 255; continuing past PATCH 400 left a live session under a different title. MCP/steer copy now says the hub 400s a spawn-body remit instead of stripping it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): wait for fresh spawn-peer child instead of resuming it

Machine spawn can return while the hub row is still inactive. ping-peer then POSTed /resume, which can launch a second agent because the original spawn has no existingSessionId for runner dedupe.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): reject flavor-illegal permissionMode before spawn-peer

Codex + bypassPermissions (and Pi + any mode) used to reach the runner and fail after a child existed, or silently drop the mode. Check isPermissionModeAllowedForFlavor when both agent and mode are explicit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): treat omitted spawn-peer agent as Claude for permissionMode

Hub and runner default agent to claude when spawn omits it. Validate permissionMode against that effective flavor so yolo/read-only fail closed before a child starts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): resolve spawn-peer dir locally and archive failed children

Relative --dir values were forwarded unchanged, so the runner resolved them against daemon cwd. Remit delivery failures also left the new session running, so a retry spawned a duplicate. Resolve in the caller and best-effort archive the child before rethrowing.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): verify remit before archiving a failed spawn-peer child

A timed-out ping-peer POST can still land the remit. Check the transcript before archive, and only say the child was archived when the hub returns ok.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): swallow spawn-peer transcript GET errors and skip unapplied names

A thrown messages GET after spawn skipped archive and leaked a live child. Treat transport errors as a miss so the verify loop can retry, then clean up. Also do not return a requested name the hub never applied.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(spawn-peer): hub peerSpawnDefaults + model/effort spawn surface

Add hub settings peerSpawnDefaults (agent, permissionMode, per-flavor models)
with stock claude/yolo/sonnet fallbacks. spawnPeer resolves explicit args →
hub settings → stock, maps yolo to flavor equivalents, and forwards model/effort
into machine spawn. Settings UI under General → Agents; MCP/CLI optional overrides.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(hub): use cursor-valid permission mode in peer spawn defaults test

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): teach spawn_peer that omit permissionMode means yolo

MCP copy said "pass permissionMode only when the operator asked", so agents
omitted it and got hub/stock whatever was stored — often approval-gated
default. Clarify omit = yolo via peerSpawnDefaults/stock; pass only to tighten.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,web): apply peerSpawnDefaults to machine spawn and New Session

POST /api/machines/:id/spawn now resolves omitted agent/permissionMode/model
from hub Settings, and New Session seeds from the same peerSpawnDefaults so
UI create and peer spawn share one authoritative default (stock yolo).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): NewSession hub seed respects sticky prefs + QueryClient in tests

Sticky localStorage last-used agent wins over hub seed; machine spawn still
applies peerSpawnDefaults server-side. Tests provide QueryClientProvider.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): mock CREATABLE_AGENT_FLAVORS for settings general peerSpawn UI

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): stabilize NewSession tests after hub peerSpawnDefaults seed

Wrap remaining mounts in QueryClientProvider, pre-seed hub settings so a
late useQuery resolve cannot wipe in-test model picks, and use neutral
stock permission defaults in the fixture.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): address tip Codex Majors for peerSpawnDefaults

Preserve explicit yolo booleans on machine spawn, fail closed when hub
defaults cannot load, validate permission modes against the resolved
agent, remap auto-approval across flavors, and stop late hub settings
from wiping New Session edits. Reject retired agents in spawn defaults
and restore the CLI executable build docs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): address follow-up tip Codex Majors

Stop absent Yolo localStorage from beating hub defaults, track New Session
edits before late hub seed, reject incompatible machine-spawn permissions,
resolve MCP spawn_peer paths against the session working directory, and
hide unsupported Codex safe-yolo from Settings spawn defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): clear tip-2 CI and follow-up Codex Majors

Omit permissionMode for Pi/DSH, preserve explicit Yolo-off across delayed
hub seed, fix settings test mocks for launch permission helpers, and
restore unrelated CLI README lifecycle/ACP docs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip-3 Majors for seed edits and launchable modes

Skip hub agent seed after permission edits, resolve inherited modes via
the launch catalog (AGY request-review fallback), preserve hub Cursor
models through preference restore, and restore Codex auth README nuance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minors for Cursor/Grok hub permission seeding

Give Cursor the native permission select so Plan/Ask survive machine
spawn, and re-apply Grok hub permissions after agent-init resets.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Minors for Cursor select and hub seed remap

Map hub permission through resolvePermissionModeForFlavor, keep native
Default when agent is explicit without a model, and assert Cursor Plan/Ask Mode labels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minors for delayed hub seed and Default model

Apply hub permission/model to unset fields even with a sticky agent,
preserve explicitly saved auto models, and seed OpenCode/AGY selectors
from hub defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Minors for model edit sticky and clear override

Mark OpenCode/AGY model picks as edited so delayed hub seed cannot
overwrite them, and treat empty hub model values as clear sentinels.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Majors for models patch typing and remit page scan

Type the models patch as NonNullable and paginate transcript verification
oldest-ward so a busy child is not archived when the remit leaves page 1.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Minor — keep agent after explicit model pick

Do not apply a late hub default agent when the operator already chose a
model; otherwise preference restore drops that selection.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(spawn-peer): tip Cursor YOLO migrate and Codex effort map

Bridge Cursor's saved YOLO toggle (incl. false) into native Default over
hub yolo, and send Codex/OpenCode --effort as modelReasoningEffort.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tip Majors — scoped YOLO bridge and catalog fallback

Keep unsupported saved permission modes at Default instead of hub yolo,
and apply delayed YOLO migration only when the sticky bridge agent matches.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): drop rebase conflict markers in startHappyServer

Both sessionDisplayRename and spawnPeer imports are required after
rebasing onto upstream rename work; markers had slipped into tip.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): wrap Kimi NewSession tests in QueryClientProvider

Hub settings useQuery requires a provider; upstream Kimi catalog tests
rendered bare and broke after the spawn-peer rebase onto main.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(peer): rename-proof Parent UUID stamp on spawn remits

Orchestrated spawn_peer / spawn-peer remits now auto-stamp a durable
[title](/sessions/<uuid>) Parent chip (fail-closed in-session). MCP copy
forbids inventing titles; UUID stays identity after parent rename.

Refs heavygee/hapi#175

Co-authored-by: Cursor <cursoragent@cursor.com>

* style(peer): plain hyphen in Parent-stamp warning and test comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): reject blank remit before Parent stamp

Codex review on #1922: stamping first turned empty remits non-empty and
bypassed the idle-session guard. Also only treat ## Parent blocks as
already-present so bare /sessions citations still get the chip.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): gate New Session Create on hub defaults; require Parent chip

Codex tip review on #1922: block Create while getHubSettings is pending so
stock mount defaults cannot bypass restrictive hub peerSpawnDefaults; skip
Parent stamp only when ## Parent already has a markdown session chip; clarify
codex resume takes a native thread id.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): resolve MCP spawn cwd; Agents settings section

Codex Major on #1922: spawn_peer relative directories now prefer the
launcher cwd (Codex --cd), then skillLookup, then session metadata.path.
Move peerSpawnDefaults UI into the unused Agents settings section.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): pass session cwd to MCP spawn_peer; Agents settings section

Codex tip review on #1922: resolve relative spawn_peer directories from the
launcher working directory (Codex --cd), skillLookup, then metadata.path;
move peerSpawnDefaults UI into the Agents settings section.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): skip archive on unread transcript; validate startingMode after hub agent

Codex tip review: do not archive a child when remit verification cannot read
the transcript; run AGY/DSH remote-only startingMode checks against the
resolved hub agent; update MCP bridge test expectations for workingDirectory.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): treat exhausted remit pagination as unverifiable

Hitting the messages page cap with hasMore still true must not count as an
observed-empty transcript — that would archive a child whose remit may still
exist on older pages.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(cli): list HAPI_API_URL as optional with localhost default

Codex tip review: the README had moved HAPI_API_URL under Required even
though configuration defaults it to http://localhost:3006 (and settings can
supply a URL). Also drop trailing whitespace flagged by git diff --check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): re-verify empty transcript before archiving failed spawn

An earlier observed-absent page plus later unread GETs must not archive a
child whose remit may have landed after the first empty read.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): never auto-archive on spawnPeer failure path

Timed-out remit POSTs and empty-read/archive TOCTOU races can still land
work on the child. Leave the session running with its id for inspection
instead of terminating an in-flight peer.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): classify empty_session from final remit verify

An earlier empty transcript read must not stick as empty_session once
later message GETs become unavailable — report verify_failed instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): recognize escaped brackets in Parent chip labels

Titles with ] were escaped in the chip label but the idempotency regex
stopped at the first raw bracket and re-stamped a second Parent block.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): avoid Parent chip regex backtracking on backslashes

Exclude \\ from the single-char label alternative so escaped pairs have
one parse path — long nonmatching backslash runs no longer explode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(cli): MCP/CLI spawn_peer --machine for cross-host remits

Wire optional machine (UUID or hostname via GET /api/machines) through
MCP spawn_peer and hapi spawn-peer into existing spawnPeer({ machineId }).
Skip local directory existence checks for cross-host targets to match the
estate wrapper; keep fail-closed remit verify.

Fixes tiann/hapi#1931

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): reject ambiguous spawn --machine label matches

Tip bot Major on #1922: hostname/displayName selectors that match more
than one online runner now fail closed with ambiguous + UUID guidance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): preserve cross-OS absolute dirs for spawn --machine

path.resolve on the caller OS was rewriting foreign absolute roots
(C:\… on Linux, /srv/… on Windows) before the hub spawn POST. Detect
POSIX or Windows absolute paths and only resolve relative directories.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(peer): resolve spawn dirs after local vs remote is known

Defer directory resolution until the target machine is selected. Remote
spawns still preserve foreign absolute roots; local spawns use native
path.resolve so Windows drive-less paths like \repo bind to the caller
drive.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): apply delayed DSH model defaults without replacing edits

* fix(web): preserve hub permission defaults across form remounts

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: weishu <twsxtd@gmail.com>
2026-11-02 13:17:22 +08:00
weishu dc08608fdc feat(ios): add @ session and file references 2026-11-02 12:16:25 +08:00
bd3fb24811 feat(android): global connection and runner version-skew banners (extracted onto main) (#2205)
* feat(android): global connection and runner version-skew banners

Two Home-screen chrome banners mirroring the web reference banner stack:

- Global connection banner: folds the SSE engine's attributed failure
  notice (reconnectNoticeFailure, 4s grace) with the resync lifecycle
  into one notice - Syncing (300ms debounce, 10s auto-clear cap,
  depth-counted episodes) suppresses Reconnecting, which labels the
  outage reason (heartbeat timeout / visibility recovery / connect
  timeout / transport error with HTTP code / closed). The engine now
  attributes every attempt end into ConnectionState.lastFailure,
  cleared on the next successful handshake.
- Runner version-skew banner: capability-set comparison
  (RunnerSkew.REQUIRED_MACHINE_CAPABILITIES, not semver) flags runners
  missing agent-availability/cursor-chat-store-status; expanded card +
  minimized chip, snooze 1h, manual restart via new
  POST /api/machines/:id/restart-runner (restart gated on
  newer-binary-on-disk mtime drift AND supervised restart).

StoreSyncTargets grows an onResyncEvent lifecycle hook (default no-op)
feeding the syncing half; HomeScreen grows optional chrome params
(null hides each banner).

Declared divergences from web/src:
- Banners mount on Home only, not above every route: an open chat
  already surfaces its own pipe state ("Reconnecting... Tap to retry"),
  so the two never double up on one screen (web mounts App-wide).
- The web OfflineBanner is not ported: a native app has no browser
  online/offline event pair; hub reachability is expressed through the
  reconnecting banner.
- Minimize/snooze state is process-lifetime memory (web: sessionStorage
  - same session-scoped lifetime per platform); the snooze timer does
  not survive process death.
- Runner rows filter only on capability skew; the active filter lives
  upstream in MachineStore (web filters machine.active on its side).

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

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Fix codeless transport attribution and banner polish from review

- SseEngine: a codeless Failure (DNS/TLS/socket errors — the dominant
  mobile outage shape) now attributes TransportError like the web's
  unconditional onerror → transport-error mapping, instead of degrading
  to a "connection closed" label.
- ConnectionChrome: a resync restart while the syncing banner is
  already shown keeps it shown (web doStartSync reshuffles timers with
  isSyncing staying true — no blink); the web's first-connect/30s-from-
  background display gating is now a declared divergence.
- RunnerSkewBanner: the expanded card scrolls past a 320dp cap (web
  40vh) so many skewed hosts cannot push the session list off-screen;
  restart failures surface the hub body's parsed error field instead
  of raw embedded JSON; handoff-hint/tooltip omissions declared.

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

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Show the reconnecting banner for auth-side outages with no failure reason

Review finding (ConnectionState.kt): a paired hub starting with a stale
JWT whose token refresh keeps failing cycles SseEngine Backoff without
any transport attempt running, so lastFailure stays null — after the 4s
grace the notice flow emitted null and ConnectionChrome read "no
banner". Home could sit disconnected indefinitely with no notice.

Outage visibility now lives on its own marker, independent of the
optional reason: reconnectOutageNotice (was reconnectNoticeFailure)
emits OutageNotice(lastFailure) once the grace elapses — non-null even
when no attempt attributed a reason — and ConnectionChrome maps any
OutageNotice to Reconnecting(failure), so a reason-less outage renders
the plain "Reconnecting…" strip (web shows the banner on sseDisconnected
regardless of reason; the parenthetical label simply drops).

Coverage added per review:
- repeated null-token retries keep the notice visible (engine level);
- null-reason outage still emits a notice after the grace (state level);
- outage without a reason still shows the banner (chrome level);
- the notice hides while backgrounded and returns with the foreground.
Resync debounce/cap and runner-restart error paths were already covered
(a sync shorter than the debounce…, a stuck sync auto-clears…, restart
failure surfaces the message…).

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

---------

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 11:37:47 +08:00
weishuandGitHub 7bb2eb914f feat(claude): mid-turn Steer for remote Claude sessions (#2259)
* feat(claude): mid-turn Steer for remote Claude sessions

Queued messages can now be steered into a running Claude turn, the same as
Ctrl+X Ctrl+S in the Claude TUI. The row is written to the live stream-json
stdin and Claude folds it in at its next tool boundary.

- Spawn Claude with --replay-user-messages and tag every stdin message with
  a uuid; the echo acks pickup and is never relayed to chat
- A result that arrives while a steer is still unacked does not end the
  turn: Claude runs a follow-up turn for it, so ready waits for that result
- Launcher registers steer-queued-message: reserve the row, reject control
  commands and mode mismatches, ack the hub after the write, mark consumed
  (steered) on the echo; abort before pickup holds the row indeterminate,
  an unprompted exit requeues it
- Open the shared steer gate and peer/hub wording to Claude (remote only)

* fix(claude): retire completed input before a steer follow-up turn

- Generalize onCompactResultAccepted to onResultAccepted and fire it when a
  result arrives with a steer still unacked, so a stream failure during the
  follow-up turn recovers only the steer instead of replaying the finished
  prompt
- Close the steer target and settle pending steers when query() setup
  throws, so a retry backoff cannot accept a steer nobody will read
2026-11-02 10:12:14 +08:00
weishu 7ba52b9a5a Release version 0.33.6 2026-11-01 20:30:00 +08:00
weishu 679a2e36ca feat(cli): show images agents view inline in chat
Codex view_image (app-server imageView items) and Claude Code tool results
with image blocks (Read of an image, screenshot tools) now emit
generated-image messages tied to the tool call, so web/iOS/Android render
what the agent looked at instead of only a path. Claude transcript lines
forwarded to the hub drop the duplicated base64 payloads.
2026-11-01 20:29:37 +08:00
weishu da5dffd8ec perf(ios): stop main-thread stalls from the session list on large hubs
Profiling a 2,745-session hub while scrolling a chat showed the two
longest main-thread stalls (~80 ms) came from the session list, not the
transcript:

- The home list, covered by the pushed chat, still rebuilt and diffed
  every row on each session change. A covered list now keeps its last
  rows and refreshes once on return; a side-by-side split stays live.
- DiskCache encoded the 2 MB session snapshot on the main actor after
  every burst of changes. Encoding now runs with the file write, off it.

After the change the trace has no session-list or snapshot work on the
main thread and no stall over 50 ms (max 38 ms, from Markdown cells
entering the screen).
2026-11-01 20:29:37 +08:00
weishu e9cbd8499b fix(ios): size the queued card to its rows and skip it for idle sends
The queued card's ScrollView is greedy, so one row still took the full
140 pt cap; measure the rows and size the card to them, capped at ~3.

Sends dispatched while the agent is idle no longer flash through the
queued bar while invokedAt is still null: the interactor records them
before the POST (the hub flips thinking on as soon as it queues), the
thread renders them, and after a 5 s grace a still-uninvoked row moves
to the bar as genuinely queued.
2026-11-01 20:29:37 +08:00
weishu c78cfa9e11 perf(ios): skip unchanged session rows on list updates
Any session change (even an offscreen one, e.g. a streaming agent)
re-ran every row's content (button, swipe actions, context menu), so one
update cost O(all rows): ~30 ms at 300 sessions in a Release simulator
build. Rows now compare only what they draw and skip unchanged content
(~4-6 ms, flat in the row count), and the minute tick redraws only each
row's age label instead of rebuilding the list.
2026-11-01 20:29:37 +08:00
AnanovoandGitHub b8a13b044a feat(web): show unavailable Agents on demand (#1798)
* feat(web): add unavailable Agent visibility toggle

* feat(web): show unavailable Agents on demand

* chore: retrigger PR checks

* fix(web): keep unavailable Agent disclosure order
2026-11-01 20:08:37 +08:00
weishu 697f4930ee feat(android): question card like iOS
AskUserQuestion / request_user_input get their own card instead of the
generic tool card with an approval banner: one question per page,
outlined option rows with a Recommended badge, a collapsed other/note
field and a single primary action. Settled questions collapse to an
answer summary that opens the inspector. Wire answers and the sign-in
URL confirmation are unchanged.
2026-11-01 16:54:49 +08:00
weishu 5e9694f6fc fix(android): keep the session list entry refresh silent
The list screen is composed as soon as a predictive back gesture starts
previewing it, so the entry refresh flashed the pull-to-refresh spinner
on every back swipe. Only user-initiated refreshes show the indicator.
2026-11-01 16:39:27 +08:00
weishu 2ac959d51a feat(ios): compact queued-message card above the composer
Replace the full-width queued bar with a floating card stacked on the
composer, following the Codex/Claude Code/Cursor convention: one-line
rows with icon actions (bolt to steer, retry, cancel), tap a row to
edit, long-press for the full menu, and animated insert/remove.
2026-11-01 16:31:36 +08:00
weishu f69c9961fd feat(ios): refine the chat composer
- Collapse the empty, unfocused composer to one row; anything in flight
  (focus, draft, chips, schedule, recording, scratchlist) expands it
  without dropping focus.
- Bare 20 pt tool symbols with color-only states; only send/stop is a
  filled 32 pt circle. Both scale with Dynamic Type.
- Fix the schedule menu reading as active: Menu tinted its relative
  `.secondary` style.
- Stop uses the accent instead of alarm red.
- Liquid Glass card on iOS 26 (damped so text behind the short pill
  stays out of the placeholder); hairline edge on earlier systems.
- ⌘↩ sends from a hardware keyboard, gated like the Send button.
2026-11-01 16:24:47 +08:00
weishu 3b6f6d151b feat(android): refresh the session list like iOS
- Second section is Recent with compact headers; swipe to pin/unpin and
  archive or delete; Mark as Read in the long-press sheet
- 30dp agent icon with a presence badge (pulsing while running); no dimmed
  rows, row spinners or unread dot (semibold title + accent time)
- Transient connection status under the title after 2s; a failed refresh
  shows "Offline · updated …" with Retry
2026-11-01 16:00:56 +08:00
weishu 832c5922f2 feat(web): align session rows and connection banners with native apps
- Agent icon spans both lines with a presence badge (pulsing while a turn
  or background work runs); no dimmed rows or row spinners
- Unread is a semibold title plus accent time instead of a dot; pending
  requests are amber hand/bubble symbols, keeping one dot per row
- Reconnecting/syncing banners appear after 2s; reconnecting is neutral,
  amber stays for offline
2026-11-01 16:00:56 +08:00
weishu e940439ecf feat(ios): quieter home connection status
- Transient SSE states appear only after 2s, as the iOS 26 nav subtitle
  (a gray line with a spinner where no title is shown), so the list
  never shifts on routine reconnects
- Only a failed list refresh is amber: "Offline · updated …" with Retry
2026-11-01 15:48:18 +08:00
weishu 6ed83eda3c fix: show unread for running sessions
Running sessions previously suppressed the ordinary unread dot, hiding
answers the user had not seen. Unread is now
manualUnread || contentRevision > readRevision on web, iOS and Android.

Web rows draw the running/background spinner beside the unread dot, and
unread outranks background status. Because session patches arrive before
the message they count, a chat following its visible tail hides its own
ordinary dot until the rendered acknowledgement lands (display-only; web
and iPad split view).
2026-11-01 15:39:46 +08:00
weishu 85a3cfb40f fix(ios): return the session list to an inline title
The large title only cost vertical space once the second section was
renamed to Recent; the inline title shares the toolbar row.
2026-11-01 15:35:20 +08:00
weishu 1ab77530fd fix(ios): mark unread rows without a second dot
- Unread is a semibold title plus an accent timestamp, so the presence
  badge stays the row's only dot and timestamps share one column
- Compact section header insets and default min header height
- README: the session list uses a large collapsing title
2026-11-01 15:33:39 +08:00
weishu cf592b8483 feat(ios): refresh the session list layout
- Large collapsing title; rename the second section to Recent
- Swipe actions: pin/mark read (leading), archive or delete/reopen (trailing)
- Two-line agent icon with a presence badge (pulses while running) instead
  of dimming disconnected rows and per-row spinners
- Larger timestamps, compact section headers, glass-friendly filter icon
- Drop the pixel-level row presentation tests
2026-11-01 15:18:09 +08:00
AnanovoandGitHub ecf40d8851 feat(web): fork active and archived sessions from the session list (#2258)
* feat(web): fork active and archived sessions from the session list

* fix(codex): preserve fork titles during history replay

* fix(web): limit list forks to supported Codex sessions
2026-11-01 14:52:42 +08:00
weishu ba2b5c5651 Release version 0.33.5 2026-11-01 13:19:38 +08:00
weishu c94a968b81 fix(android): observe platform IME state in home search tests 2026-11-01 12:56:13 +08:00
weishu b0d01c5307 Release version 0.33.4 2026-11-01 12:26:43 +08:00
weishu 5a45b1cd2f fix(ios): recover inactive sessions during attachment uploads 2026-11-01 12:26:32 +08:00
weishu f4d8faebea feat(ios): support agent-displayed video, audio and files 2026-11-01 12:26:32 +08:00
weishu 59dcddf32b fix(codex): support queued async user questions 2026-11-01 10:34:36 +08:00
AnanovoandGitHub 46bae9b0f1 fix(codex): fork archived sessions without reopening the source (#2231)
* fix(codex): fork archived sessions without reopening the source

* fix(codex): reconcile interrupted archived fork recovery

* fix(codex): release rejected forks and serialize source startup

* fix(codex): fence unconfirmed resume startup across retries

* test(codex): validate durable resume recovery and serialize archive

* fix(codex): block local resume of pending archived fork sources

* fix(hub): coalesce concurrent resume requests to preserve idempotent startup

* fix(hub): bypass startup coalescing for PTY sessions
2026-11-01 09:55:01 +08:00
AnanovoandGitHub 639f71b6a6 test(android): name the IME phases and upload instrumentation reports (#2256)
* test(android): name the IME phases and upload instrumentation reports

* test(android): report Compose's IME inset height on failure

* test(android): import the WindowInsets.ime extension used by the diagnostic
2026-11-01 09:54:30 +08:00
Junmo KimandGitHub be41e854e0 feat(codex,opencode): show compaction summaries and token counts (#2249)
* fix(chat): render available compaction facts

* feat(opencode): unify native compaction summary cards

* fix(opencode): report actual compaction application lifecycle

* feat(codex): render native compaction checkpoints and metrics

* fix(chat): render compaction summaries and token facts in native clients

* fix(opencode): preserve transcript priming across read failures

* fix(opencode): recover snapshot-only replies after attachment
2026-11-01 09:54:10 +08:00
9c6639c3c3 feat(hub): title untitled sessions with their first prompt (#2252)
New sessions showed the working directory name until the first turn
finished and a generated or native title arrived. The Hub now records
the first non-command user prompt as metadata.promptTitle, with
whitespace collapsed and capped at 80 characters, and the web shows it
after name and summary but before the path fallback.

The prompt title is Hub-owned and kept outside summary, so the existing
"only while untitled" title sources (native ai-title, change_title, the
remote prompt fallback and automatic suggestions) still apply and
replace it. It is published as a versioned metadata patch, so it does
not race the thinking patch sent while the prompt is accepted.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:53:35 +08:00
AnanovoandGitHub 3e628cad5d fix(test): make shared launch path assertions cross-platform (#2255) 2026-11-01 09:53:23 +08:00
weishu 5ef4304a4a fix: synchronize read state across web and native clients
Track readable content revisions and durable read cursors in the hub. Acknowledge only rendered foreground tails, persist offline read operations, and preserve newer manual unread choices across devices.

Migrate existing history to a read baseline and cover pagination receipts with shared native conformance fixtures.
2026-11-01 09:52:51 +08:00
weishuandGitHub ee4ac238cb feat(ios): move hub controls into Settings and new session beside search (#2257) 2026-11-01 09:11:39 +08:00
SSU-WEI HUANGandGitHub f8e55fb930 feat(agy): reuse a persistent headless stream process (#2248) 2026-10-30 19:11:26 +08:00
013ace8e88 fix(cli): show resolved versions in Claude model labels (#2245)
Co-authored-by: Kiyoshi Guo <kiyoshi.guo@bytedance.com>
2026-10-30 14:37:59 +08:00
SSU-WEI HUANGandGitHub 5fcd4a067a fix(agy): separate model and effort selection (#2244)
* fix(agy): separate model families and reasoning effort

* fix(agy): report startup before model discovery
2026-10-30 07:36:13 +08:00