Use authoritative session.idle and session.error events for notifications
while retaining legacy message.updated handling for compatibility.
Classify sessions through targeted, directory-aware session lookups instead
of fetching the full session list. Cache confirmed root and parent session
relationships without treating failed lookups as root sessions.
Honor subagent completion settings and templates across the server-driven
web, desktop, and mobile paths, and bring the VS Code webview notification
policy to feature parity.
Use freshly synchronized VS Code settings, retry failed settings syncs,
extract session error messages, and deduplicate authoritative and legacy
completion and error events.
Adds /craft-goal autocomplete and chat handling for starting a Goal crafting session.
Introduces new Magic Prompts content and localized labels/descriptions for Goal crafting.
Migrates desktop draft starters to include Craft a Goal once and persists the migration marker.
* fix(mobile): always mount SessionSidebar to eliminate >10s drawer open delay (#1695)
On mobile (Android PWA), SessionSidebar was conditionally mounted via
{mobileLeftDrawerVisible && ...}, causing the component to unmount on
drawer close and remount on every open. Each remount fired a full
data-loading cascade: paginated sessions fetch (PAGE_SIZE=500 with
retry), worktree discovery, repo status, PR status, 10+ useMemo
recomputations, and localStorage reads, manifesting as a >10s delay
before the drawer became interactive.
Desktop already avoided this by keeping SessionSidebar always mounted
inside <Sidebar> with a CSS visibility toggle.
Fix: remove the mobileLeftDrawerVisible conditional wrapper so
SessionSidebar stays mounted on mobile too, matching desktop behavior.
Visibility remains controlled by the leftDrawerX transform (off-screen
when closed). Added pointer-events-none when hidden as a defensive guard.
Added a regression test that fails if the conditional mount pattern is
reintroduced around the mobile SessionSidebar.
* fix(mobile): hide closed drawer to avoid rotation offset leak
---------
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
Compaction fixes (observed in a real long run):
- the summary message's zeroed tokens froze the goal counter at its
pre-compaction value; segments now close with the previously displayed
total as a continuity floor
- audits and continuations after a summary tail now take execution params
(provider/model/agent/variant) from the newest non-summary assistant
turn instead of inheriting agent 'compaction' and the summarize model
File-backed objectives:
- the objective text lives in <data-dir>/goals/<sessionId>.md, keyed by
session id (one goal per session, a new goal overwrites the file);
metadata carries only an objectiveFile flag so session.updated fanout
stays light, and never a path — ids are pattern-validated before any
filesystem access
- limit raised to 5000 chars, no snapshot field: the UI fetches content
via PUT/GET/DELETE /api/goals/objective/:sessionId (behind the blanket
/api auth gate), writes the file before stamping metadata, and falls
back to an inline objective when the write fails
- the loop reads the file fresh on every tick, so objectives are
live-editable mid-goal; a missing file falls back to the inline text
- scheduled goal tasks write the objective file server-side; VS Code
degrades to the audit note (route unavailable there by design)
Arm the target button in the composer and the next prompt becomes a goal:
the server keeps the session working toward it (idle tick -> small-model
audit -> continuation) until the objective is verifiably complete, blocked,
or out of budget — even with the UI closed.
Server (packages/web/server/lib/session-goal):
- event-driven loop on the global SSE hub; goal state lives in
session.metadata.openchamber.goal (merge-safe patches, stale-write guard
by goal id), so it survives restarts and syncs to every client for free
- the small-model audit (objective + last assistant turn only, language
pinned to the objective) is the sole termination authority; blocked needs
3 consecutive verdicts, audit outages tolerate one unaudited continuation
then stop the goal as resumable-blocked
- hard stops: optional token budget, auto-continuation cap (Resume grants a
fresh allowance), turn errors; user abort pauses the goal instead of
blocking it, and resuming over an aborted tail nudges immediately
- token accounting as a snapshot of the latest turn (input + cache.read +
output), goal-relative via a creation baseline and segmented across
compactions; a compaction summary skips the audit and continues
- continuations reuse the session's own provider/model/agent/variant
UI:
- three-mode target button (arm / disarm / manage dialog), informational
goal strip with inline pause/resume and an Evaluating indicator, sidebar
state glyph, objective length counter (2000-char server clamp),
read-only completed goals
- goal entry points: composer (sessions and drafts), start-new-session-
from-answer dialog, plan implement dialog (plan content becomes the
objective), scheduled tasks (Run as goal + budget)
- Settings -> Chat -> Goal: feature toggle + default token budget with
three-layer parity (web server, client persistence, VS Code bridge);
VS Code renders goal state but hides the entry points (the loop runs in
the web server only)
Notifications: per-turn "ready" notifications are suppressed while a goal
is active; settling sends one final notification (desktop, web-push, APNs
generic titles with the session name as body) honoring the completion
toggle. Error/question/permission notifications are untouched.
Docs: user guide (session-goals) in all 9 locales + sidebar entry,
scheduled-tasks cross-reference, server module DOCUMENTATION.md.
* docs: add SDK v1.17.12 migration plan — phase 4 (session.permission)
* feat(permissions): verify pending permission before auto-accept via SDK v1.17.12
Adds createPermission() and fetchPermission() wrappers on OpencodeService
for the new v2.session.permission endpoints (OpenCode SDK 1.17.12).
fetchPermission() is used by the auto-accept sweep in
resyncBlockingRequestsForDirectory to verify a permission is still
pending before replying. The auto-accept flow now skips permissions
that are already resolved, returning a null from fetchPermission()
rather than blindly calling respondToPermission on a stale entry.
createPermission() is exposed for future programmatic permission
creation; the V1 list/reply path used by the UI is unchanged.
The plan doc at plans/opencode-v1.17.12-sdk/ was rebased onto
origin/main in the prior commit to keep the PR diff focused on
this change.
Closes#1972
* fix(permissions): drop confirmed-resolved permissions from auto-accept resync
fetchPermission() now returns a tagged FetchPermissionResult so the
auto-accept loop can distinguish a server-confirmed 404 (the
permission is no longer pending) from a fetch failure (network error
or pre-v1.17.12 server). Previously both cases collapsed to null, so
a permission the server had already answered would still appear in
the resync output and trigger a spurious 'Permission needed' toast.
The auto-accept loop in resyncBlockingRequestsForDirectory now tracks
both accepted and resolved permissions, then drops both from the
'grouped' map before it falls through to the toast path. On a
pre-v1.17.12 server (no V2 endpoint) the call still returns
'unknown' and the permission stays in the resync output so the user
can answer manually — fail-closed, no false-resolved signals.
Adds a focused unit test for fetchPermission (4 cases: 200 ok, 404
resolved, 500 unknown, network throw) mocking the V2 SDK client
shape.
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* perf(worktree): skip unchanged store updates and content-aware persist
- Add content-aware equality check before setState in all three discovery
loops (SessionSidebar, ElectronMiniChatApp, MobileApp). Compares
Map size and per-entry length + element references — avoids triggering
16+ subscriber re-renders when discovery finds the same worktrees.
- Add content-hash guard to persistWorktreeMap subscription with try-catch.
Avoids redundant localStorage writes when the Map reference changed but
the content is identical. Serialization errors are caught and skipped.
Contributes to #1990
* perf(worktree): extract shared worktreeMapsEqual, fix comparison, avoid double serialization
- Extract worktreeMapsEqual() into worktreeManager.ts as a shared utility
comparing worktree maps by path (not reference identity). This replaces
the inline reference-comparison logic in all three discovery loops
(SessionSidebar, ElectronMiniChatApp, MobileApp) that was ineffective
because readStableProjectWorktrees creates new object instances on
each call after cache expiry, making item !== value[i] always true.
- Pass pre-serialized JSON to persistWorktreeMap to avoid double
JSON.stringify on every persist. The subscriber already computes the
serialized string for the content-hash check; pass it through instead
of re-serializing inside persistWorktreeMap.
- Deduplicate 3 copies of the same comparison logic into the shared util.
* refactor(worktree): make worktreeMapsEqual generic over path-bearing type
The helper's equality contract is element-wise path comparison,
not anything specific to WorktreeMetadata. Generifying on
`T extends { path: string }` documents the contract at the type
level and keeps it reusable for any future map-of-arrays shape
that has a path field. Call sites stay compatible since
WorktreeMetadata has a required `path: string`.
No runtime change.
* refactor(worktree-store): clarify persist hash name and signature
Drop the optional preSerialized parameter from persistWorktreeMap —
its only caller (the subscriber) already builds the serialized
string for the content-compare, so the dual-path body is dead code.
persistWorktreeMap now takes the serialized string directly.
Rename lastPersistedWorktreeHash → lastPersistedWorktreeSerialized
(the variable holds the full JSON string, not a hash) and drop the
try/catch around JSON.stringify: it cannot realistically throw on
Map.entries() of WorktreeMetadata (no circular refs, no BigInt, no
custom toJSON). The try/catch around setItem stays — it can throw
on quota errors.
No behavior change in the success path.
* docs(worktree): trim repeated call-site comments
Replace the 5-line explanation block (copy-pasted in all three
discovery loops) with a one-liner that points at the worktreeMapsEqual
JSDoc. The '16+ subscribers' framing is also dropped — the helper
itself is general-purpose and the precise number was fuzzy.
* fix(worktree): compare branch in worktreeMapsEqual to avoid stale sidebar label
The helper compared entries by path only. An external git checkout
between discoveries changes branch (and the derived label /
headState) while path stays the same, so the helper returned true
and the store update was skipped — leaving a stale branch label in
the sidebar until the next worktree create/remove or project switch,
since there is no periodic worktree-list refresh.
Compare branch in the inner loop alongside path. Tighten the generic
constraint to T extends { path: string; branch: string } so the
contract is documented at the type level.
worktreeStatus is intentionally NOT compared: status transitions go
through setStoredWorktreeStatus, which writes a fresh Map reference
that the persist subscriber picks up directly. Adding worktreeStatus
to the contract would also force the sidebar to detect status changes
that the persist path already handles, and would couple this helper
to a field whose semantics differ from the discovery path.
Fixes the staleness concern raised by openchamber-bot in PR #1992.
* test(worktree): cover worktreeMapsEqual edge cases
Documents the helper's equality contract and guards against
regressions in the path+branch comparison. Eight cases:
- two empty maps
- identical entries (path and branch match in order)
- same path, different branch — the F1 regression case
- different paths at the same index
- per-project array length mismatch
- project-key count mismatch
- positional reorder (helper is order-sensitive)
- non-first-entry branch difference (subset detection)
All 10 tests in the file pass (2 existing + 8 new).
* ci: retrigger checks
* test(worktree): add benchmark for worktreeMapsEqual and persist path
Documents the actual cost of the PR #1992 optimizations on representative
sizes (1-1000 worktrees per project, 1-50 projects), so future contributors
can reproduce the numbers and detect regressions in the equality helper or
the persist subscriber.
Run with: `bun run packages/ui/src/lib/worktrees/worktreeManager.bench.ts`
Measured on V8 (one example run):
- worktreeMapsEqual early-exit (50×20 with first project differing):
412 ns/op vs 33,034 ns/op full sweep — ~80x speedup when any project
actually changed.
- F1 path+branch overhead vs path-only (10×50): +2.3 µs (+15.8%) on a
full sweep; on the early-exit path the F1 cost is irrelevant.
- Stringify dedup in persistWorktreeMap subscriber: 67% saved (552 µs
per persist on 10×50). This is the main absolute win of the PR.
- Content-compare guard: 19-29 ns/op, free relative to the stringify it
gates.
Bench file is standalone (import.meta.main guard) — does not run as part
of `bun test`, does not import React, does not touch localStorage.
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* fix(number-input): stepper drift on rapid clicks (closes#2053)
The shared NumberInput stepper buttons (-/+) computed the next value from
`baseValue`, a useMemo of the controlled `value` prop. When the user
pressed - and + in rapid succession, both inline closures read the same
pre-update `baseValue` because the prop round-trip (click ->
onValueChange -> store/persistence update -> re-render) had not landed.
Net result: rapid alternation drifted or oscillated instead of returning
to the start value.
Route the stepper math through a new `committedValueRef` updated
synchronously inside `commitValue`, and re-sync the ref from `baseValue`
via a useEffect so external mutations (the reset button next to each
stepper, undo, multi-instance sync) keep the ref aligned. Keep
`baseValue` for the `disabled` predicate so the prop still gates the
buttons at the bounds.
For the same invariant, route `handleBlur`'s finite-parse branch
through `commitValue` so a typed value followed by a stepper click does
not compute from a stale ref. The empty-draft `onClear` early-return
relies on the baseValue useEffect to re-sync.
Cover the path with a new bun:test suite that drives the real onClick
closures through createRoot with a minimal document/window stub (no new
deps). Tests assert rapid --+ and +-- sequences net to the start value,
a sustained 6-click alternation does not drift, sequential clicks with a
re-render between them settle correctly, and a typed-then-stepper
sequence uses the typed base.
* test(number-input): restore DOM globals and guard empty recorded arrays
Follow-up to the stepper-drift fix on the same PR.
- installDomStub now captures the previous values of
document/window/navigator/IS_REACT_ACT_ENVIRONMENT before overwriting
and exposes a restore() function. withHandle calls stub.restore() in
finally after unmount(), so the test process no longer leaks a fake
DOM across tests.
- Replace the four 'recorded[length-1]!' non-null assertions with a
lastCommit(handle) helper that throws a clear error if the parent
never produced a commit. A regression that drops the first commit
fails loudly instead of silently coercing to undefined.
- Add a short comment on the useEffect re-sync documenting the
controlled-parent assumption (ref can briefly lead the prop if a
parent ever rejects or debounces onValueChange; no production caller
does today).
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* feat(command-palette): add projects to existing fuzzy search
Adds projects to the existing command palette search — same single-input
fuzzy search that already covers sessions, files, settings, and commands.
Projects are scored alongside everything else by scoreByFuzzyQuery, and
the best-matching result appears first regardless of type.
Selecting a project opens a new session draft with the project pre-selected.
Closes#976
* fix(command-palette): keep file search tied to debounced query
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* feat(settings): add editor font size setting for chat input and code editor
Adds an 'Editor font size' control in Settings > Appearance that sets an
absolute px font size for the chat input textarea and the in-app
CodeMirror editor. Mirrors the existing terminalFontSize lifecycle.
- New store field editorFontSize (default 13, clamp 9-32, step 1) in
useUIStore with narrow selectors at each consumer.
- Persistence wired through appearanceAutoSave, desktop + runtime API
types, and persistence.ts read/normalize.
- Settings UI row (NumberInput) with reset to 13, VisibleSetting union
entry, OpenChamberPage registration, and search index entry
appearance.editor-font-size.
- Applied as a post-zoom absolute override on the chat input textarea
and on the CodeMirror theme's content rule, leaving gutter/line-number
chrome at its existing hardcoded sizes (matches terminal scope).
- All 10 locales translated (en, es, fr, ja, ko, pl, pt-BR, uk, zh-CN,
zh-TW); no English placeholders in non-English dictionaries.
Refs #1325
* fix(codemirror): use unitless lineHeight so it scales with editor font size
The & rule in the CodeMirror theme set lineHeight to 1.5rem (~24px),
which does not scale when editorFontSize is increased (e.g., 28-32px).
This causes overlapping lines at larger font sizes.
Change to unitless 1.5, which scales proportionally with whatever fontSize
resolves to (dynamic prop or --text-code fallback). Matches browser best
practice for proportional leading.
Review comment: https://github.com/openchamber/openchamber/pull/2065
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
React error #31 (Objects are not valid as a React child) was thrown
intermittently when a task/subagent tool returned structured data
(e.g. { TODO: '...' }) in a field that the OpenCode SDK types as a
plain string. Pathological payloads would propagate into JSX children
without runtime validation, white-screening the chat until refresh.
This change adds a single `coerceToText` helper in toolRenderers.tsx
and applies it at every vulnerable JSX expression:
- ToolPart.tsx:1807,1975 {state.error} (typed string, can be object)
- ToolPart.tsx:1825 {q.question} (QuestionCard input cast)
- ToolPart.tsx:1830 {opt.label} (QuestionCard input cast)
- ToolPart.tsx:1848 task tool markdown output
- ToolPart.tsx:1898 ToolScrollableTextOutput entry
- toolRenderers.tsx {todo.content} x4 in renderTodoOutput
renderTodoOutput now also validates the parsed array at the boundary
(JSON.parse result is filtered to objects whose content and status are
runtime strings), so a single bad row no longer poisons the whole
tool output.
Tests: 12 new unit tests in
packages/ui/src/components/chat/message/parts/__tests__/issue-2011-react-error-31.test.ts
covering the {TODO}-key object path, circular references, and
non-string content/status on parsed todos.
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* fix(sync): commit first message page before expansion loop (#2084)
loadMessages committed the store only after the full expansion sequence
(50→100→150), so the hydrating skeleton stayed for 3 sequential HTTP
round-trips when a session tail had no user message boundary.
Move the store write (materialize + setState) to happen after the first
fetch. The expansion loop now commits each expanded page incrementally
instead of overwriting a page variable and committing once at the end.
The first commit is gated on hasUserMessage(page.session) || page.complete:
if the tail is assistant-only, deferring to the expansion loop keeps the
skeleton (loading state) instead of rendering an empty chat that looks
like a fresh session. Sessions with a user boundary in the first 50
messages get content after a single round-trip.
* fix(sync): address review nits for #2084
- deferred init uses page.session instead of [] so limit reflects the
real fetched count if the expansion loop is ever a no-op
- both stale branches in commitMessagesToStore return messages: [] for
consistency
- add isStale guard between expansion fetch and commit for defense-in-depth
* fix(sync): always commit prepend-mode pages to store (#2084)
The deferred init path (assistant-only tail) skipped commitMessagesToStore
entirely when options.before was set — prepend mode. The fetched older
messages were never written to the store, silently dropping them.
Gate the deferral on !options.before: prepend mode always commits because
messages are already rendered (no skeleton to protect) and skipping the
store write would lose the fetched page.
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
* fix(chat): preserve chronological message order during history pagination
The baseDisplayMessages dedup loop iterated from tail to head (newest
to oldest), keeping the newer occurrence of each message ID. During
history pagination (prepend mode), the server returns older messages
that may overlap with the current view at the boundary. The tail-first
iteration discarded the older (prepended) duplicate in favor of the
newer (existing) one, breaking chronological ordering.
Change the loop to iterate head to tail (oldest to newest) so the
first occurrence of each time-sortable message ID is preserved. Remove
the now-unnecessary .reverse() call.
Fixes#2088
* test(chat): add dedup logic coverage for baseDisplayMessages
Covers message ID deduplication in baseDisplayMessages useMemo:
- First-occurrence preservation during dedup
- Input order maintenance
- Empty input, single-element, all-same-ID edge cases
- History pagination prepend scenario with overlapping IDs
---------
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
Fixes GitHub PR/issue context endpoints returning 404 when working
from a fork because they resolved the repo from origin remote only.
- Pass sourceRepo: status?.repo ?? null to all prContext() calls in
PullRequestSection.tsx (5 call sites)
- Pass sourceRepo: args.pr.sourceRepo ?? null / args.issue.sourceRepo
?? null to NewWorktreeDialog.tsx (3 call sites: prContext, issueGet,
issueComments)
- Add status?.repo to dependency arrays to prevent stale closures
The prStatus endpoint already resolves the correct repo through the
fork network; this change wires it through to the downstream API calls.
Closes#2090
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
Replace the destructive refreshRoot() with an incremental refresh that
re-fetches the root and every expanded directory while preserving
childrenByDir. This keeps the file tree expanded instead of collapsing
it to the root on every manual refresh.
Closes#2036
Co-authored-by: bashrusakh <bashrusakh@users.noreply.github.com>
* docs(agents): add step-by-step workflows with posting and label procedures
Add numbered step-by-step workflows to all four automation agents
(pr-review, reproduce-issue, summarize, triage), each with an explicit
comment-posting sub-procedure: draft once, post via gh, capture result,
verify by reading comments back only, and retry once on failure.
pr-review also gains a Labels section that applies confidence:* and
risk:* labels matching the review scores, removing stale labels first
to avoid stacking. merge-conflict:true is left to its dedicated action.
triage renames its label-selection steps to Category 1-5 to avoid
colliding with the new workflow step numbering.
* fix(agents): avoid duplicate comments after ambiguous posts
---------
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
Adds a surface=desktop URL param to embedded session chat links
Uses the surface override to classify embedded chat as desktop
Covers the new URL parameter in tests
Prevents narrow embedded session chat panels from being misdetected as mobile
Uses the ocPanel=session-chat query parameter to पहचान desktop-like layout
Keeps device detection aligned with other desktop shell runtimes
Android 15 enforces edge-to-edge and ignores the StatusBar overlay:false
inset the app relied on, while every --oc-safe-area-* CSS definition was
gated behind iOS-only conditions. Read the Capacitor-injected
--safe-area-inset-* vars (with env() fallback) on the Android native
shell so the header, top toasts, and connect screen clear the status
bar; both sources report 0 where the native inset still applies.
- --relay links now carry both routes: direct LAN plus relay fallback,
matching the UI's Anywhere pairing; devices prefer the direct route
- pairing sessions created by the CLI are marked with usesRelay, and the
server reconciles relay demand on a timer, so a headless instance
brings the relay up on its own after connect-url --relay
- warn with LAN_UNREACHABLE when the link's direct route points at
loopback and other devices cannot use it
- document the --relay flow and the --lan binding caveat in Connect a
Device and Remote Instances across all locales
The "Add to Context" command and the active-editor pin-selection suggestion both create selection attachments but used the basename only (e.g. assist.ts:47). OpenCode synthesizes its Read call from that filename, so the directory was lost and the model could read or edit the wrong file when names collide.
Use the workspace-relative path (asRelativePath(uri, false)) in both paths so the filename carries the directory and the two paths produce identical filenames, restoring attachment dedup.
Fixes#1914
- new Connect a Device page: one-time QR pairing, transport choices, device management
- new Private Relay page: E2EE guarantees, demand-driven lifecycle, relay vs tunnel
- rewrite mobile page around the native iOS/Android apps (TestFlight + APK)
- update remote-instances, security, tunnels, and remote-access troubleshooting to point at the new pairing flow
- translate everything across all 8 locales and update the sidebar
Tool JSON output now starts with a compact navigable summary view.
Expandable tool output includes quick open-file and diff actions for changed files.
Reasoning headers strip stray HTML comments, and navigation tools stay compact.
Changelog leads with the private relay and the native mobile apps (TestFlight
beta + Android APK links), followed by pairing v2 and the device management,
desktop multi-transport, and chat items; VS Code changelog gets the shared
chat-render entries.