Merge main after paired test retirement

This commit is contained in:
Brennan Benson
2026-11-10 17:33:21 -08:00
325 changed files with 5574 additions and 13646 deletions
@@ -45,6 +45,9 @@ export type ControlAttachment = {
clientKeepalive?: boolean
// A keepalive control found silent: one relay ping sent at this time (see probeSilentControls).
probeAt?: number
// Upgrade and activation times, for metrics (absent on attachments from before these fields).
openedAt?: number
activeAt?: number
}
export type Attachment = ControlAttachment
export type Conn = {
@@ -28,8 +28,16 @@ export abstract class HostRelayControl extends HostRelayHandshake {
// Where the host is going away anyway (export, erase, drain, a new control of the same host): a
// silent control is closed now. Its orphan time is the latest the ping alarm would have found it,
// so rebind and the orphan grace are never shorter than before.
// A control closed for silence: value = seconds silent, label = where it was found, reason =
// keepalive | legacy; double2 = seconds since it became active (-1 if unknown).
protected deadControlMetric(a: ControlAttachment, now: number, seen: number, found: 'alarm' | 'on_demand' | 'expired'): void {
const ageS = a.activeAt === undefined ? -1 : Math.round((now - a.activeAt) / 1000)
metric(this.env, 'silence_close', Math.round((now - seen) / 1000), found, [ageS], this.keepalive(a) ? 'keepalive' : 'legacy', a.place)
}
protected async closeSilentControls(now = Date.now()): Promise<void> {
for (const { ws, seen } of this.silentControls(now)) {
for (const { ws, a, seen } of this.silentControls(now)) {
this.deadControlMetric(a, now, seen, 'on_demand')
this.close(ws, RELAY_CLOSE_CODE.PEER_DROPPED, 'control silence timeout')
await this.onSocketGone(ws, RELAY_CLOSE_CODE.PEER_DROPPED, '', Math.min(now, seen + this.config.silenceTimeoutMs + this.config.pingIntervalMs))
}
@@ -157,6 +157,7 @@ export abstract class HostRelayHandshake extends HostRelayBase {
})
const leaseExpiresAt = now + LEASE_BASE_MS + Math.round((Math.random() * 2 - 1) * LEASE_JITTER_MS)
a.phase = 'active'
a.activeAt = now
a.generation = generation
a.lastPongAt = now
a.lastPingAt = now
@@ -191,7 +192,7 @@ export abstract class HostRelayHandshake extends HostRelayBase {
})
// After the ack, which strict shipped parsers must see unchanged; only hosts that asked get it.
if (a.clientKeepalive) { this.send(ws, { type: 'keepalive-offer', v: 1, intervalMs: this.config.pingIntervalMs }) }
metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], a.clientKeepalive ? 'keepalive' : 'legacy', a.place)
metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [a.openedAt === undefined ? -1 : now - a.openedAt], a.clientKeepalive ? 'keepalive' : 'legacy', a.place)
await this.reschedule()
}
}
+13 -2
View File
@@ -145,7 +145,8 @@ export class HostRelay extends HostRelayPhones {
claims,
origin,
caps: [...parseRelayHostCapabilities(request.headers.get('x-orca-host-capabilities') ?? '')],
deadline: Date.now() + RELAY_PROTOCOL_LIMITS.firstFrameDeadlineMs
deadline: Date.now() + RELAY_PROTOCOL_LIMITS.firstFrameDeadlineMs,
openedAt: Date.now()
})
await this.reschedule()
return new Response(null, { status: 101, webSocket: client })
@@ -180,15 +181,25 @@ export class HostRelay extends HostRelayPhones {
continue
}
if (now - seen > this.config.silenceTimeoutMs && (!this.keepalive(a) || now - a.probeAt! >= KEEPALIVE_PROBE_MS - 50)) {
this.deadControlMetric(a, now, seen, 'alarm')
this.close(ws, RELAY_CLOSE_CODE.PEER_DROPPED, 'control silence timeout')
await this.onSocketGone(ws, RELAY_CLOSE_CODE.PEER_DROPPED, '')
continue
}
// Same order as the cells' heartbeat: expired auth past its grace, then the 6 h lease.
if (now > a.claims.exp + CONTROL_CONTINUITY_LIMITS.expiredAuthExistingSpliceGraceMs) {
// A host already silent past the limit is gone (asleep, offline): it closes as one, so
// drop counts stay comparable with the cells, whose pings would have closed it earlier.
// Its probe is cut short: the expired authorization ends the socket either way.
if (now - seen > this.config.silenceTimeoutMs) {
this.deadControlMetric(a, now, seen, 'expired')
this.close(ws, RELAY_CLOSE_CODE.PEER_DROPPED, 'control silence timeout')
await this.onSocketGone(ws, RELAY_CLOSE_CODE.PEER_DROPPED, '', Math.min(now, seen + this.config.silenceTimeoutMs + this.config.pingIntervalMs))
continue
}
const sinceRefreshS = a.lastRefreshAt === undefined ? -1 : Math.round((now - a.lastRefreshAt) / 1000)
const seenAgoS = Math.round((now - seen) / 1000)
metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [seenAgoS], this.keepalive(a) ? 'keepalive' : 'legacy', a.place)
metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [seenAgoS, a.activeAt === undefined ? -1 : Math.round((now - a.activeAt) / 1000)], this.keepalive(a) ? 'keepalive' : 'legacy', a.place)
this.close(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, 'relay authorization expired')
await this.onSocketGone(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, '')
continue
+6 -2
View File
@@ -2,7 +2,8 @@
import type { Env } from './env'
export type MetricEvent =
// label 'new' | 'rebind'; reason 'keepalive' | 'legacy' (took the keepalive offer or not).
// label 'new' | 'rebind'; reason 'keepalive' | 'legacy' (took the keepalive offer or not);
// double2 = ms from the upgrade to activation (the desktop gives up a connect after 15 s).
| 'control_active'
| 'control_close'
| 'phone_open'
@@ -27,8 +28,11 @@ export type MetricEvent =
| 'control_upgrade'
// Control closed 4401 for expired authorization: value = seconds since its last extending
// refresh, label 'refreshed'; -1 and label 'never' when this socket never extended its token.
// double2 = seconds since the host's last inbound frame or keepalive; reason 'keepalive' | 'legacy'.
// double2 = seconds since the host's last inbound frame or keepalive, double3 = seconds since the
// control became active (-1 if unknown); reason 'keepalive' | 'legacy'.
| 'auth_expired_close'
// Control closed for silence (deadControlMetric, host-relay-control.ts).
| 'silence_close'
// Pre-auth socket refused by the per-source limiter: label 'phone' | 'data' | 'health'. Unpushed-host phones: 'not_on_edge'.
| 'preauth_limited'
| 'not_on_edge'
@@ -47,14 +47,14 @@ export function newHost(): Host {
}
}
export async function mint(key: KeyLike, relayHostId: string, issuer = ISSUER): Promise<string> {
export async function mint(key: KeyLike, relayHostId: string, issuer = ISSUER, expiresIn = '5m'): Promise<string> {
return new SignJWT({ purpose: 'host-control', prof: `prof-${USER}`, relayHostId })
.setProtectedHeader({ alg: 'ES256', kid: REMOTE ? 'spike' : 'mvp' })
.setSubject(USER)
.setIssuer(issuer)
.setAudience('orca-relay')
.setIssuedAt()
.setExpirationTime('5m')
.setExpirationTime(expiresIn)
.sign(key)
}
@@ -128,6 +128,32 @@ export async function keepaliveProbeCheck(key: KeyLike): Promise<void> {
}
}
// K4: a keepalive host gone silent when its authorization expires closes as a dropped host (4408),
// not 4401, so edge drop counts stay comparable with the cells (their pings would have closed it).
export async function keepaliveExpiredSilentCheck(key: KeyLike): Promise<void> {
const host = newHost()
await assign(host.relayHostId, 'edge', EPOCH, [])
const started = Date.now()
// Alive for 50 s, then silent: the silence probe (sent ~9 s later) is still pending when the
// 3 s token passes its 60 s grace at ~63 s, so the expiry check is what closes it.
const c = control(host, await mint(key, host.relayHostId, undefined, '3s'), EPOCH, {
caps: `${SHIPPED_CAPS},client-keepalive-v1`,
drop: () => Date.now() - started > 50_000
})
await c.client.connect()
try {
const closed = await waitFor(() => c.events.closes.length > 0, 3_000 + 60_000 + 15_000)
const after = Date.now() - started
record(
'K4 silent keepalive host at token expiry: closed 4408 (not 4401)',
closed && c.events.closes.includes(4408) && !c.events.closes.includes(4401) && after >= 59_000,
`closedAfter=${after}ms pings=${c.events.pings} closes=${c.events.closes}`
)
} finally {
c.client.closeNow()
}
}
// F5: POST /__admin/drain sends the host's controls back to the director (drain frame, 4503).
export async function drainCheck(key: KeyLike): Promise<void> {
const host = newHost()
+2 -2
View File
@@ -41,7 +41,7 @@ import {
waitFor,
type Host
} from './harness-mvp-object'
import { drainCheck, heartbeatCheck, keepaliveCheck, keepaliveProbeCheck, objectHealthCheck } from './mvp-object-hardening'
import { drainCheck, heartbeatCheck, keepaliveCheck, keepaliveExpiredSilentCheck, keepaliveProbeCheck, objectHealthCheck } from './mvp-object-hardening'
import { replayCheck, rotationCheck } from './mvp-object-replay'
async function mainRemote(): Promise<void> {
@@ -107,7 +107,7 @@ async function main(): Promise<void> {
await sleep(500)
}
await run(host, privateKey, () => jwksHits)
await Promise.all([heartbeatCheck(privateKey), keepaliveCheck(privateKey), keepaliveProbeCheck(privateKey), drainCheck(privateKey), replayCheck(), rotationCheck()])
await Promise.all([heartbeatCheck(privateKey), keepaliveCheck(privateKey), keepaliveProbeCheck(privateKey), keepaliveExpiredSilentCheck(privateKey), drainCheck(privateKey), replayCheck(), rotationCheck()])
await sweepCheck()
await preAuthCheck(stateDir)
await objectHealthCheck(stateDir)
@@ -116,6 +116,43 @@ describe('relay edge fence after a host leaves', () => {
})
})
describe('relay edge fence over a same-epoch conflict', () => {
it('fences once more one epoch above a conflict at its epoch, and never bumps over a stale answer', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
h.edge.answers = ['conflict', 'applied']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9)).toBe(true)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([9, 10])
expect(h.edge.calls.every((call) => call.body.cellId === 'us-c1')).toBe(true)
expect(logged(warn, 'orca_relay_edge_fence_above_conflict')).toEqual([
{ event: 'orca_relay_edge_fence_above_conflict', outcome: 'applied', assignmentEpoch: 10 }
])
expect(await h.pending()).toEqual([])
// Stale: the edge holds a newer epoch (the host may be back there); no bump, recorded for retry.
h.edge.calls = []
h.edge.answers = ['stale']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 11)).toBe(false)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([11])
})
it('a pending fence retried into a same-epoch conflict lands one epoch above the row', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
await h.placeRow('us-c1', 7)
h.edge.answers = ['down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 7)).toBe(false)
expect(await h.pending()).toHaveLength(1)
h.edge.calls = []
h.edge.answers = ['conflict', 'applied']
h.clock.now += 60_000
await h.retry()
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([7, 8])
expect(await h.pending()).toEqual([])
})
})
describe('relay edge pending fence retries', () => {
it('re-fences to the current row, not the recorded one, and clears the record once it lands', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+23 -2
View File
@@ -41,6 +41,27 @@ export async function recordPendingFence(
)
}
// One fence call. `conflict` means the edge holds this very epoch for another placement (a move onto
// the edge whose push landed though the director counted it as failed, then a placement elsewhere
// minted the same epoch). No later move can produce that (a later move has a higher epoch, which
// answers `stale`), so the fence goes once more one epoch above: it lands, and a later move onto
// the edge re-mints above it as for any edge epoch (moveToEdge).
async function assignFence(
admin: EdgeAdmin,
fence: Identity & { cellId: string; assignmentEpoch: number }
): Promise<{ outcome: string; assignmentEpoch: number }> {
const first = await admin.assign(fence)
if (first.outcome !== 'conflict' || first.assignmentEpoch !== fence.assignmentEpoch) {
return { outcome: first.outcome, assignmentEpoch: fence.assignmentEpoch }
}
const above = fence.assignmentEpoch + 1
const second = await admin.assign({ ...fence, assignmentEpoch: above })
console.warn(
JSON.stringify({ event: 'orca_relay_edge_fence_above_conflict', outcome: second.outcome, assignmentEpoch: above })
)
return { outcome: second.outcome, assignmentEpoch: above }
}
// The fence right after a host left (EdgeAssignments.fenceAway). Anything but applied/unchanged
// fails: unavailable, `conflict`, or `stale` (the edge holds a newer epoch, so it still claims the
// host); the failure is logged and recorded for retry. Returns whether the fence landed.
@@ -55,7 +76,7 @@ export async function fenceEdge(
let outcome = 'unavailable'
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
outcome = (await admin.assign(fence)).outcome
outcome = (await assignFence(admin, fence)).outcome
} catch (error) {
if (!(error instanceof EdgeAdminUnavailableError)) { throw error }
outcome = error.message
@@ -138,7 +159,7 @@ async function retryOne(
const assignmentEpoch = integer(row, 'assignment_epoch')
let outcome: string
try {
outcome = (await admin.assign({ ...identity, cellId, assignmentEpoch })).outcome
outcome = (await assignFence(admin, { ...identity, cellId, assignmentEpoch })).outcome
} catch (error) {
if (!(error instanceof EdgeAdminUnavailableError)) { throw error }
outcome = error.message
-1
View File
@@ -29,7 +29,6 @@
1 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-idle-arbitration.test.ts
3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts
1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts
1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts
1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts
1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts
1 test-no-polling-loop:src/main/claude/claude-stream-json-connection.test.ts
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -18,7 +18,7 @@
3 src/renderer/src/components/worktree-jump/worktree-jump-palette-status-inputs.ts
1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts
4 src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts
1 src/renderer/src/lib/pane-manager/client-hosted-browser-row-state.ts
1 src/renderer/src/runtime/browser/client-hosting/client-hosted-browser-row-state.ts
4 src/renderer/src/lib/workspace/persistence/session-write-subscriber.ts
1 src/renderer/src/lib/workspace/persistence/workspace-session-browser-tabs.ts
7 src/renderer/src/lib/workspace/persistence/workspace-session-host-hydration.ts
@@ -4744,7 +4744,6 @@
"src/renderer/src/components/browser-pane/history/use-browser-history-shortcut.test.tsx": 1990,
"src/renderer/src/components/browser-pane/host-guest/agent-input-focus-guard.test.ts": 228,
"src/renderer/src/components/browser-pane/host-guest/browser-automation-visibility.test.ts": 45,
"src/renderer/src/components/browser-pane/host-guest/browser-guest-eviction-veto.test.ts": 1724,
"src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839,
"src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515,
"src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197,
@@ -5366,7 +5365,6 @@
"src/renderer/src/components/right-sidebar/checks-panel/gitlab-review-client.test.ts": 321,
"src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171,
"src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh-recovery.test.tsx": 2909,
"src/renderer/src/lib/repository-refresh/coalesced-poll-runner.test.ts": 61,
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx": 2023,
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts": 1767,
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.test.ts": 2072,
@@ -5631,7 +5629,6 @@
"src/renderer/src/components/status-bar/use-resource-usage-derived-model.test.tsx": 742,
"src/renderer/src/components/tab-bar/CopyTabIdMenuItem.test.tsx": 428,
"src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx": 3224,
"src/renderer/src/components/tab-bar/TabBarItemRow.test.tsx": 2116,
"src/renderer/src/components/tab-bar/TabBarQuickCommandItem.test.tsx": 384,
"src/renderer/src/components/tab-bar/TabBarQuickCommandsMenu.virtualization.test.tsx": 1644,
"src/renderer/src/components/tab-bar/TabStripScrollIndicator.test.tsx": 356,
@@ -5656,8 +5653,6 @@
"src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts": 261,
"src/renderer/src/components/tab-bar/use-tab-bar-quick-command-search-input.test.tsx": 536,
"src/renderer/src/components/tab-group/RetainedPaneHost.test.tsx": 340,
"src/renderer/src/components/tab-group/TabGroupPanel.os-file-drop.test.tsx": 1711,
"src/renderer/src/components/tab-group/TabGroupPanel.pane-actions.test.tsx": 1419,
"src/renderer/src/components/tab-group/tab-drag-pointer-sensor.test.ts": 187,
"src/renderer/src/components/tab-group/tab-drag-preview-activation.test.ts": 1785,
"src/renderer/src/components/tab-group/tab-drag-retained-guest-passthrough.test.tsx": 2104,
@@ -5958,7 +5953,6 @@
"src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.test.ts": 1878,
"src/renderer/src/components/terminal-pane/mobile-driver/use-mobile-overlay-ticks-desktop-fit.test.tsx": 371,
"src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-visibility-resume.test.ts": 1951,
"src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-window-focus-recovery.test.ts": 1836,
"src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1806,
"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts": 752,
"src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-window-wake-recovery.test.ts": 494,
@@ -6118,13 +6112,10 @@
"src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 5510,
"src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts": 5268,
"src/renderer/src/hooks/useIpcEvents-agent-status-queue-ordering.test.ts": 3680,
"src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts": 7403,
"src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts": 4119,
"src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts": 3310,
"src/renderer/src/hooks/useIpcEvents-browser-certificate-failure.test.ts": 2981,
"src/renderer/src/hooks/useIpcEvents-browser-navigation.test.ts": 1511,
"src/renderer/src/hooks/useIpcEvents-client-hosted-browser-rows.test.ts": 1894,
"src/renderer/src/hooks/useIpcEvents-close-routing-active-browser-tab.test.ts": 4572,
"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812,
"src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts": 2326,
"src/renderer/src/hooks/useIpcEvents-new-workspace-shortcut.test.ts": 72,
@@ -6255,7 +6246,6 @@
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-new-tab-host-route-readiness.test.ts": 489,
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts": 3592,
"src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx": 2347,
"src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.test.ts": 2266,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx": 2754,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-defaults.test.ts": 1594,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx": 3435,
@@ -6360,7 +6350,7 @@
"src/renderer/src/lib/review-owner.test.ts": 238,
"src/renderer/src/lib/runtime-host-copy.test.ts": 317,
"src/renderer/src/components/sidebar/sidebar-feed/sidebar-pending-layer.test.ts": 338,
"src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.test.ts": 1728,
"src/renderer/src/components/sidebar/worktree-list/parity/sidebar-workspace-activity.test.ts": 1728,
"src/renderer/src/lib/simulator/launch/simulator-launch-coordination.test.ts": 43,
"src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts": 515,
"src/renderer/src/lib/simulator/tabs/simulator-pane-shutdown-scheduler.test.ts": 1679,
@@ -6380,9 +6370,8 @@
"src/renderer/src/lib/text-input/paste/text-control-paste-ownership.test.ts": 217,
"src/renderer/src/lib/text-input/paste/text-control-paste.test.ts": 222,
"src/renderer/src/lib/text-generation-error-copy.test.ts": 466,
"src/renderer/src/lib/typing-latency/echo-instrumentation.test.ts": 145,
"src/renderer/src/lib/typing-latency/renderer-long-tasks.test.ts": 75,
"src/renderer/src/lib/typing-latency/sample-window.test.ts": 77,
"src/renderer/src/diagnostics/typing-latency/echo-instrumentation.test.ts": 145,
"src/renderer/src/diagnostics/typing-latency/renderer-long-tasks.test.ts": 75,
"src/renderer/src/attention/unread/unread-badge-count-selector.test.ts": 1930,
"src/renderer/src/lib/agent-session/tab-identity/use-tab-agent-observed-signal-dispatch.test.tsx": 1971,
"src/renderer/src/lib/agent-session/tab-identity/use-tab-agent.test.ts": 1961,
@@ -6404,7 +6393,6 @@
"src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043,
"src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768,
"src/renderer/src/lib/workspace/activation/worktree-agent-activation-seam.test.ts": 3440,
"src/renderer/src/lib/workspace/creation/worktree-creation-backend-startup-focus.test.ts": 2267,
"src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258,
"src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-lifecycle.test.ts": 2633,
"src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-prompts.test.tsx": 4554,
@@ -6434,13 +6422,10 @@
"src/renderer/src/runtime/workspace-layout/frames/layout-changes-during-stream-outage.test.ts": 1948,
"src/renderer/src/runtime/workspace-layout/commands/layout-owner-command.test.ts": 549,
"src/renderer/src/runtime/native-chat/naming/legacy-chat-rename-migration.test.tsx": 3834,
"src/renderer/src/runtime/local-structured-session-tabs-sync/local-structured-session-tabs-sync.test.ts": 2643,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/mirrored-agent-status-clock-skew.test.ts": 1839,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts": 1905,
"src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-environment-removal.test.ts": 1897,
"src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-reload.test.ts": 1943,
"src/renderer/src/runtime/workspace-layout/frames/pane-titles-drawn-from-frames.test.ts": 1988,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/remote-agent-row-last-assistant-message.test.ts": 1776,
"src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts": 55,
"src/renderer/src/runtime/hosted-terminals/snapshots/remote-runtime-snapshot-outcome.test.ts": 233,
"src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-frame-drop-resync.test.ts": 266,
@@ -6490,12 +6475,10 @@
"src/renderer/src/runtime/browser/creation/web-runtime-browser-creation-placement.test.ts": 1927,
"src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217,
"src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-replay.test.ts": 1119,
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-open-files-batch-equivalence.test.ts": 1478,
"src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-restored-placeholder-identity.test.ts": 985,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-agent-completion-notifications.test.ts": 1953,
"src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854,
"src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-stream-end-resubscribe.test.tsx": 2282,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-agent-status.test.ts": 987,
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts": 925,
"src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-cross-runtime-worktree.test.ts": 964,
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts": 1902,
@@ -6538,7 +6521,6 @@
"src/renderer/src/store/github/requests/provider-request-coalescing.test.ts": 969,
"src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts": 97,
"src/renderer/src/store/github/repositories/wsl-stopped-distro-poll-refusal.test.ts": 696,
"src/renderer/src/store/workspaces/host-isolation/host-twin-worktree-purge.test.ts": 1945,
"src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435,
"src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377,
"src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216,
@@ -6578,7 +6560,6 @@
"src/renderer/src/store/slices/browser/cleanup/browser-cleanup-close.test.ts": 1911,
"src/renderer/src/store/slices/browser/cleanup/browser-mount-admission-removal.test.ts": 1982,
"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts": 1777,
"src/renderer/src/store/slices/browser/hosts/browser-remote-tab-creation.test.ts": 2119,
"src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts": 988,
"src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts": 792,
"src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts": 1886,
@@ -6593,7 +6574,6 @@
"src/renderer/src/store/slices/diff-comments/diffComments.test.ts": 1896,
"src/renderer/src/store/slices/editor/git/editor-branch-line-total.test.ts": 892,
"src/renderer/src/store/slices/editor/checks/editor-check-details-reading.test.ts": 945,
"src/renderer/src/store/slices/editor/checks/editor-check-details-reconstructed-owner.test.ts": 2056,
"src/renderer/src/store/slices/editor/checks/editor-check-details-tab-owner.test.ts": 1103,
"src/renderer/src/store/slices/editor/checks/editor-check-details-tabs.test.ts": 1814,
"src/renderer/src/store/slices/editor/closing/editor-close-background-file.test.ts": 893,
@@ -6614,7 +6594,6 @@
"src/renderer/src/store/slices/editor/hydration/editor-session-duplicate-restore.test.ts": 1931,
"src/renderer/src/store/slices/editor/focus/editor-set-active-file-guard.test.ts": 895,
"src/renderer/src/store/slices/editor/tabs/editor-tab-layout-owner.test.ts": 1883,
"src/renderer/src/store/slices/editor/tabs/editor-tab-placement.test.ts": 1837,
"src/renderer/src/store/slices/editor/tabs/editor-tab-shared-project-owner.test.ts": 954,
"src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-identity.test.ts": 1775,
"src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-joins.test.ts": 1766,
@@ -6695,15 +6674,10 @@
"src/renderer/src/store/slices/settings/settings-terminal-quick-commands.test.ts": 1734,
"src/renderer/src/store/slices/settings/settings.test.ts": 1938,
"src/renderer/src/store/slices/worktrees/create/sparse-presets.test.ts": 217,
"src/renderer/src/store/slices/ssh/ssh.test.ts": 1843,
"src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts": 1867,
"src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801,
"src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919,
"src/renderer/src/store/repos/store-session-cascades.test.ts": 1775,
"src/renderer/src/store/slices/editor/hydration/store-session-editor-hydration.test.ts": 1719,
"src/renderer/src/store/terminals/store-session-terminal-reconnect.test.ts": 2279,
"src/renderer/src/store/terminals/store-session-workspace-hydration.test.ts": 1733,
"src/renderer/src/store/terminals/store-sleep-agent-status-retention.test.ts": 7641,
"src/renderer/src/store/terminals/store-sleep-exact-runtime-stop.test.ts": 1842,
"src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932,
"src/renderer/src/store/terminals/store-sleep-runtime-convergence.test.ts": 1767,
@@ -6716,13 +6690,11 @@
"src/renderer/src/store/slices/tabs/tabs-model-reconciliation.test.ts": 1800,
"src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts": 2140,
"src/renderer/src/store/slices/tabs/tabs-pane-layout-operations.test.ts": 1652,
"src/renderer/src/store/slices/tabs/tabs-split-create.test.ts": 1733,
"src/renderer/src/store/slices/tabs/tabs-unread-and-focus.test.ts": 1801,
"src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts": 1866,
"src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703,
"src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts": 1734,
"src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts": 1627,
"src/renderer/src/store/terminals/terminal-pane-detach-agent-retention.test.ts": 2846,
"src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts": 1751,
"src/renderer/src/store/terminals/terminal-quick-command-hosts.test.ts": 1759,
"src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts": 50,
@@ -6771,7 +6743,6 @@
"src/renderer/src/store/slices/worktrees/metadata/worktrees-linked-review-push-target.test.ts": 1186,
"src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts": 1132,
"src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-purge-terminal-state.test.ts": 1133,
"src/renderer/src/store/slices/worktrees/create/worktrees-remote-runtime-create.test.ts": 1244,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-remote-runtime-removal.test.ts": 1227,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts": 1229,
+1 -1
View File
@@ -35,7 +35,7 @@
1 src/renderer/src/lib/workspace/ownership/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param
2 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty
2 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly
3 src/renderer/src/lib/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field
3 src/renderer/src/diagnostics/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field
2 src/renderer/src/attention/unread/unread-badge-count.ts # reads a passed-in copy
1 src/renderer/src/lib/workspace/paths/workspace-directory.ts # P5b-2 must clear: optional state field defaults to empty
2 src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.ts # P5b-2 must clear: optional state fields
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 168m">
<title>downloads: 168m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 169m">
<title>downloads: 169m</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,7 +15,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
<text x="37" y="14">downloads</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">168m</text>
<text x="93.5" y="14">168m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">169m</text>
<text x="93.5" y="14">169m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

+1 -1
View File
@@ -427,7 +427,7 @@ A selection applies to every agent of that provider launched on the host after i
## Artifacts
Publish HTML or Markdown through the signed-in Orca account. Viewing a public link does not require sign-in; create/list/update/delete do. **Publishing is off by default** — a human must enable **Settings → Artifacts → Allow publishing public artifact links** on the device. There is no CLI flag that grants the gate. `list`, `unshare`, and `delete` stay available so you can audit or revoke links after turning publishing off.
Publish HTML or Markdown through the signed-in Orca account. Viewing a public link does not require sign-in; create/list/update/delete do. Publishing follows **Settings → Artifacts → Allow publishing public artifact links** on the device: on by default for new profiles, while profiles created before this default keep their previous setting. Only a human can change it; there is no CLI flag that grants the gate. `list`, `unshare`, and `delete` stay available so you can audit or revoke links after turning publishing off.
```bash
orca artifacts share ./report.html --json
+1 -1
View File
@@ -51,4 +51,4 @@ For long documents, click the **Table of Contents** button (tree icon) in the ed
## Share as artifact
From the editor header, **Share as artifact** publishes the open Markdown file as a public view link through your signed-in Orca account. Requires **Settings → Artifacts → Allow publishing public artifact links** (off by default). Republish updates the same link when Orca still has the mapping; manage or delete links from the sidebar **Artifacts** page. Agents and scripts can use `orca artifacts share|update|list|delete` — see [CLI reference → Artifacts](/docs/cli/reference#artifacts).
From the editor header, **Share as artifact** publishes the open Markdown file as a public view link through your signed-in Orca account. Requires **Settings → Artifacts → Allow publishing public artifact links** (on by default for new profiles). Republish updates the same link when Orca still has the mapping; manage or delete links from the sidebar **Artifacts** page. Agents and scripts can use `orca artifacts share|update|list|delete` — see [CLI reference → Artifacts](/docs/cli/reference#artifacts).
+1 -1
View File
@@ -91,7 +91,7 @@ Settings are grouped into panes. Everything here is searchable with `Cmd-,` then
## Artifacts
- **Orca account** — sign in (same account family as Orca Relay) to publish and manage shared files.
- **Allow publishing public artifact links** — **off by default**. Device-wide gate: when on, you, agents, and the `orca` CLI on this machine can upload HTML/Markdown and mint public view links. Turning it off does not delete existing links.
- **Allow publishing public artifact links** — **on by default for new profiles**; profiles created before this default keep their previous setting. Device-wide gate: when on, you, agents, and the `orca` CLI on this machine can upload HTML/Markdown and mint public view links. Turning it off does not delete existing links.
- **Show Artifacts** / sidebar shortcut — open the Artifacts list to search, preview, copy, or delete account-owned links.
- **Ask Before Deleting Artifacts** — optional confirmation before breaking a public link.
- Share from an open local HTML page or Markdown editor with **Share as artifact**, or via `orca artifacts …`. See [CLI reference → Artifacts](/docs/cli/reference#artifacts).
+2 -9
View File
@@ -21,14 +21,7 @@ function oneLine(text: string | null | undefined): string {
return text?.replace(/\s+/g, ' ').trim() ?? ''
}
// A worktree agent row or a session tab's AgentStatusEntry, which leaves these optional.
type AgentPreviewSource = Pick<RuntimeWorktreeAgentRow, 'prompt'> & {
lastAssistantMessage?: string | null
toolName?: string | null
toolInput?: string | null
}
function lastMessage(agent: AgentPreviewSource): string {
function lastMessage(agent: RuntimeWorktreeAgentRow): string {
const message = agent.lastAssistantMessage
return message ? oneLine(withoutNativeChatVisualDirectiveLines(message)) : ''
}
@@ -38,7 +31,7 @@ function lastMessage(agent: AgentPreviewSource): string {
* (`group` null) shows no tool, since the tool call is long over.
*/
export function agentListPreview(
agent: AgentPreviewSource,
agent: RuntimeWorktreeAgentRow,
group: AgentStatusGroup | null,
title: string
): string {
@@ -15,6 +15,8 @@ export type ActionSheetAction = {
destructive?: boolean
disabled?: boolean
hint?: string
/** Short trailing state, e.g. "↑2" or "Up to date". */
status?: string
/** Marks the choice that is current, as a trailing check. */
checked?: boolean
loading?: boolean
@@ -77,6 +79,7 @@ export function ActionSheetContent({ title, message, children, actions, onClose
key={action.id ?? action.label}
title={action.label}
subtitle={action.hint}
value={action.status}
leading={
action.renderIcon?.() ?? (
<Icon
+2 -7
View File
@@ -84,8 +84,6 @@ export function SwipeRowActions({
})
// Web has no worklet plugin; mapper hooks need this explicit dependency list.
const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset])
// Hidden at rest, so the action can't show through a rounded group's antialiased corners.
const actionsStyle = useAnimatedStyle(() => ({ opacity: offset.value === 0 ? 0 : 1 }), [offset])
// A tap on an open row closes it rather than pressing the row.
const guardPress = (onPress: () => void) => () => {
// The click a drag release produces belongs to the drag, not to the row.
@@ -126,10 +124,8 @@ export function SwipeRowActions({
}
return (
<View>
<Animated.View pointerEvents="box-none" style={[styles.actions, actionsStyle]}>
{leading ? renderAction(leading, 'leading') : null}
{trailing ? renderAction(trailing, 'trailing') : null}
</Animated.View>
{leading ? renderAction(leading, 'leading') : null}
{trailing ? renderAction(trailing, 'trailing') : null}
{/* pan-y keeps the page scrolling vertically over the row on the web. */}
<GestureDetector gesture={pan} touchAction="pan-y">
<Animated.View style={rowStyle}>{children(guardPress)}</Animated.View>
@@ -148,7 +144,6 @@ const styles = themedStyleSheet(() => ({
justifyContent: 'center',
gap: 2
},
actions: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 },
leading: { left: 0 },
trailing: { right: 0 },
actionPressed: { opacity: feedback.pressedOpacity },
+15 -1
View File
@@ -196,7 +196,9 @@ export function PullDownMenu({ visible, anchorRef, groups, onClose }: PullDownMe
disabled={action.disabled || action.loading}
onPress={() => press(action)}
accessibilityRole="menuitem"
accessibilityLabel={action.label}
accessibilityLabel={
action.status ? `${action.label}, ${action.status}` : action.label
}
accessibilityHint={action.hint}
accessibilityState={
action.checked === undefined ? undefined : { checked: action.checked }
@@ -213,6 +215,11 @@ export function PullDownMenu({ visible, anchorRef, groups, onClose }: PullDownMe
</Text>
) : null}
</View>
{action.status ? (
<Text style={styles.status} numberOfLines={1}>
{action.status}
</Text>
) : null}
{action.checked ? (
<Check size={17} color={tint} strokeWidth={2.2} />
) : action.renderIcon ? (
@@ -280,5 +287,12 @@ const styles = themedStyleSheet(() => ({
hint: {
color: colors.textSecondary,
fontSize: typography.metaSize
},
status: {
marginLeft: 'auto',
flexShrink: 0,
color: colors.textSecondary,
fontSize: typography.metaSize,
fontVariant: ['tabular-nums']
}
}))
+2 -1
View File
@@ -2454,7 +2454,8 @@
"tabStrip": {
"checkingCapabilities": "Desktop-Funktionen werden geprüft – gleich erneut versuchen",
"newTab": "Neuen Tab erstellen",
"quickCommandsUpdateRequired": "Desktop-Update für Schnellbefehle erforderlich"
"quickCommandsUpdateRequired": "Desktop-Update für Schnellbefehle erforderlich",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Terminal leeren",
+19 -27
View File
@@ -2184,10 +2184,10 @@
"renameTerminal": "Rename Terminal",
"renameTerminalFailed": "Couldn't rename the terminal. {{reason}}",
"terminalName": "Terminal name",
"allowAutoClose": "Allow Auto-Close",
"agents": "Agents"
"allowAutoClose": "Allow Auto-Close"
},
"tabStrip": {
"tabStatus": "{{title}}, {{status}}",
"newTab": "New tab",
"quickCommandsUpdateRequired": "Desktop update required for quick commands",
"checkingCapabilities": "Checking desktop capabilities — try again in a moment"
@@ -2889,6 +2889,8 @@
},
"presentation": {
"loadingTabs": "Loading tabs",
"oneTab": "1 tab",
"tabCount": "{{tabCount}} tabs",
"tapToRetry": "{{status}} — tap to retry"
},
"documentReaders": {
@@ -2926,29 +2928,6 @@
"skip": "Skip",
"stop": "Stop",
"yes": "Yes"
},
"tabsSheet": {
"needsYou": "Needs you",
"working": "Working",
"everythingElse": "Everything else",
"open": "Open",
"closeTab": "Close {{title}}"
},
"tabRows": {
"browser": "Browser",
"markdown": "Markdown note",
"file": "File",
"chat": "Chat",
"terminal": "Terminal"
},
"tabBar": {
"oneTab": "1 tab",
"tabCount": "{{count}} tabs",
"anotherNeedsYou": "another tab needs you",
"actionsHint": "Shows actions for this tab",
"next": "Next tab",
"previous": "Previous tab",
"hint": "Shows all tabs"
}
},
"chat": {
@@ -3484,7 +3463,12 @@
"commitThenPullPush": "Commit, then pull and push",
"resolveConflicts": "Resolve conflicts before committing",
"stageFile": "Stage at least one file to commit",
"enterMessage": "Enter a commit message to commit"
"enterMessage": "Enter a commit message to commit",
"statusConflicts": "Conflicts",
"statusNothingStaged": "Nothing staged",
"statusNeedsMessage": "Needs message",
"statusNotPublished": "Not published",
"statusNoBranch": "No branch"
},
"createPrAction": {
"createReview": "Create {{titleLabel}}",
@@ -3561,7 +3545,15 @@
"nothingToPushTo": "Nothing to push to {{upstreamName}}",
"nothingToForcePushTo": "Nothing to force push to {{upstreamName}}",
"rebaseFromNamedBase": "Rebase from {{baseRef}}",
"rebaseWithLatestFrom": "Rebase current branch with latest commits from {{baseRef}}"
"rebaseWithLatestFrom": "Rebase current branch with latest commits from {{baseRef}}",
"statusUpToDate": "Up to date",
"statusSetsUpstream": "Sets upstream",
"statusNotPublished": "Not published",
"statusNoBranch": "No branch",
"statusMayFail": "May fail",
"statusPublished": "Published",
"statusStashFirst": "Stash first",
"statusReplaces": "Replaces ↓{{behind}}"
},
"actions": {
"createPr": "Create PR",
+2 -1
View File
@@ -2524,7 +2524,8 @@
"tabStrip": {
"checkingCapabilities": "Comprobando las funciones del escritorio. Inténtalo de nuevo en un momento.",
"newTab": "Nueva pestaña",
"quickCommandsUpdateRequired": "Actualiza el escritorio para usar los comandos rápidos."
"quickCommandsUpdateRequired": "Actualiza el escritorio para usar los comandos rápidos.",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Limpiar terminal",
+2 -1
View File
@@ -2524,7 +2524,8 @@
"tabStrip": {
"checkingCapabilities": "Vérification des fonctionnalités de l'ordinateur — réessayez dans un instant",
"newTab": "Nouvel onglet",
"quickCommandsUpdateRequired": "Mettez à jour Orca sur l'ordinateur pour utiliser les commandes rapides"
"quickCommandsUpdateRequired": "Mettez à jour Orca sur l'ordinateur pour utiliser les commandes rapides",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Effacer le terminal",
+2 -1
View File
@@ -2450,7 +2450,8 @@
"tabStrip": {
"checkingCapabilities": "デスクトップの対応機能を確認中です。少し待ってから再試行してください。",
"newTab": "新規タブ",
"quickCommandsUpdateRequired": "クイックコマンドの利用にはデスクトップの更新が必要です。"
"quickCommandsUpdateRequired": "クイックコマンドの利用にはデスクトップの更新が必要です。",
"tabStatus": "{{title}}、{{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "ターミナルをクリア",
+2 -1
View File
@@ -2450,7 +2450,8 @@
"tabStrip": {
"checkingCapabilities": "데스크톱에서 지원하는 기능을 확인 중입니다. 잠시 후 다시 시도하세요.",
"newTab": "새 탭",
"quickCommandsUpdateRequired": "빠른 명령을 사용하려면 데스크톱 업데이트가 필요합니다."
"quickCommandsUpdateRequired": "빠른 명령을 사용하려면 데스크톱 업데이트가 필요합니다.",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "터미널 지우기",
+2 -1
View File
@@ -2524,7 +2524,8 @@
"tabStrip": {
"checkingCapabilities": "Verificando os recursos do desktop — tente novamente em instantes",
"newTab": "Nova aba",
"quickCommandsUpdateRequired": "Atualize o desktop para usar comandos rápidos"
"quickCommandsUpdateRequired": "Atualize o desktop para usar comandos rápidos",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Limpar Terminal",
+2 -1
View File
@@ -2594,7 +2594,8 @@
"tabStrip": {
"checkingCapabilities": "Проверяем возможности Orca на компьютере — повторите попытку чуть позже",
"newTab": "Новая вкладка",
"quickCommandsUpdateRequired": "Для быстрых команд обновите Orca на компьютере"
"quickCommandsUpdateRequired": "Для быстрых команд обновите Orca на компьютере",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Очистить терминал",
+2 -1
View File
@@ -2454,7 +2454,8 @@
"tabStrip": {
"checkingCapabilities": "Masaüstü özellikleri kontrol ediliyor — birazdan tekrar deneyin",
"newTab": "Yeni sekme",
"quickCommandsUpdateRequired": "Hızlı komutlar için masaüstü uygulaması güncellenmeli"
"quickCommandsUpdateRequired": "Hızlı komutlar için masaüstü uygulaması güncellenmeli",
"tabStatus": "{{title}}, {{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "Terminali Temizle",
+2 -1
View File
@@ -2450,7 +2450,8 @@
"tabStrip": {
"checkingCapabilities": "正在檢查桌面版支援的功能,請稍後再試",
"newTab": "新分頁",
"quickCommandsUpdateRequired": "需更新桌面版才能使用快速命令"
"quickCommandsUpdateRequired": "需更新桌面版才能使用快速命令",
"tabStatus": "{{title}},{{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "清除終端機",
+2 -1
View File
@@ -2450,7 +2450,8 @@
"tabStrip": {
"checkingCapabilities": "正在检查桌面支持的功能,请稍后重试",
"newTab": "新标签页",
"quickCommandsUpdateRequired": "使用快捷命令需更新桌面应用"
"quickCommandsUpdateRequired": "使用快捷命令需更新桌面应用",
"tabStatus": "{{title}},{{status}}"
},
"terminalActionSheetActions": {
"clearTerminal": "清空终端",
+3 -3
View File
@@ -6,7 +6,7 @@ import { NavBar, NavBarRefreshLine } from '../components/nav-bar/NavBar'
import { useRefreshHint } from '../query/refresh-hint'
import { NavBarButton } from '../components/nav-bar/NavBarButton'
import { MobileSessionHeaderMoreMenu } from './MobileSessionHeaderMoreMenu'
import { MobileSessionTabBar } from './tabs/MobileSessionTabBar'
import { MobileSessionTabStrip } from './tabs/MobileSessionTabStrip'
import { MobileSessionTitleBlock } from './MobileSessionTitleBlock'
import type { SessionTitleCard } from './tabs/use-session-title-card'
import { styles } from './mobile-session-styles'
@@ -58,11 +58,11 @@ export function MobileSessionHeader({
// Why: a sideways phone is ~390pt tall, so the tabs share the top bar instead of taking a second row.
const hasTabs = visibleTabs.length > 0
const tabsInTopBar = (layout.isLandscapePhone || sideRail) && hasTabs
// Bar buttons otherwise leave the tab bar too narrow to read on a narrow header.
// Bar buttons otherwise leave less than two readable tabs on a narrow header.
const actionsCollapsed = tabsInTopBar && (headerWidth ?? layout.width) < 600
const sourceControlInBar = !isFloatingWorkspaceRoute && !actionsCollapsed
const tabStrip = hasTabs ? (
<MobileSessionTabBar
<MobileSessionTabStrip
controller={controller}
inTopBar={tabsInTopBar}
actionsCollapsed={actionsCollapsed}
+55 -29
View File
@@ -2,7 +2,7 @@ import { Platform } from 'react-native'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { getRepoIdFromWorktreeId } from '../../../src/shared/worktree/id'
import { useClipboardWriter } from '../platform/clipboard'
import { Copy, FileText, RefreshCw } from 'lucide-react-native'
import { Copy, FileText, Globe, RefreshCw, SquareTerminal } from 'lucide-react-native'
import { MobileSessionTerminalLayoutSheet } from '../terminal/session/MobileSessionTerminalLayoutSheet'
import { QuickCommandsSheet } from '../terminal/quick-commands/QuickCommandsSheet'
import { triggerSuccess, triggerError } from '../platform/haptics'
@@ -19,7 +19,6 @@ import { isTerminalPhoneDisplayMode } from '../terminal/session/terminal-phone-d
import type { MobileSessionController } from './use-mobile-session-controller'
import { useMobileAllowAutoCloseActions } from './tabs/mobile-worker-auto-close'
import { MobileAgentSessionTabActionSheet } from './tabs/MobileAgentSessionTabActionSheet'
import { MobileNewTabSheet } from './tabs/MobileNewTabSheet'
export function MobileSessionSheets({ controller }: { controller: MobileSessionController }) {
const t = useMobileTranslation()
@@ -91,8 +90,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC
bulkCloseActions,
bulkCloseConfirm,
closeWithBulkActions,
createTabAgentStatusRow,
createTabAgentOptions,
createTabAgentActions,
sendDiffNotesAgentActions
} = controller
const clipboard = useClipboardWriter()
@@ -117,33 +115,61 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC
agentPromptMaxLength={controller.quickCommandAgentPromptMaxLength}
onLaunch={launchQuickCommand}
/>
<MobileNewTabSheet
<ActionSheetModal
visible={showCreateTabDrawer}
workspaceName={worktreeName}
agentOptions={createTabAgentOptions}
agentStatusRow={createTabAgentStatusRow}
// Why: browser/markdown creation resolve a real worktree on the host
// (browser.tabCreate, files.createFile); the floating sentinel is
// terminal-only over RPC, so those options hide there.
canCreateBrowser={!isFloatingWorkspaceRoute}
canCreateMarkdownNote={!isFloatingWorkspaceRoute && onPairedHost}
title={t('session.sheets.newTab', 'New Tab')}
actions={[
...createTabAgentActions,
{
id: 'terminal',
label: t('session.sheets.terminal', 'Terminal'),
icon: SquareTerminal,
onPress: () => {
setShowCreateTabDrawer(false)
void handleCreateTerminal()
}
},
// Why: browser/markdown creation resolve a real worktree on the host
// (browser.tabCreate, files.createFile); the floating sentinel is
// terminal-only over RPC, so those options hide there.
...(isFloatingWorkspaceRoute
? []
: [
{
id: 'browser',
label: t('session.sheets.browser', 'Browser'),
icon: Globe,
closeBeforePress: true,
onPress: () => {
if (browserScreencastSupported !== true) {
showToast(
t(
'session.sheets.browserUpdateRequired',
'Desktop update required for mobile browser streaming'
),
1600
)
return
}
setShowCreateBrowserModal(true)
}
},
...(onPairedHost
? [
{
id: 'markdownNote',
label: t('session.sheets.markdownNote', 'Markdown Note'),
icon: FileText,
onPress: () => {
setShowCreateTabDrawer(false)
void handleCreateMarkdownNote()
}
}
]
: [])
])
]}
onClose={() => setShowCreateTabDrawer(false)}
onCreateAgent={(agent) => void handleCreateTerminal(agent)}
onCreateTerminal={() => void handleCreateTerminal()}
onCreateBrowser={() => {
if (browserScreencastSupported !== true) {
showToast(
t(
'session.sheets.browserUpdateRequired',
'Desktop update required for mobile browser streaming'
),
1600
)
return
}
setShowCreateBrowserModal(true)
}}
onCreateMarkdownNote={() => void handleCreateMarkdownNote()}
/>
<ActionSheetModal
visible={pendingDiffNotesDelivery !== null}
@@ -58,6 +58,108 @@ export const mobileSessionFrameStyles = themedStyleSheet(() => ({
color: colors.textSecondary,
fontSize: typography.metaSize
},
tabBar: {
flexDirection: 'row',
alignItems: 'center',
borderTopWidth: 1,
borderTopColor: colors.borderSubtle
},
// Cancels the top bar's vertical padding so tab borders run the bar's full height.
tabBarInTopBar: {
flex: 1,
minWidth: 0,
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch',
marginVertical: -spacing.xs,
marginLeft: spacing.md,
borderLeftWidth: 1,
borderLeftColor: colors.borderSubtle
},
tabScrollFrame: {
flex: 1,
minWidth: 0,
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch'
},
tabEdgeHint: {
position: 'absolute',
top: 0,
bottom: 0,
justifyContent: 'center',
paddingHorizontal: spacing.xs,
backgroundColor: colors.bgPanel
},
tabEdgeHintLeft: {
left: 0,
borderRightWidth: 1,
borderRightColor: colors.borderSubtle
},
tabEdgeHintRight: {
right: 0,
borderLeftWidth: 1,
borderLeftColor: colors.borderSubtle
},
// Opaque like the chrome behind it: see the chat page scroll (#36553).
tabScroll: {
flex: 1,
maxHeight: 44,
backgroundColor: colors.bgPanel
},
tabScrollInTopBar: {
alignSelf: 'stretch',
maxHeight: 44
},
tabContent: {
paddingLeft: spacing.md,
paddingRight: spacing.sm
},
tabContentInTopBar: {
paddingLeft: 0
},
tab: {
minWidth: 44,
maxWidth: 128,
minHeight: 44,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: spacing.sm,
paddingVertical: spacing.sm,
borderBottomWidth: 2,
borderBottomColor: 'transparent',
borderRightWidth: 1,
borderRightColor: colors.borderSubtle
},
tabFirst: {
borderLeftWidth: 1,
borderLeftColor: colors.borderSubtle
},
tabActive: {
borderBottomColor: colors.textSecondary,
backgroundColor: colors.bgRaised
},
tabPressed: {
backgroundColor: colors.translucentFill
},
tabLabelRow: {
maxWidth: '100%',
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs
},
// Prevent web SVG shrink before the title ellipsizes.
tabIcon: {
flexShrink: 0
},
tabText: {
flexShrink: 1,
color: colors.textSecondary,
fontSize: 13
},
tabTextActive: {
color: colors.textPrimary
},
newTerminalButtonPressed: {
backgroundColor: colors.bgRaised
},
@@ -1,183 +0,0 @@
import { useRef } from 'react'
import { Pressable, Text, View } from 'react-native'
import { FileText, Globe, SquareTerminal } from 'lucide-react-native'
import type { TuiAgent } from '../../../../src/shared/agent-launch/catalog/tui-agent'
import { ActionSheetContent, type ActionSheetAction } from '../../components/ActionSheetModal'
import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer'
import {
LIST_LEADING_INSET,
ListGroup,
ListRow,
SectionHeader
} from '../../components/list/ListGroup'
import { MobileAgentIcon } from '../../components/MobileAgentIcon'
import { SheetHeader } from '../../components/nav-bar/SheetHeader'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import { colors, radii, spacing } from '../../theme/mobile-theme'
import { themedStyleSheet } from '../../theme/themed-styles'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import type { MobileNewTabAgentOption } from '../agent-launch/mobile-new-tab-agent-options'
const AGENT_GRID_COLUMNS = 3
type Props = {
visible: boolean
workspaceName: string
agentOptions: readonly MobileNewTabAgentOption[]
/** Loading, none, other-server or error; shown instead of the agent grid. */
agentStatusRow: ActionSheetAction | null
canCreateBrowser: boolean
canCreateMarkdownNote: boolean
onClose: () => void
onCreateAgent: (agent: TuiAgent) => void
onCreateTerminal: () => void
/** Runs after the sheet has gone, so it may open another modal. */
onCreateBrowser: () => void
onCreateMarkdownNote: () => void
}
export function MobileNewTabSheet({
visible,
workspaceName,
agentOptions,
agentStatusRow,
canCreateBrowser,
canCreateMarkdownNote,
onClose,
onCreateAgent,
onCreateTerminal,
onCreateBrowser,
onCreateMarkdownNote
}: Props) {
useMobileColorScheme()
const t = useMobileTranslation()
// Wait for the iOS sheet window to unmount before presenting another native modal.
const afterCloseRef = useRef<(() => void) | null>(null)
const closeThen = (action: () => void) => {
afterCloseRef.current = action
onClose()
}
const closeAndRun = (action: () => void) => {
onClose()
action()
}
const showAgentGrid = agentStatusRow === null && agentOptions.length > 0
// Short last rows keep empty slots so every tile stays a third of the row wide.
const agentRows: { options: MobileNewTabAgentOption[]; emptySlots: string[] }[] = []
for (let start = 0; start < agentOptions.length; start += AGENT_GRID_COLUMNS) {
const options = agentOptions.slice(start, start + AGENT_GRID_COLUMNS)
const emptySlots: string[] = []
for (let column = options.length; column < AGENT_GRID_COLUMNS; column += 1) {
emptySlots.push(`empty:${column}`)
}
agentRows.push({ options, emptySlots })
}
const iconColor = colors.textSecondary
return (
<BottomDrawer
visible={visible}
onClose={onClose}
onAfterClose={() => {
const run = afterCloseRef.current
afterCloseRef.current = null
run?.()
}}
dragContentToDismiss
>
<SheetHeader
title={t('session.sheets.newTab', 'New Tab')}
{...(workspaceName ? { subtitle: workspaceName } : {})}
onClose={onClose}
/>
{showAgentGrid || agentStatusRow ? (
<SectionHeader title={t('session.sheets.agents', 'Agents')} first />
) : null}
{agentStatusRow ? <ActionSheetContent actions={[agentStatusRow]} /> : null}
{showAgentGrid ? (
<View style={styles.grid}>
{agentRows.map((row) => (
<View key={row.options.map((option) => option.agent).join(':')} style={styles.gridRow}>
{row.options.map((option) => (
<Pressable
key={option.agent}
onPress={() => closeAndRun(() => onCreateAgent(option.agent))}
accessibilityRole="button"
accessibilityLabel={option.label}
style={styles.tile}
>
{({ pressed }) => (
<>
{pressed ? <View style={styles.tilePressed} /> : null}
<MobileAgentIcon agentId={option.agent} size={22} />
<Text style={styles.tileLabel} numberOfLines={1}>
{option.label}
</Text>
</>
)}
</Pressable>
))}
{row.emptySlots.map((slot) => (
<View key={slot} style={styles.tileSpacer} />
))}
</View>
))}
</View>
) : null}
<ListGroup separatorInset={LIST_LEADING_INSET} style={styles.actions}>
<ListRow
key="terminal"
title={t('session.sheets.terminal', 'Terminal')}
leading={<SquareTerminal size={16} color={iconColor} />}
onPress={() => closeAndRun(onCreateTerminal)}
/>
{canCreateBrowser ? (
<ListRow
key="browser"
title={t('session.sheets.browser', 'Browser')}
leading={<Globe size={16} color={iconColor} />}
navigates
onPress={() => closeThen(onCreateBrowser)}
/>
) : null}
{canCreateMarkdownNote ? (
<ListRow
key="markdownNote"
title={t('session.sheets.markdownNote', 'Markdown Note')}
leading={<FileText size={16} color={iconColor} />}
onPress={() => closeAndRun(onCreateMarkdownNote)}
/>
) : null}
</ListGroup>
</BottomDrawer>
)
}
const styles = themedStyleSheet(() => ({
grid: { gap: spacing.sm },
gridRow: { flexDirection: 'row', gap: spacing.sm },
tile: {
flex: 1,
minWidth: 0,
height: 78,
borderRadius: radii.surface,
backgroundColor: colors.sheetGroup,
overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center',
gap: spacing.sm,
paddingHorizontal: spacing.sm
},
// Same wash as a pressed ListRow, laid over the tile so its own fill stays underneath.
tilePressed: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: colors.translucentFill
},
tileLabel: { fontSize: 13.5, fontWeight: '600', color: colors.textPrimary, maxWidth: '100%' },
// Padded like a tile: flex shares space after padding, so a bare spacer would widen its row's tiles.
tileSpacer: { flex: 1, paddingHorizontal: spacing.sm },
actions: { marginTop: spacing.lg }
}))
@@ -1,361 +0,0 @@
import { useMemo, useRef, useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import { Plus } from 'lucide-react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withSequence,
withTiming
} from 'react-native-reanimated'
import { triggerMediumImpact, triggerSelection } from '../../platform/haptics'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import { AgentStateDot } from '../../components/AgentStateDot'
import { ArrivalFade } from '../../components/ArrivalFade'
import { useDrawerReducedMotion } from '../../components/bottom-drawer/bottom-drawer-constants'
import { SHEET_CURVE } from '../../components/sheet-motion-values'
import { useReducedMotionEnabled } from '../../platform/use-reduced-motion'
import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps'
import { useNow } from '../../hooks/use-now'
import { agentStateLabel, type AgentDotState } from '../../worktree/agent-row-display'
import { colors, feedback, radii, spacing } from '../../theme/mobile-theme'
import { themedStyleSheet } from '../../theme/themed-styles'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import { buildMobileSessionTabRow, type MobileSessionTabRow } from './mobile-session-tab-rows'
import { MobileSessionTabMark } from './MobileSessionTabMark'
import { MobileSessionTabsSheet } from './MobileSessionTabsSheet'
import type { MobileSessionController } from '../use-mobile-session-controller'
const SWIPE_SETTLE_MS = 250
// A tab arriving from the side starts this far out, as a share of the tab cell's width.
const SWIPE_ENTRY_SHARE = 0.4
const FLICK_VELOCITY = 600
// With no tab on that side, the tab gives only this share of the drag.
const EDGE_RESISTANCE = 0.25
const DRAG_CLICK_WINDOW_MS = 400
// A tab drawn before it had any agent state (from the phone's store) fades its dot in when one lands.
function TabBarDot({ tabId, state }: { tabId: string; state: AgentDotState | undefined }) {
const [startedEmpty] = useState({ tabId, empty: state === undefined })
if (startedEmpty.tabId === tabId && startedEmpty.empty) {
return <ArrivingTabBarDot state={state} />
}
return state && state !== 'idle' ? <AgentStateDot state={state} /> : null
}
// Mounted with the bare tab, so the motion preference is read before the dot arrives.
function ArrivingTabBarDot({ state }: { state: AgentDotState | undefined }) {
const reducedMotion = useReducedMotionEnabled()
if (!state || state === 'idle') {
return null
}
return (
<ArrivalFade animate={reducedMotion === false}>
<AgentStateDot state={state} />
</ArrivalFade>
)
}
/** The tab you're in as one cell: tap for its actions, swipe for the next one; the count shows every tab, + adds one. */
export function MobileSessionTabBar({
controller,
inTopBar,
actionsCollapsed = false
}: {
controller: MobileSessionController
inTopBar: boolean
actionsCollapsed?: boolean
}) {
useMobileColorScheme()
const t = useMobileTranslation()
const {
activeSessionTabId,
connState,
createTabBusy,
handleOpenNewTab,
switchSessionTab,
openSessionTabActionSheetAfterKeyboardDismiss,
visibleTabs,
terminals
} = controller
// Why: the first tap must reach the bar with the keyboard open instead of only dismissing it (#5106).
const keepsKeyboard = useKeyboardPersistingTaps('handled')
const now = useNow(60_000)
const rows = useMemo(
() => visibleTabs.map((tab) => buildMobileSessionTabRow(tab, terminals, now)),
[visibleTabs, terminals, now]
)
const activeIndex = rows.findIndex((row) => row.tab.id === activeSessionTabId)
const active: MobileSessionTabRow | undefined = rows[activeIndex]
const previous = activeIndex > 0 ? rows[activeIndex - 1] : undefined
const next = activeIndex !== -1 ? rows[activeIndex + 1] : undefined
const othersNeedYou = rows.some(
(row) => row.tab.id !== activeSessionTabId && row.group === 'needs-you'
)
const [sheetOpen, setSheetOpen] = useState(false)
const reducedMotion = useDrawerReducedMotion()
const offset = useSharedValue(0)
const width = useSharedValue(0)
// On the web, releasing a mouse drag also clicks the tab.
const dragEndedAtRef = useRef(0)
const settle = (to: number) =>
withTiming(
to,
reducedMotion
? { duration: 0, reduceMotion: ReduceMotion.Never }
: { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) }
)
const step = (target: MobileSessionTabRow | undefined, direction: 1 | -1) => {
if (!target) {
offset.value = settle(0)
return
}
triggerSelection()
switchSessionTab(target.tab)
offset.value = withSequence(
withTiming(-direction * width.value * SWIPE_ENTRY_SHARE, { duration: 0 }),
settle(0)
)
}
// Callbacks run on JS: the session page is a web document, and stepping switches React state.
const pan = Gesture.Pan()
.runOnJS(true)
.enabled(rows.length > 1)
.activeOffsetX([-12, 12])
.failOffsetY([-10, 10])
.onUpdate((event) => {
const target = event.translationX > 0 ? previous : next
offset.value = target ? event.translationX : event.translationX * EDGE_RESISTANCE
})
.onEnd((event) => {
// oxlint-disable-next-line react/purity -- runs when the drag ends, never during render.
dragEndedAtRef.current = Date.now()
const direction = event.translationX > 0 ? 1 : -1
const flicked =
Math.abs(event.velocityX) > FLICK_VELOCITY && Math.sign(event.velocityX) === direction
if (Math.abs(event.translationX) > width.value / 2 || flicked) {
step(direction === 1 ? previous : next, direction)
return
}
offset.value = settle(0)
})
// Web has no worklet plugin; mapper hooks need this explicit dependency list.
const contentStyle = useAnimatedStyle(
() => ({
transform: [{ translateX: offset.value }],
opacity: 1 - Math.min(Math.abs(offset.value) / Math.max(width.value, 1), 1) * 0.6
}),
[offset, width]
)
const status = active?.dotState && active.dotState !== 'idle' ? active.dotState : undefined
const countLabel =
rows.length === 1
? t('session.tabBar.oneTab', '1 tab')
: t('session.tabBar.tabCount', '{{count}} tabs', { count: rows.length })
const tabLabel = [active?.title, status ? agentStateLabel(status) : null]
.filter(Boolean)
.join(', ')
const countAccessibilityLabel = [
countLabel,
othersNeedYou ? t('session.tabBar.anotherNeedsYou', 'another tab needs you') : null
]
.filter(Boolean)
.join(', ')
const createDisabled = createTabBusy || connState !== 'connected'
const openTabActions = () => {
// The click a drag release produces on the web belongs to the drag.
if (!active || Date.now() - dragEndedAtRef.current < DRAG_CLICK_WINDOW_MS) {
return
}
openSessionTabActionSheetAfterKeyboardDismiss(active.tab)
}
return (
<View ref={keepsKeyboard} style={inTopBar ? styles.barInTopBar : styles.bar}>
{/* pan-y keeps vertical touches with the page on the web. */}
<GestureDetector gesture={pan} touchAction="pan-y">
<View
style={styles.tabCell}
onLayout={(event) => {
width.value = event.nativeEvent.layout.width
}}
>
<Pressable
style={({ pressed }) => [styles.tabPress, pressed && styles.cellPressed]}
onPress={openTabActions}
onLongPress={() => {
triggerMediumImpact()
openTabActions()
}}
delayLongPress={400}
disabled={!active}
accessibilityRole="button"
accessibilityLabel={tabLabel || countLabel}
accessibilityHint={t('session.tabBar.actionsHint', 'Shows actions for this tab')}
accessibilityActions={[
...(next ? [{ name: 'nextTab', label: t('session.tabBar.next', 'Next tab') }] : []),
...(previous
? [{ name: 'previousTab', label: t('session.tabBar.previous', 'Previous tab') }]
: [])
]}
onAccessibilityAction={(event) => {
const name = event.nativeEvent.actionName
if (name === 'nextTab') {
step(next, -1)
} else if (name === 'previousTab') {
step(previous, 1)
}
}}
>
{/* Only the contents slide, so the cell stays flush with the screen edge. */}
<Animated.View style={[styles.tabContent, contentStyle]}>
{active ? (
<>
<TabBarDot tabId={active.tab.id} state={active.dotState} />
<View style={styles.mark}>
<MobileSessionTabMark row={active} size={14} />
</View>
</>
) : null}
<Text style={styles.title} numberOfLines={1}>
{active?.title ?? countLabel}
</Text>
</Animated.View>
</Pressable>
</View>
</GestureDetector>
<Pressable
style={({ pressed }) => [
styles.sideCell,
actionsCollapsed && !inTopBar && styles.lastCell,
pressed && styles.cellPressed
]}
onPress={() => setSheetOpen(true)}
accessibilityRole="button"
accessibilityLabel={countAccessibilityLabel}
accessibilityHint={t('session.tabBar.hint', 'Shows all tabs')}
>
<View style={styles.countBox}>
<Text style={styles.countText}>{rows.length}</Text>
</View>
{othersNeedYou ? <View style={styles.alert} /> : null}
</Pressable>
{/* A collapsed bar's + lives in the header's ⋯ menu. */}
{!actionsCollapsed ? (
<Pressable
style={({ pressed }) => [
styles.sideCell,
!inTopBar && styles.lastCell,
pressed && styles.cellPressed,
createDisabled && styles.cellDisabled
]}
disabled={createDisabled}
onPress={handleOpenNewTab}
accessibilityRole="button"
accessibilityLabel={t('session.tabStrip.newTab', 'New tab')}
accessibilityState={{ disabled: createDisabled }}
>
<Plus size={18} color={colors.textPrimary} strokeWidth={2.2} />
</Pressable>
) : null}
<MobileSessionTabsSheet
controller={controller}
rows={rows}
visible={sheetOpen}
onClose={() => setSheetOpen(false)}
/>
</View>
)
}
const styles = themedStyleSheet(() => ({
bar: {
height: 44,
flexDirection: 'row',
alignItems: 'stretch',
borderTopWidth: 1,
borderTopColor: colors.borderSubtle
},
// Cancels the top bar's vertical padding so the cells run the bar's full height.
barInTopBar: {
flex: 1,
minWidth: 0,
flexDirection: 'row',
alignItems: 'stretch',
alignSelf: 'stretch',
marginVertical: -spacing.xs,
marginLeft: spacing.md,
borderLeftWidth: 1,
borderLeftColor: colors.borderSubtle
},
// The open tab, drawn like the strip's active tab: raised, with a line under it.
tabCell: {
flex: 1,
minWidth: 0,
backgroundColor: colors.bgRaised,
borderBottomWidth: 2,
borderBottomColor: colors.textSecondary,
borderRightWidth: 1,
borderRightColor: colors.borderSubtle,
overflow: 'hidden'
},
tabPress: {
flex: 1,
justifyContent: 'center',
paddingLeft: spacing.lg,
paddingRight: spacing.sm
},
tabContent: { flexDirection: 'row', alignItems: 'center', gap: 6 },
// Keeps web SVGs from shrinking before the title ellipsizes.
mark: { flexShrink: 0 },
title: {
flexShrink: 1,
minWidth: 0,
fontSize: 14,
fontWeight: '600',
color: colors.textPrimary
},
sideCell: {
width: 46,
alignItems: 'center',
justifyContent: 'center',
borderRightWidth: 1,
borderRightColor: colors.borderSubtle
},
// At the screen edge; in the top bar the hairline stays to part the cells from the round buttons.
lastCell: { borderRightWidth: 0 },
cellPressed: { backgroundColor: colors.translucentFill },
cellDisabled: { opacity: feedback.disabledOpacity },
countBox: {
minWidth: 19,
height: 19,
paddingHorizontal: 3,
borderRadius: 6,
borderWidth: 1.8,
borderColor: colors.textPrimary,
alignItems: 'center',
justifyContent: 'center'
},
countText: {
fontSize: 11,
fontWeight: '700',
color: colors.textPrimary,
fontVariant: ['tabular-nums']
},
// Another tab needs you: a red dot on the count's corner, ringed in the bar's colour.
alert: {
position: 'absolute',
top: 8,
right: 9,
width: 9,
height: 9,
borderRadius: radii.pill,
backgroundColor: colors.statusRed,
borderWidth: 2,
borderColor: colors.bgPanel
}
}))
@@ -1,28 +0,0 @@
import { File, FileText, Globe, SquareTerminal } from 'lucide-react-native'
import { MobileAgentIcon } from '../../components/MobileAgentIcon'
import { colors } from '../../theme/mobile-theme'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import type { MobileSessionTabRow } from './mobile-session-tab-rows'
/** The tab's agent icon, else an icon for what kind of tab it is. */
export function MobileSessionTabMark({
row,
size
}: {
row: Pick<MobileSessionTabRow, 'tab' | 'agentId'>
size: number
}) {
useMobileColorScheme()
if (row.agentId) {
return <MobileAgentIcon agentId={row.agentId} size={size} />
}
const Icon =
row.tab.type === 'browser'
? Globe
: row.tab.type === 'markdown'
? FileText
: row.tab.type === 'file'
? File
: SquareTerminal
return <Icon size={size} color={colors.textSecondary} strokeWidth={2.1} />
}
@@ -0,0 +1,327 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { View, Text, ScrollView, Pressable, StyleSheet } from 'react-native'
import { File, FileText, Globe, Plus, SquareTerminal } from 'lucide-react-native'
import { triggerMediumImpact } from '../../platform/haptics'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import { MobileAgentIcon } from '../../components/MobileAgentIcon'
import { AgentStateDot } from '../../components/AgentStateDot'
import { ArrivalFade } from '../../components/ArrivalFade'
import { useReducedMotionEnabled } from '../../platform/use-reduced-motion'
import { useNow } from '../../hooks/use-now'
import {
agentDotState,
agentStateLabel,
type AgentDotState
} from '../../worktree/agent-row-display'
import {
getMobileTerminalTabHostAgentIdentity,
getMobileSessionTabTitle,
resolveMobileTerminalTabAgentId
} from '../../terminal/session/mobile-terminal-tab-agent'
import { colors, spacing } from '../../theme/mobile-theme'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import { NavBarButton } from '../../components/nav-bar/NavBarButton'
import {
resolveTabStripEdgeHint,
resolveTabStripHiddenTabs,
resolveTabStripTapOffset,
type TabStripHiddenTabs
} from './tab-strip-scroll'
import { styles } from '../mobile-session-styles'
import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps'
import type { MobileSessionController } from '../use-mobile-session-controller'
const DOUBLE_TAP_RENAME_MS = 300
// A tab drawn before it had any agent state (a strip from the phone's store) fades its dot in when one lands.
function SessionTabAgentDot({ state }: { state: AgentDotState | undefined }) {
const [startedEmpty] = useState(state === undefined)
if (startedEmpty) {
return <ArrivingSessionTabAgentDot state={state} />
}
return state && state !== 'idle' ? <AgentStateDot state={state} /> : null
}
// Mounted with the bare tab, so the motion preference is read before the dot arrives.
function ArrivingSessionTabAgentDot({ state }: { state: AgentDotState | undefined }) {
const reducedMotion = useReducedMotionEnabled()
if (!state || state === 'idle') {
return null
}
return (
<ArrivalFade animate={reducedMotion === false}>
<AgentStateDot state={state} />
</ArrivalFade>
)
}
export function MobileSessionTabStrip({
controller,
inTopBar,
actionsCollapsed = false
}: {
controller: MobileSessionController
inTopBar: boolean
actionsCollapsed?: boolean
}) {
useMobileColorScheme()
const t = useMobileTranslation()
const {
activeSessionTabId,
activeSessionTabIdRef,
tabStripRef,
tabStripOffsetRef,
tabStripViewportWidthRef,
tabStripContentWidthRef,
tabLayoutsRef,
connState,
createTabBusy,
handleOpenNewTab,
scrollActiveTabIntoView,
holdTabStripReveal,
cancelHeldTabStripReveal,
switchSessionTab,
openSessionTabActionSheetAfterKeyboardDismiss,
setRenameTarget,
activeHandleRef,
visibleTabs,
terminals
} = controller
const tabBarKeepsKeyboard = useKeyboardPersistingTaps('handled')
const lastTabTapRef = useRef<{ id: string; at: number } | null>(null)
const now = useNow(60_000)
const tabStates = useMemo(() => {
const states = new Map<string, AgentDotState>()
for (const tab of visibleTabs) {
// Why: a status restored across a host restart is unconfirmed, so like desktop it shows no live state.
if (tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed) {
states.set(tab.id, agentDotState(tab.agentStatus, now))
} else if (tab.type === 'agent-session' && tab.chatStatus) {
states.set(tab.id, agentDotState(tab.chatStatus, now))
}
}
return states
}, [visibleTabs, now])
const [hiddenTabs, setHiddenTabs] = useState<TabStripHiddenTabs>({ left: [], right: [] })
const refreshHiddenTabs = () => {
const next = resolveTabStripHiddenTabs({
layouts: tabLayoutsRef.current,
viewportWidth: tabStripViewportWidthRef.current,
currentOffset: tabStripOffsetRef.current
})
// Why: scroll fires every frame; re-render only when a tab crosses an edge.
setHiddenTabs((prev) =>
prev.left.join('\n') === next.left.join('\n') &&
prev.right.join('\n') === next.right.join('\n')
? prev
: next
)
}
const leftHint = resolveTabStripEdgeHint(hiddenTabs.left, tabStates)
const rightHint = resolveTabStripEdgeHint(hiddenTabs.right, tabStates)
const pressTab = useCallback(
(t: (typeof visibleTabs)[number]) => {
const at = Date.now()
const lastTap = lastTabTapRef.current
lastTabTapRef.current = { id: t.id, at }
if (
lastTap?.id === t.id &&
at - lastTap.at < DOUBLE_TAP_RENAME_MS &&
t.type === 'terminal' &&
typeof t.terminal === 'string'
) {
lastTabTapRef.current = null
triggerMediumImpact()
setRenameTarget({
handle: t.terminal,
title: t.title,
isActive: t.terminal === activeHandleRef.current
})
// The first tap's held reveal still runs once the window closes.
return
}
cancelHeldTabStripReveal()
const nextOffset = resolveTabStripTapOffset({
tabId: t.id,
tabs: visibleTabs,
layouts: tabLayoutsRef.current,
viewportWidth: tabStripViewportWidthRef.current,
contentWidth: tabStripContentWidthRef.current,
currentOffset: tabStripOffsetRef.current
})
if (nextOffset !== tabStripOffsetRef.current) {
holdTabStripReveal(nextOffset, DOUBLE_TAP_RENAME_MS)
}
switchSessionTab(t)
},
[
activeHandleRef,
cancelHeldTabStripReveal,
holdTabStripReveal,
setRenameTarget,
switchSessionTab,
tabLayoutsRef,
tabStripContentWidthRef,
tabStripOffsetRef,
tabStripRef,
tabStripViewportWidthRef,
visibleTabs
]
)
const attachTabStrip = useCallback(
(view: ScrollView | null) => {
if (view) {
tabStripOffsetRef.current = 0
tabStripViewportWidthRef.current = 0
tabStripContentWidthRef.current = 0
tabLayoutsRef.current.clear()
}
tabStripRef.current = view
},
[
tabStripRef,
tabStripOffsetRef,
tabStripViewportWidthRef,
tabStripContentWidthRef,
tabLayoutsRef
]
)
return (
<View ref={tabBarKeepsKeyboard} style={inTopBar ? styles.tabBarInTopBar : styles.tabBar}>
{/* Why: tab taps must register on first press with the keyboard open instead of being eaten by dismissal (#5106). */}
<View style={styles.tabScrollFrame}>
<ScrollView
ref={attachTabStrip}
horizontal
showsHorizontalScrollIndicator={false}
style={[styles.tabScroll, inTopBar && styles.tabScrollInTopBar]}
contentContainerStyle={[styles.tabContent, inTopBar && styles.tabContentInTopBar]}
keyboardShouldPersistTaps="handled"
scrollEventThrottle={16}
onScrollBeginDrag={cancelHeldTabStripReveal}
onScroll={(e) => {
tabStripOffsetRef.current = e.nativeEvent.contentOffset.x
refreshHiddenTabs()
}}
onLayout={(e) => {
tabStripViewportWidthRef.current = e.nativeEvent.layout.width
scrollActiveTabIntoView(activeSessionTabIdRef.current, false)
refreshHiddenTabs()
}}
onContentSizeChange={(width) => {
tabStripContentWidthRef.current = width
scrollActiveTabIntoView(activeSessionTabIdRef.current, false)
refreshHiddenTabs()
}}
>
{visibleTabs.map((tab, index) => {
const tabState = tabStates.get(tab.id)
const hostAgentIdentity = getMobileTerminalTabHostAgentIdentity(tab, terminals)
const title = getMobileSessionTabTitle(tab, hostAgentIdentity)
return (
<Pressable
key={tab.id}
style={({ pressed }) => [
styles.tab,
index === 0 && !inTopBar && styles.tabFirst,
tab.id === activeSessionTabId && styles.tabActive,
pressed && styles.tabPressed
]}
onLayout={(e) => {
const { x, width } = e.nativeEvent.layout
tabLayoutsRef.current.set(tab.id, { x, width })
if (tab.id === activeSessionTabIdRef.current) {
scrollActiveTabIntoView(tab.id, false)
}
refreshHiddenTabs()
}}
onPress={() => pressTab(tab)}
accessibilityRole="tab"
accessibilityLabel={
tabState && tabState !== 'idle'
? t('session.tabStrip.tabStatus', '{{title}}, {{status}}', {
title,
status: agentStateLabel(tabState)
})
: title
}
accessibilityState={{ selected: tab.id === activeSessionTabId }}
onLongPress={() => {
triggerMediumImpact()
openSessionTabActionSheetAfterKeyboardDismiss(tab)
}}
delayLongPress={400}
>
<View style={styles.tabLabelRow}>
<SessionTabAgentDot state={tabState} />
<View style={styles.tabIcon}>
{tab.type === 'browser' && (
<Globe size={13} color={colors.textSecondary} strokeWidth={2.1} />
)}
{tab.type === 'markdown' && (
<FileText size={13} color={colors.textSecondary} strokeWidth={2.1} />
)}
{tab.type === 'file' && (
<File size={13} color={colors.textSecondary} strokeWidth={2.1} />
)}
{tab.type === 'agent-session' && (
<MobileAgentIcon agentId={tab.agent} size={13} />
)}
{tab.type === 'terminal' &&
(() => {
const agentId = resolveMobileTerminalTabAgentId(tab, hostAgentIdentity)
return agentId ? (
<MobileAgentIcon agentId={agentId} size={13} />
) : (
<SquareTerminal
size={13}
color={colors.textSecondary}
strokeWidth={2.1}
/>
)
})()}
</View>
<Text
style={[styles.tabText, tab.id === activeSessionTabId && styles.tabTextActive]}
numberOfLines={1}
>
{title}
</Text>
</View>
</Pressable>
)
})}
</ScrollView>
{leftHint ? (
<View pointerEvents="none" style={[styles.tabEdgeHint, styles.tabEdgeHintLeft]}>
<AgentStateDot state={leftHint} />
</View>
) : null}
{rightHint ? (
<View pointerEvents="none" style={[styles.tabEdgeHint, styles.tabEdgeHintRight]}>
<AgentStateDot state={rightHint} />
</View>
) : null}
</View>
{/* Terminal layout and Quick commands live in the header's ⋯ menu. */}
{!actionsCollapsed ? (
<View style={newTabStyles.slot}>
<NavBarButton
disabled={createTabBusy || connState !== 'connected'}
onPress={handleOpenNewTab}
accessibilityLabel={t('session.tabStrip.newTab', 'New tab')}
icon={Plus}
/>
</View>
) : null}
</View>
)
}
// The right inset matches the nav bar's, so the + lines up with the ⋯ above it.
const newTabStyles = StyleSheet.create({
slot: {
paddingLeft: spacing.sm,
paddingRight: spacing.md
}
})
@@ -1,220 +0,0 @@
import { Fragment, useRef, useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import { Plus, X } from 'lucide-react-native'
import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer'
import { ListGroup, SectionHeader } from '../../components/list/ListGroup'
import { NavBarButton } from '../../components/nav-bar/NavBarButton'
import { SheetHeader } from '../../components/nav-bar/SheetHeader'
import { SwipeRowActions } from '../../components/SwipeRowActions'
import { AgentStateDot } from '../../components/AgentStateDot'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import { useNow } from '../../hooks/use-now'
import { formatTimeAgo } from '../../worktree/agent-row-display'
import { colors, radii, spacing } from '../../theme/mobile-theme'
import { themedStyleSheet } from '../../theme/themed-styles'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import type { MobileSessionTabGroup, MobileSessionTabRow } from './mobile-session-tab-rows'
import { MobileSessionTabMark } from './MobileSessionTabMark'
import type { MobileSessionController } from '../use-mobile-session-controller'
const TILE_SIZE = 34
const TILE_DOT_RING = 2
const GROUP_ORDER: readonly MobileSessionTabGroup[] = ['needs-you', 'working', 'other']
/** Every tab in the workspace, what needs you first; tap one to go there, swipe one to close it. */
export function MobileSessionTabsSheet({
controller,
rows,
visible,
onClose
}: {
controller: MobileSessionController
rows: readonly MobileSessionTabRow[]
visible: boolean
onClose: () => void
}) {
useMobileColorScheme()
const t = useMobileTranslation()
const now = useNow(60_000)
const {
activeSessionTabId,
worktreeName,
switchSessionTab,
handleCloseSessionTab,
handleOpenNewTab,
createTabBusy,
connState
} = controller
// Sections hold still while the sheet is open, so a row never moves under a finger.
const [frozenGroups, setFrozenGroups] = useState<ReadonlyMap<string, MobileSessionTabGroup>>()
if (visible && frozenGroups === undefined) {
setFrozenGroups(new Map(rows.map((row) => [row.tab.id, row.group])))
}
const afterCloseRef = useRef<(() => void) | null>(null)
const sections = GROUP_ORDER.map((group) => ({
group,
rows: rows.filter((row) => (frozenGroups?.get(row.tab.id) ?? row.group) === group)
})).filter((section) => section.rows.length > 0)
const sectionTitles: Record<MobileSessionTabGroup, string> = {
'needs-you': t('session.tabsSheet.needsYou', 'Needs you'),
working: t('session.tabsSheet.working', 'Working'),
other: t('session.tabsSheet.everythingElse', 'Everything else')
}
const title =
rows.length === 1
? t('session.tabBar.oneTab', '1 tab')
: t('session.tabBar.tabCount', '{{count}} tabs', { count: rows.length })
const renderRow = (row: MobileSessionTabRow) => {
const current = row.tab.id === activeSessionTabId
const badge = row.dotState && row.dotState !== 'idle' ? row.dotState : undefined
const time = current
? t('session.tabsSheet.open', 'Open')
: row.timeAt !== null
? formatTimeAgo(row.timeAt, now)
: ''
return (
<SwipeRowActions
key={row.tab.id}
trailing={{
label: t('common.close', 'Close'),
accessibilityLabel: t('session.tabsSheet.closeTab', 'Close {{title}}', {
title: row.title
}),
icon: X,
background: colors.statusRed,
foreground: colors.onStatusRed,
onPress: () => void handleCloseSessionTab(row.tab)
}}
>
{(guardPress) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={[row.title, row.detail, time].filter(Boolean).join(', ')}
accessibilityState={{ selected: current }}
style={styles.row}
onPress={guardPress(() => {
if (!current) {
switchSessionTab(row.tab)
}
onClose()
})}
>
{({ pressed }) => (
<>
{current || pressed ? <View pointerEvents="none" style={styles.wash} /> : null}
<View style={styles.tile}>
<MobileSessionTabMark row={row} size={17} />
{badge ? (
<View style={styles.tileBadge}>
<AgentStateDot state={badge} />
</View>
) : null}
</View>
<View style={styles.text}>
<Text style={styles.title} numberOfLines={1}>
{row.title}
</Text>
<Text style={styles.detail} numberOfLines={1}>
{row.detail}
</Text>
</View>
{time ? (
<Text style={[styles.time, current && styles.timeCurrent]}>{time}</Text>
) : null}
</>
)}
</Pressable>
)}
</SwipeRowActions>
)
}
return (
<BottomDrawer
visible={visible}
onClose={onClose}
onAfterClose={() => {
setFrozenGroups(undefined)
const afterClose = afterCloseRef.current
afterCloseRef.current = null
afterClose?.()
}}
>
<View>
<SheetHeader title={title} subtitle={worktreeName || undefined} />
<View style={styles.newTab}>
<NavBarButton
icon={Plus}
disabled={createTabBusy || connState !== 'connected'}
accessibilityLabel={t('session.tabStrip.newTab', 'New tab')}
onPress={() => {
// The new-tab sheet is its own drawer; open it once this one is gone.
afterCloseRef.current = handleOpenNewTab
onClose()
}}
/>
</View>
</View>
<View style={styles.body}>
{sections.map((section, index) => (
<Fragment key={section.group}>
{sections.length > 1 ? (
<SectionHeader title={sectionTitles[section.group]} first={index === 0} />
) : null}
<ListGroup separatorInset={spacing.lg + TILE_SIZE + spacing.md}>
{section.rows.map(renderRow)}
</ListGroup>
</Fragment>
))}
</View>
</BottomDrawer>
)
}
const styles = themedStyleSheet(() => ({
// Over the sheet header's empty trailing side, centred in its 52pt row.
newTab: { position: 'absolute', top: 8, right: spacing.xs },
body: { paddingBottom: spacing.lg },
// Opaque so a swipe's action stays hidden until the row slides off it.
row: {
minHeight: 60,
flexDirection: 'row',
alignItems: 'center',
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.sm,
backgroundColor: colors.sheetGroup
},
// The tab you're in, or a pressed row, washed like a picked segment on a sheet group.
wash: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: colors.translucentFill
},
tile: {
width: TILE_SIZE,
height: TILE_SIZE,
borderRadius: radii.tile,
backgroundColor: colors.translucentFill,
alignItems: 'center',
justifyContent: 'center'
},
// The state dot on the tile's corner, ringed in the group's colour.
tileBadge: {
position: 'absolute',
top: -4,
right: -4,
padding: TILE_DOT_RING,
borderRadius: radii.pill,
backgroundColor: colors.sheetGroup
},
text: { flex: 1, minWidth: 0, gap: 2 },
title: { fontSize: 15, fontWeight: '600', color: colors.textPrimary },
detail: { fontSize: 13, color: colors.textSecondary },
time: { fontSize: 12, color: colors.textMuted, fontVariant: ['tabular-nums'] },
timeCurrent: { fontWeight: '600', color: colors.accentBlue }
}))
@@ -1,121 +0,0 @@
import { agentListPreview } from '../../agents/agent-list-row-text'
import { agentStatusGroup } from '../../agents/agent-list-rows'
import { translate } from '../../i18n/mobile-i18n'
import {
getMobileSessionTabTitle,
getMobileTerminalTabHostAgentIdentity,
resolveMobileTerminalTabAgentId
} from '../../terminal/session/mobile-terminal-tab-agent'
import {
agentDotState,
agentRowTimeAt,
agentStateLabel,
type AgentDotState
} from '../../worktree/agent-row-display'
import type { MobileSessionTab } from './mobile-session-tabs'
export type MobileSessionTabGroup = 'needs-you' | 'working' | 'other'
export type MobileSessionTabRow = {
tab: MobileSessionTab
title: string
/** The agent whose icon marks the tab; null draws the tab kind's icon. */
agentId: string | null
dotState: AgentDotState | undefined
group: MobileSessionTabGroup
/** The second line: the state, then what the tab is doing or showing. */
detail: string
timeAt: number | null
}
export function mobileSessionTabDotState(
tab: MobileSessionTab,
now: number
): AgentDotState | undefined {
// Why: a status restored across a host restart is unconfirmed, so like desktop it shows no live state.
if (tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed) {
return agentDotState(tab.agentStatus, now)
}
if (tab.type === 'agent-session' && tab.chatStatus) {
return agentDotState(tab.chatStatus, now)
}
return undefined
}
function tabGroup(state: AgentDotState | undefined): MobileSessionTabGroup {
if (!state) {
return 'other'
}
const group = agentStatusGroup(state)
return group === 'needs-you' || group === 'working' ? group : 'other'
}
function tabContent(
tab: MobileSessionTab,
title: string,
dotState: AgentDotState | undefined
): string {
switch (tab.type) {
case 'terminal': {
const status = tab.agentStatus
if (!status || !dotState) {
return ''
}
return agentListPreview(status, agentStatusGroup(dotState), title)
}
case 'browser':
return tab.url === title ? '' : tab.url
case 'markdown':
case 'file':
return tab.relativePath === title ? '' : tab.relativePath
case 'agent-session':
return ''
}
}
function tabKindLabel(tab: MobileSessionTab): string {
switch (tab.type) {
case 'browser':
return translate('session.tabRows.browser', 'Browser')
case 'markdown':
return translate('session.tabRows.markdown', 'Markdown note')
case 'file':
return translate('session.tabRows.file', 'File')
case 'agent-session':
return translate('session.tabRows.chat', 'Chat')
case 'terminal':
return translate('session.tabRows.terminal', 'Terminal')
}
}
export function buildMobileSessionTabRow(
tab: MobileSessionTab,
terminals: readonly { handle: string; agentIdentity?: string }[],
now: number
): MobileSessionTabRow {
const hostAgentIdentity = getMobileTerminalTabHostAgentIdentity(tab, terminals)
const title = getMobileSessionTabTitle(tab, hostAgentIdentity)
const dotState = mobileSessionTabDotState(tab, now)
const stateWord = dotState && dotState !== 'idle' ? agentStateLabel(dotState) : ''
const content = tabContent(tab, title, dotState)
const timeAt =
tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed
? agentRowTimeAt(tab.agentStatus)
: tab.type === 'agent-session' && tab.chatStatus
? tab.chatStatus.updatedAt
: null
return {
tab,
title,
agentId:
tab.type === 'agent-session'
? tab.agent
: tab.type === 'terminal'
? resolveMobileTerminalTabAgentId(tab, hostAgentIdentity)
: null,
dotState,
group: tabGroup(dotState),
detail: [stateWord, content].filter(Boolean).join(' · ') || tabKindLabel(tab),
timeAt
}
}
@@ -1,3 +1,5 @@
import type { AgentDotState } from '../../worktree/agent-row-display'
export type TabStripScrollInput = {
tabX: number
tabWidth: number
@@ -34,3 +36,98 @@ export function resolveTabStripScrollOffset({
return Math.min(Math.max(0, nextOffset), maxOffset)
}
type TabLayouts = ReadonlyMap<string, { x: number; width: number }>
export function resolveTabStripTapOffset(args: {
tabId: string
tabs: readonly { id: string }[]
layouts: TabLayouts
viewportWidth: number
contentWidth: number
currentOffset: number
}): number {
const { tabs, layouts, viewportWidth, contentWidth, currentOffset } = args
const index = tabs.findIndex((tab) => tab.id === args.tabId)
const selected = layouts.get(args.tabId)
if (index === -1 || !selected || viewportWidth <= 0) {
return currentOffset
}
const selectedOnly = resolveTabStripScrollOffset({
tabX: selected.x,
tabWidth: selected.width,
viewportWidth,
contentWidth,
currentOffset
})
if (selectedOnly === currentOffset) {
return currentOffset
}
const left = selected.x + selected.width / 2 < currentOffset + viewportWidth / 2
const neighbor = tabs[index + (left ? -1 : 1)]
const layout = neighbor ? layouts.get(neighbor.id) : undefined
let start = selected.x
let end = selected.x + selected.width
if (layout) {
const gap = left ? selected.x - (layout.x + layout.width) : layout.x - end
// Keep the tapped tab whole while revealing as much of its neighbor as fits within both margins.
const peek = Math.min(layout.width, Math.max(0, viewportWidth - 24 - selected.width - gap))
if (left) {
start -= gap + peek
} else {
end += gap + peek
}
}
return resolveTabStripScrollOffset({
tabX: start,
tabWidth: end - start,
viewportWidth,
contentWidth,
currentOffset
})
}
export type TabStripHiddenTabs = { left: readonly string[]; right: readonly string[] }
export function resolveTabStripHiddenTabs(args: {
layouts: TabLayouts
viewportWidth: number
currentOffset: number
}): TabStripHiddenTabs {
const left: string[] = []
const right: string[] = []
if (args.viewportWidth > 0) {
for (const [tabId, layout] of args.layouts) {
const center = layout.x + layout.width / 2
if (center < args.currentOffset) {
left.push(tabId)
} else if (center > args.currentOffset + args.viewportWidth) {
right.push(tabId)
}
}
}
return { left, right }
}
// Lower ranks win when several hidden tabs share an edge; other states get no edge hint.
const EDGE_HINT_RANK: Partial<Record<AgentDotState, number>> = {
blocked: 0,
waiting: 0,
working: 1,
monitoring: 1
}
export function resolveTabStripEdgeHint(
tabIds: readonly string[],
tabStates: ReadonlyMap<string, AgentDotState>
): AgentDotState | null {
let hint: AgentDotState | null = null
for (const tabId of tabIds) {
const state = tabStates.get(tabId)
const rank = state ? EDGE_HINT_RANK[state] : undefined
if (state && rank !== undefined && (hint === null || rank < (EDGE_HINT_RANK[hint] ?? 0))) {
hint = state
}
}
return hint
}
@@ -52,7 +52,6 @@ export function useMobileSessionFoundation() {
name: worktreeName,
path: worktreePath,
hostId: worktreeHostId,
branch: worktreeBranch,
resolution: worktreeResolution
} = useLiveWorktreeName({
client,
@@ -116,7 +115,6 @@ export function useMobileSessionFoundation() {
worktreeName,
worktreePath,
worktreeHostId,
worktreeBranch,
worktreeResolution,
isWideLayout,
activePanel,
@@ -7,7 +7,7 @@ import {
shouldShowSessionHeaderChecksAction,
panelRouteDescriptor
} from './session-panel-host'
import type { ActionSheetAction } from '../components/ActionSheetModal'
import { MobileAgentIcon } from '../components/MobileAgentIcon'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import {
useWorkspaceExecutionHost,
@@ -49,81 +49,127 @@ export function useMobileSessionPanelRouteActions(scope: MobileSessionPresentati
quickCommandsSupported,
showToast
} = scope
const agentStatusRow = (errorHint: string): ActionSheetAction | null =>
const otherRuntimeAgentRow = {
id: 'otherServerAgents',
label: t('session.usePanelRouteActions.otherServerAgents', 'Agents on Another Server'),
hint: t('session.usePanelRouteActions.pairServerHint', 'Pair that server directly'),
icon: Bot,
disabled: true,
onPress: () => {}
}
const createTabAgentActions =
createTabAgentLoadState === 'loading'
? {
id: 'detectingAgents',
label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'),
icon: Bot,
disabled: true,
loading: true,
onPress: () => {}
}
? [
{
id: 'detectingAgents',
label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'),
icon: Bot,
disabled: true,
loading: true,
onPress: () => {}
}
]
: createTabAgentOptions.length > 0
? null
: createTabAgentLoadState === 'loaded'
? {
id: 'noEnabledAgents',
label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'),
icon: Bot,
disabled: true,
onPress: () => {}
? createTabAgentOptions.map((option) => ({
id: `agent:${option.agent}`,
label: option.label,
renderIcon: () => <MobileAgentIcon agentId={option.agent} size={16} />,
onPress: () => {
setShowCreateTabDrawer(false)
void handleCreateTerminal(option.agent)
}
: createTabAgentLoadState === 'other-runtime'
? {
id: 'otherServerAgents',
label: t(
'session.usePanelRouteActions.otherServerAgents',
'Agents on Another Server'
),
hint: t('session.usePanelRouteActions.pairServerHint', 'Pair that server directly'),
}))
: createTabAgentLoadState === 'loaded'
? [
{
id: 'noEnabledAgents',
label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'),
icon: Bot,
disabled: true,
onPress: () => {}
}
]
: createTabAgentLoadState === 'other-runtime'
? [otherRuntimeAgentRow]
: createTabAgentLoadState === 'error'
? {
id: 'presetsUnavailable',
label: t(
'session.usePanelRouteActions.presetsUnavailable',
'Agent Presets Unavailable'
),
hint: errorHint,
? [
{
id: 'presetsUnavailable',
label: t(
'session.usePanelRouteActions.presetsUnavailable',
'Agent Presets Unavailable'
),
hint: t(
'session.usePanelRouteActions.checkHostHint',
'Check the host connection'
),
icon: Bot,
disabled: true,
onPress: () => {}
}
]
: []
const sendDiffNotesAgentActions =
pendingDiffNotesDelivery === null
? []
: createTabAgentLoadState === 'loading'
? [
{
id: 'detectingAgents',
label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'),
icon: Bot,
disabled: true,
loading: true,
onPress: () => {}
}
]
: createTabAgentOptions.length > 0
? createTabAgentOptions.map((option) => ({
id: `agent:${option.agent}`,
label: option.label,
hint: t('session.usePanelRouteActions.newSessionHint', 'New agent session'),
icon: Bot,
onPress: () => {
const delivery = pendingDiffNotesDelivery
setPendingDiffNotesDelivery(null)
if (!delivery) {
return
}
void sendDiffNotesToNewAgent(delivery, async () => {
await handleCreateTerminal(option.agent, {
initialPrompt: delivery.prompt,
onPromptSent: () => void clearDeliveredDiffComments(delivery.comments)
})
})
}
}))
: createTabAgentLoadState === 'loaded'
? [
{
id: 'noEnabledAgents',
label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'),
icon: Bot,
disabled: true,
onPress: () => {}
}
: null
const createTabAgentStatusRow = agentStatusRow(
t('session.usePanelRouteActions.checkHostHint', 'Check the host connection')
)
const sendDiffNotesStatusRow = agentStatusRow(
t('session.usePanelRouteActions.copyNotesHint', 'Copy notes instead')
)
const sendDiffNotesAgentActions: ActionSheetAction[] =
pendingDiffNotesDelivery === null
? []
: sendDiffNotesStatusRow
? [sendDiffNotesStatusRow]
: createTabAgentOptions.map((option) => ({
id: `agent:${option.agent}`,
label: option.label,
hint: t('session.usePanelRouteActions.newSessionHint', 'New agent session'),
icon: Bot,
onPress: () => {
const delivery = pendingDiffNotesDelivery
setPendingDiffNotesDelivery(null)
if (!delivery) {
return
}
void sendDiffNotesToNewAgent(delivery, async () => {
await handleCreateTerminal(option.agent, {
initialPrompt: delivery.prompt,
onPromptSent: () => void clearDeliveredDiffComments(delivery.comments)
})
})
}
}))
]
: createTabAgentLoadState === 'other-runtime'
? [otherRuntimeAgentRow]
: createTabAgentLoadState === 'error'
? [
{
id: 'presetsUnavailable',
label: t(
'session.usePanelRouteActions.presetsUnavailable',
'Agent Presets Unavailable'
),
hint: t('session.usePanelRouteActions.copyNotesHint', 'Copy notes instead'),
icon: Bot,
disabled: true,
onPress: () => {}
}
]
: []
const handleSessionContentRowLayout = useCallback((event: LayoutChangeEvent) => {
const width = Math.round(event.nativeEvent.layout.width)
@@ -189,7 +235,7 @@ export function useMobileSessionPanelRouteActions(scope: MobileSessionPresentati
)
}
return {
createTabAgentStatusRow,
createTabAgentActions,
sendDiffNotesAgentActions,
handleSessionContentRowLayout,
handlePanelTap,
@@ -76,8 +76,11 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel)
presentedConnState === 'connected'
? showLoadingState && visibleTabs.length === 0
? t('session.presentation.loadingTabs', 'Loading tabs')
: // The tab count lives in the tab bar, so the header names the branch instead.
(scope.worktreeBranch ?? MOBILE_SESSION_STATUS_LABELS.connected)
: visibleTabs.length === 1
? t('session.presentation.oneTab', '1 tab')
: t('session.presentation.tabCount', '{{tabCount}} tabs', {
tabCount: visibleTabs.length
})
: showConnectionRetry
? t('session.presentation.tapToRetry', '{{status}} — tap to retry', {
status: verdictDisplayLabel(connectionVerdict)
@@ -1,7 +1,7 @@
import { useState, useRef, useMemo } from 'react'
import { useTerminalSplitLayout } from '../terminal/session/use-terminal-split-layout'
import { createLiveInputCapture } from '../terminal/session/live-input-capture'
import { Animated } from 'react-native'
import { Animated, type ScrollView } from 'react-native'
import type { MobileTerminalLinkOpenMode } from '../storage/preferences'
import type { TerminalKeyboardAvoidanceMetrics } from '../terminal/terminal-webview-contract'
import {
@@ -46,6 +46,11 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
const activeSessionTabIdRef = useRef<string | null>(null)
// Preserve an explicit phone tab pick while a host snapshot is transiently incomplete.
const selectedSessionTabIdRef = useRef<string | null>(null)
const tabStripRef = useRef<ScrollView>(null)
const tabStripOffsetRef = useRef(0)
const tabStripViewportWidthRef = useRef(0)
const tabStripContentWidthRef = useRef(0)
const tabLayoutsRef = useRef<Map<string, { x: number; width: number }>>(new Map())
const [markdownDocs, setMarkdownDocs] = useState<Map<string, MarkdownDocState>>(new Map())
const markdownDocsRef = useRef<Map<string, MarkdownDocState>>(new Map())
const [fileDocs, setFileDocs] = useState<Map<string, FileDocState>>(new Map())
@@ -129,6 +134,11 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
setActiveSessionTabId,
activeSessionTabIdRef,
selectedSessionTabIdRef,
tabStripRef,
tabStripOffsetRef,
tabStripViewportWidthRef,
tabStripContentWidthRef,
tabLayoutsRef,
markdownDocs,
setMarkdownDocs,
markdownDocsRef,
@@ -69,6 +69,18 @@ export function mobileCommitDropdownCopy(t: Translate): CommitDropdownCopy {
case 'Enter a commit message to commit':
return t('sourceControl.commitDropdown.enterMessage', 'Enter a commit message to commit')
}
}
},
commitDisabledStatus: (reason) => {
switch (reason) {
case 'Resolve conflicts before committing':
return t('sourceControl.commitDropdown.statusConflicts', 'Conflicts')
case 'Stage at least one file to commit':
return t('sourceControl.commitDropdown.statusNothingStaged', 'Nothing staged')
case 'Enter a commit message to commit':
return t('sourceControl.commitDropdown.statusNeedsMessage', 'Needs message')
}
},
statusNotPublished: t('sourceControl.commitDropdown.statusNotPublished', 'Not published'),
statusNoBranch: t('sourceControl.commitDropdown.statusNoBranch', 'No branch')
}
}
@@ -160,6 +160,15 @@ export function mobileRemoteDropdownCopy(t: Translate): RemoteDropdownCopy {
manualForcePush: (ahead, behind, upstreamName) =>
localizedManualForcePush(ahead, behind, upstreamName, t),
unpublishedForcePush: (branchCommitsAhead) =>
localizedUnpublishedForcePush(branchCommitsAhead, t)
localizedUnpublishedForcePush(branchCommitsAhead, t),
statusUpToDate: t('sourceControl.remoteDropdown.statusUpToDate', 'Up to date'),
statusSetsUpstream: t('sourceControl.remoteDropdown.statusSetsUpstream', 'Sets upstream'),
statusNotPublished: t('sourceControl.remoteDropdown.statusNotPublished', 'Not published'),
statusNoBranch: t('sourceControl.remoteDropdown.statusNoBranch', 'No branch'),
statusMayFail: t('sourceControl.remoteDropdown.statusMayFail', 'May fail'),
statusPublished: t('sourceControl.remoteDropdown.statusPublished', 'Published'),
statusStashFirst: t('sourceControl.remoteDropdown.statusStashFirst', 'Stash first'),
statusReplaces: (behind) =>
t('sourceControl.remoteDropdown.statusReplaces', 'Replaces ↓{{behind}}', { behind })
}
}
@@ -31,6 +31,7 @@ export type MobileSourceControlAction = {
iconKey: MobileSourceControlActionIcon
disabled?: boolean
hint?: string
status?: string
loading?: boolean
skipAutoClose?: boolean
closeBeforePress?: boolean
@@ -84,7 +85,7 @@ export function buildMobileSourceControlActions(
const busy = args.busyAction !== null
const blockForce = (item: DropdownItem): DropdownItem =>
args.forcePushBlockedReason
? { ...item, disabled: true, title: args.forcePushBlockedReason }
? { ...item, disabled: true, title: args.forcePushBlockedReason, status: undefined }
: item
const row = (
item: DropdownItem,
@@ -98,6 +99,7 @@ export function buildMobileSourceControlActions(
disabled: busy || item.disabled,
// Mobile has no tooltips: show why a row is disabled, and always what Force Push replaces.
hint: item.disabled || item.kind === 'force_push' ? item.title : undefined,
status: item.status,
loading: args.busyAction === actionId,
skipAutoClose: true,
onPress
@@ -1,9 +1,10 @@
import { useEffect, useCallback } from 'react'
import { useEffect, useCallback, useRef } from 'react'
import { currentSoftKeyboardHeight, subscribeSoftKeyboard } from '../../platform/keyboard-occlusion'
import { useTerminalViewportRefit } from '../terminal-viewport-refit'
import { removeCustomKey, type CustomKey } from '../terminal-custom-keys'
import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host'
import { writeLastVisitedWorktree } from '../../worktree/last-visited-worktree-by-host'
import { resolveTabStripScrollOffset } from '../../session/tabs/tab-strip-scroll'
import type { MobileSessionLifecycleModel } from '../../session/use-mobile-session-lifecycle'
export type MobileSessionKeyboardScope = Pick<
@@ -11,6 +12,7 @@ export type MobileSessionKeyboardScope = Pick<
| 'activeHandleRef'
| 'visibleTerminalHandlesRef'
| 'terminalPaneViewportsRef'
| 'activeSessionTabId'
| 'clientRef'
| 'connState'
| 'deviceTokenRef'
@@ -20,6 +22,11 @@ export type MobileSessionKeyboardScope = Pick<
| 'setShowCustomKeyModal'
| 'showNativeChatRef'
| 'subscribeToTerminal'
| 'tabLayoutsRef'
| 'tabStripContentWidthRef'
| 'tabStripOffsetRef'
| 'tabStripRef'
| 'tabStripViewportWidthRef'
| 'terminalFrameRef'
| 'terminalRefs'
| 'terminals'
@@ -38,6 +45,12 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope)
connState,
terminals,
terminalTextScale,
activeSessionTabId,
tabStripRef,
tabStripOffsetRef,
tabStripViewportWidthRef,
tabStripContentWidthRef,
tabLayoutsRef,
setCustomKeys,
setShowCustomKeyModal,
deviceTokenRef,
@@ -85,6 +98,55 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope)
)
}, [notifyKeyboardVisibility])
const heldTabStripRevealRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const cancelHeldTabStripReveal = useCallback(() => {
if (heldTabStripRevealRef.current) {
clearTimeout(heldTabStripRevealRef.current)
heldTabStripRevealRef.current = null
}
}, [])
useEffect(() => cancelHeldTabStripReveal, [cancelHeldTabStripReveal])
// Hold strip movement through double-tap detection so its second tap reaches the same tab.
const holdTabStripReveal = useCallback(
(offset: number, delayMs: number) => {
cancelHeldTabStripReveal()
heldTabStripRevealRef.current = setTimeout(() => {
heldTabStripRevealRef.current = null
if (offset !== tabStripOffsetRef.current) {
tabStripOffsetRef.current = offset
tabStripRef.current?.scrollTo({ x: offset, animated: true })
}
}, delayMs)
},
[cancelHeldTabStripReveal]
)
const scrollActiveTabIntoView = useCallback((tabId: string | null, animated: boolean) => {
if (!tabId || heldTabStripRevealRef.current) {
return
}
const layout = tabLayoutsRef.current.get(tabId)
if (!layout) {
return
}
const nextOffset = resolveTabStripScrollOffset({
tabX: layout.x,
tabWidth: layout.width,
viewportWidth: tabStripViewportWidthRef.current,
contentWidth: tabStripContentWidthRef.current,
currentOffset: tabStripOffsetRef.current
})
if (nextOffset !== tabStripOffsetRef.current) {
tabStripOffsetRef.current = nextOffset
tabStripRef.current?.scrollTo({ x: nextOffset, animated })
}
}, [])
useEffect(() => {
const id = requestAnimationFrame(() => scrollActiveTabIntoView(activeSessionTabId, true))
return () => cancelAnimationFrame(id)
}, [activeSessionTabId, scrollActiveTabIntoView])
const executionHost = useWorkspaceExecutionHost()
useEffect(() => {
if (hostId && worktreeId) {
@@ -109,6 +171,9 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope)
notifyTerminalFrameWidth,
notifyKeyboardVisibility,
notifyTerminalCellBoxChange,
scrollActiveTabIntoView,
holdTabStripReveal,
cancelHeldTabStripReveal,
handleDeleteCustomKey,
handleManageShortcuts
}
+1 -1
View File
@@ -88,7 +88,7 @@ export function agentDisplayLabel(row: RuntimeWorktreeAgentRow, now: number): st
// Mirror desktop lastEnteredDoneAt: date main-agent failures independently while subagents remain active.
export function agentRowTimeAt(
row: AgentRowVerdictSource & Pick<RuntimeWorktreeAgentRow, 'stateStartedAt'>
row: Pick<RuntimeWorktreeAgentRow, 'state' | 'interrupted' | 'mainAgent' | 'stateStartedAt'>
): number {
if (row.state !== 'done' && row.mainAgent && agentVerdictDisplayMark(row) === 'failed') {
return row.mainAgent.stateStartedAt
@@ -14,7 +14,6 @@ export const sessionWorktreeRecordSchema = z
repo: salvagedOptional('repo', z.string().nullable()),
path: salvagedOptional('path', z.string()),
hostId: salvagedOptional('hostId', z.string()),
branch: salvagedOptional('branch', z.string().nullable()),
diffComments: z.unknown().optional()
})
)
@@ -23,11 +22,6 @@ export const sessionWorktreeRecordSchema = z
(
reply
):
| (WorktreeDisplayNameSource & {
path?: string
hostId?: string
branch?: string | null
diffComments?: unknown
})
| (WorktreeDisplayNameSource & { path?: string; hostId?: string; diffComments?: unknown })
| undefined => reply.worktree
)
+3 -16
View File
@@ -30,8 +30,6 @@ export type LiveWorktreeName = {
/** Where the worktree lives on its host; null until the host's record arrives. */
path: string | null
hostId: string | null
/** The checked-out branch without refs/heads/; null for folders, detached heads and until the record arrives. */
branch: string | null
resolution: WorktreeShowResolution
}
@@ -50,7 +48,6 @@ export function useLiveWorktreeName({
name: string
path?: string | null
hostId?: string | null
branch?: string | null
}>(() => ({ worktreeId, name: routeNameHint }))
// Key verdicts by route so a previous workspace’s deletion cannot escape into the new one.
const [resolved, setResolved] = useState<{
@@ -128,16 +125,13 @@ export function useLiveWorktreeName({
if (liveName) {
const path = worktree?.path || null
const hostId = worktree?.hostId ?? null
// Match desktop formatBranchName by hiding the refs/heads/ prefix.
const branch = worktree?.branch?.replace(/^refs\/heads\//, '') || null
setWorktreeName((current) =>
current.worktreeId === worktreeId &&
current.name === liveName &&
current.path === path &&
current.hostId === hostId &&
current.branch === branch
current.hostId === hostId
? current
: { worktreeId, name: liveName, path, hostId, branch }
: { worktreeId, name: liveName, path, hostId }
)
}
hasSuccessfulRefresh = true
@@ -203,19 +197,12 @@ export function useLiveWorktreeName({
)
if (isFloatingWorkspace) {
return {
name: getFloatingWorkspaceTitle(),
path: null,
hostId: 'local',
branch: null,
resolution: 'unknown'
}
return { name: getFloatingWorkspaceTitle(), path: null, hostId: 'local', resolution: 'unknown' }
}
return {
name: worktreeName.worktreeId === worktreeId ? worktreeName.name : routeNameHint,
path: worktreeName.worktreeId === worktreeId ? (worktreeName.path ?? null) : null,
hostId: worktreeName.worktreeId === worktreeId ? (worktreeName.hostId ?? null) : null,
branch: worktreeName.worktreeId === worktreeId ? (worktreeName.branch ?? null) : null,
resolution: resolved.worktreeId === worktreeId ? resolved.resolution : 'unknown'
}
}
+2 -2
View File
@@ -308,8 +308,8 @@ Use them only when the user explicitly asks to publish through Orca. A generic r
public link, page, or URL does not select Orca, and a provider the user names always wins.
**Only a human can turn publishing on or off.** `share` and `update` need the device-wide
setting under Settings → Artifacts ("Allow publishing public artifact links"); there is no
CLI or RPC way to grant it. `list`, `unshare`, and `delete` are never gated, so old links
setting under Settings → Artifacts ("Allow publishing public artifact links"), which is on
for new profiles; there is no CLI or RPC way to grant it. `list`, `unshare`, and `delete` are never gated, so old links
stay auditable and revocable.
A denied share fails with `artifact_sharing_disabled` before any upload. Do not retry. Tell
+2 -2
View File
@@ -536,8 +536,8 @@ const ORCA_CLI_MARKDOWN = [
"public link, page, or URL does not select Orca, and a provider the user names always wins.",
"",
"**Only a human can turn publishing on or off.** `share` and `update` need the device-wide",
"setting under Settings → Artifacts (\"Allow publishing public artifact links\"); there is no",
"CLI or RPC way to grant it. `list`, `unshare`, and `delete` are never gated, so old links",
"setting under Settings → Artifacts (\"Allow publishing public artifact links\"), which is on",
"for new profiles; there is no CLI or RPC way to grant it. `list`, `unshare`, and `delete` are never gated, so old links",
"stay auditable and revocable.",
"",
"A denied share fails with `artifact_sharing_disabled` before any upload. Do not retry. Tell",
@@ -0,0 +1,148 @@
import { setTimeout as delay } from 'node:timers/promises'
import { observeAcpForkSupport } from '../capabilities/acp-fork-support'
import {
assertStructuredAgentResolutionCurrent,
type StructuredAgentResolutionOperation
} from '../../native-chat/structured-agent-command-resolution'
import type { AgentSessionModelOption } from '../../../shared/agent-session/agent-session-wire'
import type { AcpSessionModelDiscovery } from './acp-model-discovery-policy'
import type { AcpLaunchSpec } from '../launch/acp-launch-contract'
import type { AcpSessionStarted, AcpSessionStartOptions } from '../protocol/acp-session-setup'
import { AcpStructuredOptions } from '../options/acp-structured-options'
import type {
InitializeResponse,
SetSessionConfigOptionResponse
} from '../generated/acp-protocol.generated'
import { withTimeout } from '../../../shared/promise-timeout-fallback'
import { AcpAgentError } from '../transport/acp-errors'
/** Session-free capability boundary: no session methods are exposed. */
export type AcpModelCatalogConnection = {
initialize(): Promise<InitializeResponse>
requestSessionFreeExtension(method: string, params: unknown): Promise<unknown>
close(): Promise<unknown>
}
export type AcpModelCatalogSessionConnection = Omit<
AcpModelCatalogConnection,
'requestSessionFreeExtension'
> & {
start(options: AcpSessionStartOptions): Promise<AcpSessionStarted>
setConfigOption(configId: string, value: string): Promise<SetSessionConfigOptionResponse>
deleteSession(sessionId: string): Promise<unknown>
}
// OpenCode can answer -32603 while its providers are still opening; a later attempt lists them.
async function startListingSession(
connection: AcpModelCatalogSessionConnection,
workspace: string,
operation?: StructuredAgentResolutionOperation
): Promise<AcpSessionStarted> {
for (const backoffMs of [250, 500]) {
try {
return await connection.start({ cwd: workspace, mcpServers: [] })
} catch (error) {
if (!(error instanceof AcpAgentError && error.code === -32603)) {
throw error
}
}
await delay(backoffMs, undefined, { signal: operation?.signal })
assertStructuredAgentResolutionCurrent(operation)
}
return connection.start({ cwd: workspace, mcpServers: [] })
}
/** Lists models from a disposable session, learning menus for the models it starts on or switches to. */
export async function readSessionModels(
spec: AcpLaunchSpec,
listing: AcpSessionModelDiscovery,
connection: AcpModelCatalogSessionConnection,
workspace: string,
operation?: StructuredAgentResolutionOperation,
selectedModels?: readonly string[],
launchedModel?: string,
ready?: (cleanup: () => Promise<unknown>) => void
): Promise<{ models: AgentSessionModelOption[]; attemptedModels: string[] }> {
const initialized = await connection.initialize()
assertStructuredAgentResolutionCurrent(operation)
observeAcpForkSupport(spec.agent, initialized)
const deletes = Boolean(initialized.agentCapabilities?.sessionCapabilities?.delete)
if (!deletes && !listing.sessionFolderArgs) {
throw new Error(`${spec.agent} cannot delete a session, so it lists its models only in chats`)
}
const started = await startListingSession(connection, workspace, operation)
let stopped = false
const cleanup = async (): Promise<void> => {
stopped = true
if (deletes) {
await connection.deleteSession(started.sessionId).catch((error: unknown) => {
console.warn(`[acp-model-catalog] ${spec.agent} kept its listing session:`, error)
})
}
}
// Startup and menu discovery have separate budgets; cleanup also runs on cancellation.
ready?.(cleanup)
const options = new AcpStructuredOptions(spec.dialect)
options.adoptSession(started.response, 'new')
let models = options.read().models
const attemptedModels: string[] = []
try {
if (launchedModel !== undefined) {
attemptedModels.push(launchedModel)
const running = options.read().current.model
// An unresolved --model leaves OMP on its default with a menu that is not that model's.
if (running !== launchedModel) {
models = models.map((row) =>
row.id === running ? { ...row, efforts: [], effortsKnown: false as const } : row
)
}
} else if (spec.dialect.effortChangesModel) {
const byId = new Map(models.map((model) => [model.id, model]))
const targets = selectedModels ? selectedModels.flatMap((id) => byId.get(id) ?? []) : models
const sweep = async () => {
for (const model of targets) {
if (stopped) {
return
}
assertStructuredAgentResolutionCurrent(operation)
if (model.effortsKnown !== false) {
continue
}
attemptedModels.push(model.id)
try {
for (let attempt = 0; attempt < 2 && !stopped; attempt++) {
const write = options.write('model', model.id)
if (write?.method !== 'config') {
break
}
const reply = await connection.setConfigOption(write.configId, write.value)
if (stopped) {
return
}
assertStructuredAgentResolutionCurrent(operation)
options.adoptConfigOptions(reply.configOptions)
const observed = options.read()
if (observed.current.model !== model.id) {
continue
}
const known = observed.models.find((row) => row.id === model.id)
if (known) {
models = models.map((row) => (row.id === model.id ? known : row))
}
break
}
} catch {
assertStructuredAgentResolutionCurrent(operation)
}
}
}
await withTimeout(sweep(), 5_000, undefined)
}
assertStructuredAgentResolutionCurrent(operation)
return { models, attemptedModels }
} finally {
if (!ready) {
await cleanup()
}
}
}
@@ -1,3 +1,6 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { acpLaunchSpecFor } from '../launch/acp-launch-registry'
import type { AcpLaunchSpec } from '../launch/acp-launch-contract'
@@ -5,6 +8,10 @@ import { createAcpModelCatalogProbe } from './acp-model-catalog-probe'
import { AcpSessionRuntime } from '../protocol/acp-session-runtime'
import { AcpScriptedAgent } from '../process/testing/acp-scripted-agent.test-support'
import { openCodeAcpAccountBinding } from '../../opencode/opencode-structured-account-home'
import { AcpAgentExitedError } from '../transport/acp-errors'
// Real `omp acp` 18.17.0 session/new replies: started on its default fake/wide, with
// `--model fake/narrow`, and with `--model fake/gone`, which it cannot resolve.
import recorded from '../fixtures/omp-v18.17.0-model-efforts.json'
// Bypass the app's managed-account service for this fixture.
const OPENCODE: AcpLaunchSpec = {
@@ -87,3 +94,103 @@ describe('ACP model catalog probes', () => {
])
})
})
async function listOmp(selectedModels?: string[]) {
const agent = new AcpScriptedAgent()
agents.push(agent)
let launchedModel: string | undefined
agent.on('initialize', (frame) => agent.reply(frame, { protocolVersion: 1 }))
agent.on('session/new', (frame) =>
agent.reply(frame, {
sessionId: 'probe-session',
...(launchedModel === 'fake/narrow'
? recorded.narrow
: launchedModel === 'fake/gone'
? recorded.unresolved
: recorded.new)
})
)
const dataDirectory = await mkdtemp(join(tmpdir(), 'orca-omp-efforts-'))
try {
const listing = await createAcpModelCatalogProbe(acpLaunchSpecFor('omp')!, {
resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }),
resolveCommand: () => '/opt/omp/bin/omp',
probeVersion: async () => ({ version: '18.17.0' }),
homePath: '/home/user',
dataDirectory,
connectSession: (launch) => {
const at = launch.args.indexOf('--model')
launchedModel = at === -1 ? undefined : launch.args[at + 1]
if (launchedModel?.includes(':')) {
// OMP 18.17.0 prints `Model "fake/gone:high" not found.` and exits 1 before ACP starts.
const exited = async () => {
throw new AcpAgentExitedError('Model "fake/gone:high" not found.')
}
return {
initialize: exited,
start: exited,
setConfigOption: exited,
deleteSession: exited,
close: async () => {}
}
}
const runtime = new AcpSessionRuntime(agent.stdout, agent.stdin)
return {
initialize: () => runtime.initialize(),
start: (options) => runtime.start(options),
setConfigOption: (id, value) => runtime.setConfigOption(id, value),
deleteSession: (sessionId) => runtime.deleteSession(sessionId),
close: async () => runtime.close()
}
}
})(
{ variable: 'PI_CODING_AGENT_DIR', path: '/homes/omp' },
{ workspacePath: '/work/project', ...(selectedModels ? { selectedModels } : {}) }
)
// A model switch would record usage in the user's OMP account.
expect(agent.frames.map((frame) => frame.method)).toEqual(['initialize', 'session/new'])
return (id: string) => listing.models.find((model) => model.id === id)
} finally {
await rm(dataDirectory, { recursive: true, force: true })
}
}
const levels = (model: { efforts: { value: string }[] } | undefined) =>
model?.efforts.map((effort) => effort.value)
it("lists a picked OMP model with its own thinking levels, not the startup model's", async () => {
const listed = await listOmp()
expect(levels(listed('fake/wide'))).toEqual([
'off',
'auto',
'minimal',
'low',
'medium',
'high',
'xhigh'
])
expect(listed('fake/narrow')).toMatchObject({ efforts: [], effortsKnown: false })
const picked = await listOmp(['fake/narrow'])
expect(levels(picked('fake/narrow'))).toEqual(['off', 'auto', 'low', 'high'])
expect(picked('fake/narrow')).not.toHaveProperty('effortsKnown')
expect(picked('fake/wide')).toMatchObject({ efforts: [], effortsKnown: false })
})
it('trusts no menu when OMP cannot start on the picked model', async () => {
const picked = await listOmp(['fake/gone'])
expect(picked('fake/wide')).toMatchObject({ efforts: [], effortsKnown: false })
})
it('still lists OMP when it cannot start on the picked model', async () => {
const picked = await listOmp(['fake/gone:high'])
expect(levels(picked('fake/wide'))).toEqual([
'off',
'auto',
'minimal',
'low',
'medium',
'high',
'xhigh'
])
})
+56 -160
View File
@@ -1,10 +1,6 @@
import { observeAcpForkSupport } from '../capabilities/acp-fork-support'
import {
assertStructuredAgentResolutionCurrent,
type StructuredAgentResolutionOperation
} from '../../native-chat/structured-agent-command-resolution'
import { assertStructuredAgentResolutionCurrent } from '../../native-chat/structured-agent-command-resolution'
import { homedir } from 'node:os'
import { setTimeout as delay } from 'node:timers/promises'
import { join } from 'node:path'
import type { AgentCliVersionReader } from '../../agent-launch/preflight/agent-cli-version-probe'
import type { AgentModelCatalogProbe } from '../../native-chat/agent-model-catalog/agent-model-catalog-store'
@@ -20,40 +16,22 @@ import { acpRunFolder } from '../launch/acp-private-temp'
import {
acpListingDependsOnRelease,
acpListingNeedsChatFolder,
acpModelListingForRelease,
type AcpSessionModelDiscovery
acpModelListingForRelease
} from './acp-model-discovery-policy'
import type { AcpLaunchSpec } from '../launch/acp-launch-contract'
import type { AcpSessionStarted, AcpSessionStartOptions } from '../protocol/acp-session-setup'
import { checkAcpLaunchVersion } from '../launch/acp-launch-version'
import {
resolveAcpLaunchInvocation,
type AcpLaunchInvocationDeps
} from '../launch/acp-structured-launch-resolution'
import { AcpStructuredOptions } from '../options/acp-structured-options'
import type {
InitializeResponse,
SetSessionConfigOptionResponse
} from '../generated/acp-protocol.generated'
import { withTimeout } from '../../../shared/promise-timeout-fallback'
import { AcpAgentError } from '../transport/acp-errors'
import {
readSessionModels,
type AcpModelCatalogConnection,
type AcpModelCatalogSessionConnection
} from './acp-listing-session-models'
import { AcpAgentError, AcpAgentExitedError } from '../transport/acp-errors'
import { AgentModelCatalogUnavailableError } from '../../native-chat/agent-model-catalog/agent-model-catalog-unavailable'
/** Session-free capability boundary: no session methods are exposed. */
export type AcpModelCatalogConnection = {
initialize(): Promise<InitializeResponse>
requestSessionFreeExtension(method: string, params: unknown): Promise<unknown>
close(): Promise<unknown>
}
export type AcpModelCatalogSessionConnection = Omit<
AcpModelCatalogConnection,
'requestSessionFreeExtension'
> & {
start(options: AcpSessionStartOptions): Promise<AcpSessionStarted>
setConfigOption(configId: string, value: string): Promise<SetSessionConfigOptionResponse>
deleteSession(sessionId: string): Promise<unknown>
}
import { usesModelSpecificAcpEfforts } from '../../../shared/agent-session/options/agent-model-catalog-ownership'
export type AcpModelCatalogProbeDeps = AcpLaunchInvocationDeps & {
probeVersion?: AgentCliVersionReader
@@ -113,6 +91,11 @@ export function createAcpModelCatalogProbe(
envToDelete
}
const run = { label: spec.agent, signal: options?.signal }
// OMP records every model switch as account usage; starting on the picked model records none.
const launchedModel =
spec.launchesWithModel && usesModelSpecificAcpEfforts(spec.agent)
? options?.selectedModels?.[0]
: undefined
let models: AgentSessionModelOption[]
let attemptedModels: string[] | undefined
if (listing.kind === 'command') {
@@ -133,32 +116,49 @@ export function createAcpModelCatalogProbe(
}
// Remove disposable session storage after the process closes.
const folderArgs = listing.sessionFolderArgs
const folder = folderArgs
? await acpRunFolder(join(deps.dataDirectory, 'acp-listing-sessions', spec.agent))
: null
try {
assertStructuredAgentResolutionCurrent(operation)
const args =
folderArgs && folder ? [...launch.args, ...folderArgs(folder.path)] : launch.args
const result = await runAgentModelCatalogSession(
() => (deps.connectSession ?? createAcpAgentConnection)({ ...launch, args }),
(connection, ready) =>
readSessionModels(
spec,
listing,
connection,
workspace,
operation,
options?.selectedModels,
spec.dialect.effortChangesModel ? ready : undefined
),
run
)
models = result.models
attemptedModels = result.attemptedModels
} finally {
await folder?.remove()
const listInSession = async (model: string | undefined) => {
const folder = folderArgs
? await acpRunFolder(join(deps.dataDirectory, 'acp-listing-sessions', spec.agent))
: null
try {
assertStructuredAgentResolutionCurrent(operation)
const args = [
...prefixArgs,
...spec.args({ fullAccess: false, pluginDir: null, model }),
...(folderArgs && folder ? folderArgs(folder.path) : [])
]
return await runAgentModelCatalogSession(
() => (deps.connectSession ?? createAcpAgentConnection)({ ...launch, args }),
(connection, ready) =>
readSessionModels(
spec,
listing,
connection,
workspace,
operation,
options?.selectedModels,
model,
spec.dialect.effortChangesModel ? ready : undefined
),
run
)
} finally {
await folder?.remove()
}
}
let result: Awaited<ReturnType<typeof listInSession>>
try {
result = await listInSession(launchedModel)
} catch (error) {
// OMP exits before ACP on a model it cannot start (a stale `:level` id); list without it.
if (launchedModel === undefined || !(error instanceof AcpAgentExitedError)) {
throw error
}
assertStructuredAgentResolutionCurrent(operation)
result = { ...(await listInSession(undefined)), attemptedModels: [launchedModel] }
}
models = result.models
attemptedModels = result.attemptedModels
} else {
models = await runAgentModelCatalogSession(
() => (deps.connect ?? createAcpAgentConnection)(launch),
@@ -190,107 +190,3 @@ export function createAcpModelCatalogProbe(
const folderlessListing = (spec: AcpLaunchSpec) =>
new AgentModelCatalogListingStoppedError(`${spec.agent} lists in a chat's folder`)
// OpenCode can answer -32603 while its providers are still opening; a later attempt lists them.
async function startListingSession(
connection: AcpModelCatalogSessionConnection,
workspace: string,
operation?: StructuredAgentResolutionOperation
): Promise<AcpSessionStarted> {
for (const backoffMs of [250, 500]) {
try {
return await connection.start({ cwd: workspace, mcpServers: [] })
} catch (error) {
if (!(error instanceof AcpAgentError && error.code === -32603)) {
throw error
}
}
await delay(backoffMs, undefined, { signal: operation?.signal })
assertStructuredAgentResolutionCurrent(operation)
}
return connection.start({ cwd: workspace, mcpServers: [] })
}
async function readSessionModels(
spec: AcpLaunchSpec,
listing: AcpSessionModelDiscovery,
connection: AcpModelCatalogSessionConnection,
workspace: string,
operation?: StructuredAgentResolutionOperation,
selectedModels?: readonly string[],
ready?: (cleanup: () => Promise<unknown>) => void
): Promise<{ models: AgentSessionModelOption[]; attemptedModels: string[] }> {
const initialized = await connection.initialize()
assertStructuredAgentResolutionCurrent(operation)
observeAcpForkSupport(spec.agent, initialized)
const deletes = Boolean(initialized.agentCapabilities?.sessionCapabilities?.delete)
if (!deletes && !listing.sessionFolderArgs) {
throw new Error(`${spec.agent} cannot delete a session, so it lists its models only in chats`)
}
const started = await startListingSession(connection, workspace, operation)
let stopped = false
const cleanup = async (): Promise<void> => {
stopped = true
if (deletes) {
await connection.deleteSession(started.sessionId).catch((error: unknown) => {
console.warn(`[acp-model-catalog] ${spec.agent} kept its listing session:`, error)
})
}
}
// Startup and menu discovery have separate budgets; cleanup also runs on cancellation.
ready?.(cleanup)
const options = new AcpStructuredOptions(spec.dialect)
options.adoptSession(started.response, 'new')
let models = options.read().models
const attemptedModels: string[] = []
try {
if (spec.dialect.effortChangesModel) {
const byId = new Map(models.map((model) => [model.id, model]))
const targets = selectedModels ? selectedModels.flatMap((id) => byId.get(id) ?? []) : models
const sweep = async () => {
for (const model of targets) {
if (stopped) {
return
}
assertStructuredAgentResolutionCurrent(operation)
if (model.effortsKnown !== false) {
continue
}
attemptedModels.push(model.id)
try {
for (let attempt = 0; attempt < 2 && !stopped; attempt++) {
const write = options.write('model', model.id)
if (write?.method !== 'config') {
break
}
const reply = await connection.setConfigOption(write.configId, write.value)
if (stopped) {
return
}
assertStructuredAgentResolutionCurrent(operation)
options.adoptConfigOptions(reply.configOptions)
const observed = options.read()
if (observed.current.model !== model.id) {
continue
}
const known = observed.models.find((row) => row.id === model.id)
if (known) {
models = models.map((row) => (row.id === model.id ? known : row))
}
break
}
} catch {
assertStructuredAgentResolutionCurrent(operation)
}
}
}
await withTimeout(sweep(), 5_000, undefined)
}
assertStructuredAgentResolutionCurrent(operation)
return { models, attemptedModels }
} finally {
if (!ready) {
await cleanup()
}
}
}
@@ -0,0 +1,102 @@
{
"new": {
"configOptions": [
{
"id": "model",
"name": "Model",
"category": "model",
"type": "select",
"currentValue": "fake/wide",
"options": [
{ "value": "fake/wide", "name": "Wide", "description": "fake/wide" },
{ "value": "fake/narrow", "name": "Narrow", "description": "fake/narrow" },
{
"value": "apple/on-device",
"name": "Apple AFM 3 Core Advanced",
"description": "apple/on-device"
}
]
},
{
"id": "thinking",
"name": "Thinking",
"category": "thought_level",
"type": "select",
"currentValue": "high",
"options": [
{ "value": "off", "name": "Off" },
{ "value": "auto", "name": "Auto", "description": "Auto-detect per prompt" },
{ "value": "minimal", "name": "minimal" },
{ "value": "low", "name": "low" },
{ "value": "medium", "name": "medium" },
{ "value": "high", "name": "high" },
{ "value": "xhigh", "name": "xhigh" }
]
}
]
},
"narrow": {
"configOptions": [
{
"id": "model",
"name": "Model",
"category": "model",
"type": "select",
"currentValue": "fake/narrow",
"options": [
{ "value": "fake/wide", "name": "Wide", "description": "fake/wide" },
{ "value": "fake/narrow", "name": "Narrow", "description": "fake/narrow" },
{
"value": "apple/on-device",
"name": "Apple AFM 3 Core Advanced",
"description": "apple/on-device"
}
]
},
{
"id": "thinking",
"name": "Thinking",
"category": "thought_level",
"type": "select",
"currentValue": "high",
"options": [
{ "value": "off", "name": "Off" },
{ "value": "auto", "name": "Auto", "description": "Auto-detect per prompt" },
{ "value": "low", "name": "low" },
{ "value": "high", "name": "high" }
]
}
]
},
"unresolved": {
"configOptions": [
{
"id": "model",
"name": "Model",
"category": "model",
"type": "select",
"currentValue": "fake/wide",
"options": [
{ "value": "fake/wide", "name": "Wide", "description": "fake/wide" },
{ "value": "fake/narrow", "name": "Narrow", "description": "fake/narrow" },
{
"value": "apple/on-device",
"name": "Apple AFM 3 Core Advanced",
"description": "apple/on-device"
}
]
},
{
"id": "thinking",
"name": "Thinking",
"category": "thought_level",
"type": "select",
"currentValue": "off",
"options": [
{ "value": "off", "name": "Off" },
{ "value": "auto", "name": "Auto", "description": "Auto-detect per prompt" }
]
}
]
}
}
@@ -250,10 +250,7 @@ export class AcpStructuredOptions {
model.id === currentModel
? { efforts: sessionEfforts }
: (modelOption || effortOption) && !advertised
? {
efforts: this.dialect.clampsUnlistedEffort ? sessionEfforts : [],
effortsKnown: false as const
}
? { efforts: [], effortsKnown: false as const }
: { efforts: [] }
return {
...model,
@@ -0,0 +1,96 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state'
import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload'
import { AgentHookServer } from '../../../agent-hook-server'
import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures'
const ROOT_ID = '5883db93-32ca-48da-ba29-db952021d273'
const WORKER_ID = 'dc08d047-adfd-4190-a0f4-6c3f7167d394'
describe('Droid mission resume identity', () => {
let dir: string
let server: AgentHookServer
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'orca-droid-server-'))
server = new AgentHookServer()
await server.start({ env: 'production' })
})
afterEach(() => {
server.stop()
rmSync(dir, { recursive: true, force: true })
})
// Droid writes `callingSessionId` on the first transcript record of sub-sessions only.
function transcript(id: string, callingSessionId?: string): string {
const path = join(dir, `${id}.jsonl`)
const start = { type: 'session_start', id, ...(callingSessionId ? { callingSessionId } : {}) }
writeFileSync(path, `${JSON.stringify(start)}\n`)
return path
}
function body(sessionId: string, transcriptPath: string, event: string) {
return buildBody(
{
hook_event_name: event,
session_id: sessionId,
transcript_path: transcriptPath,
tool_name: 'Execute',
prompt: 'run the mission'
},
{ launchToken: 'droid-token' }
)
}
async function post(sessionId: string, transcriptPath: string, event: string) {
expect(
(await postHookEvent(server, body(sessionId, transcriptPath, event), '/hook/droid')).status
).toBe(204)
}
const resumeId = () => server.getStatusSnapshotForPane(PANE)[0]?.providerSession?.id
it('keeps the orchestrator as the resume target while its workers report', async () => {
const rootPath = transcript(ROOT_ID)
const workerPath = transcript(WORKER_ID, ROOT_ID)
await post(WORKER_ID, workerPath, 'PreToolUse')
expect(resumeId()).toBeUndefined()
await post(ROOT_ID, rootPath, 'UserPromptSubmit')
await post(WORKER_ID, workerPath, 'PreToolUse')
await post(WORKER_ID, workerPath, 'Stop')
expect(resumeId()).toBe(ROOT_ID)
// Dismissing the row keeps only the resume identity; the mission is still running.
server.dropStatusEntry(PANE)
await post(WORKER_ID, workerPath, 'PreToolUse')
expect(resumeId()).toBe(ROOT_ID)
})
it('keeps the orchestrator when a restarted relay forwards a worker hook', () => {
// A cold relay has no pane row, so it forwards the worker hook with no session.
const relayed = (sessionId: string, transcriptPath: string) => {
const event = normalizeHookPayload(
createHookListenerState(),
'droid',
body(sessionId, transcriptPath, 'PreToolUse'),
'production'
)
if (!event) {
throw new Error('Missing Droid event')
}
return event
}
server.ingestRemote(relayed(ROOT_ID, transcript(ROOT_ID)), 'host-1')
const worker = relayed(WORKER_ID, transcript(WORKER_ID, ROOT_ID))
expect(worker.providerSession).toBeUndefined()
server.ingestRemote(worker, 'host-1')
expect(resumeId()).toBe(ROOT_ID)
})
})
@@ -8,12 +8,10 @@ async function sshTrustRequest(input: {
worktreeId: string
globalEnabled?: boolean
repoDecision?: AgentWorkspaceTrustDecision
skipForThisLaunch?: boolean
}): Promise<AgentTrustSpawnFields> {
const spawnOptions: AgentTrustSpawnFields = {}
await applyAgentWorkspaceTrustToSpawn({
launchAgent: 'claude',
skipForThisLaunch: input.skipForThisLaunch,
worktreeId: input.worktreeId,
cwd: '/srv/app',
store: {
@@ -56,10 +54,4 @@ describe('agent folder trust follows the repo decision', () => {
})
).toEqual({})
})
it("honours this launch's let-agents-ask answer even when the repo has none stored", async () => {
expect(
await sshTrustRequest({ worktreeId: 'repo-1::/srv/app', skipForThisLaunch: true })
).toEqual({})
})
})
@@ -43,8 +43,6 @@ export function agentWorkspaceTrustDecisionForWorkspace(
export function applyAgentWorkspaceTrustToSpawn(
args: {
launchAgent: unknown
/** The user chose "let agents ask" for this launch; it wins even if saving that answer failed. */
skipForThisLaunch?: boolean
/** Placement workspace id; its root may differ from the agent’s starting folder. */
worktreeId: string | undefined
/** Section root to pre-trust for this launch; never part of the terminal identity. */
@@ -64,7 +62,6 @@ export function applyAgentWorkspaceTrustToSpawn(
const trustWorkspaceId = resolveAgentWorkspaceTrustOwner(args)
if (
!args.isFreshLaunch ||
args.skipForThisLaunch === true ||
!shouldPreTrustAgentWorkspace(
args.settings?.agentWorkspaceTrustEnabled,
agentWorkspaceTrustDecisionForWorkspace(trustWorkspaceId, args.store)
@@ -108,7 +108,8 @@ function readOptions(journal: AgentSessionJournal, agents: StructuredAgentRegist
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => running,
conversation: async () => running
conversation: async () => running,
sessions: new Map([[SESSION, running]])
} as unknown as StructuredAgentSessionMutationContext
return readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true })
}
@@ -41,11 +41,19 @@ export function beginClaudeOptionMutation(session: ClaudeSession, key: string):
return sequence
}
/** Until a turn carries the pick, the running process's answers name the model it replaced. */
export function noteClaudeModelPick(session: ClaudeSession, model: string): void {
session.modelPickAwaitingTurn = model
delete session.reportedOptions.reportedModel
}
/** An init names execution; a control answer only acknowledges its input. */
export function observeClaudeExecutionModel(session: ClaudeSession, model: string): boolean {
const previous = claudeExecutionObservations(session).model
const previousResponse = session.reportedOptions.reportedModel
session.reportedOptions.reportedModel = model
if (!session.modelPickAwaitingTurn) {
session.reportedOptions.reportedModel = model
}
if (previous !== model) {
delete session.appliedOptions
}
@@ -93,7 +101,7 @@ function observeClaudeResponseModel(
: null,
responseModel: response
}) ?? response
if (model === session.reportedOptions.reportedModel) {
if (session.modelPickAwaitingTurn || model === session.reportedOptions.reportedModel) {
return false
}
session.reportedOptions.reportedModel = model
@@ -152,3 +152,50 @@ it('keeps a model picked during a turn over that turn’s later replies until a
await adapter.closeAll()
}
})
it('retires the answered model on a saved pick until a turn carries that pick', async () => {
const claude = fakeClaude({ initModel: 'claude-opus-5-5' })
const adapter = await acquired(claude)
const connection = claude.connections[0]!
const read = async () => (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current
const answer = (uuid: string, model: string) =>
claudeFrame(connection, {
type: 'assistant',
uuid,
message: { role: 'assistant', model, content: [] }
})
const turn = async (clientMessageId: string, model: string) => {
claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' })
await adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: USER_MESSAGE,
executionOptions: { model },
fence: 7
})
}
try {
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' })
answer('fallback', 'claude-opus-4-8')
expect((await read()).reportedModel).toBe('claude-opus-4-8')
adapter.noteOptionPick({ sessionId: 'session-1', fence: 7, key: 'model', value: 'sonnet' })
answer('same-turn', 'claude-opus-4-8')
expect((await read()).reportedModel).toBeUndefined()
expect((await read()).confirmed ?? []).not.toContain('model')
// A message accepted before the pick runs the model it captured.
await turn('queued-before-pick', 'opus')
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' })
answer('queued-answer', 'claude-opus-5-5')
expect((await read()).reportedModel).toBeUndefined()
await turn('carries-pick', 'sonnet')
expect(connection.calls).toContainEqual({ subtype: 'set_model', params: { model: 'sonnet' } })
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-sonnet-5-5' })
answer('next-fallback', 'claude-opus-4-8')
expect((await read()).reportedModel).toBe('claude-opus-4-8')
} finally {
await adapter.closeAll()
}
})
@@ -18,6 +18,7 @@ import { supportsClaudeStructuredLocation } from './launch/claude-structured-loc
import * as claudeOptions from './launch/claude-structured-options'
import { dispatchClaudeMessage } from './launch/claude-structured-message-options'
import { readClaudeStructuredSessionOptions } from './launch/claude-structured-session-options'
import { noteClaudeModelPick } from './claude-structured-execution-observations'
import {
ClaudeAcquisitionRegistry,
type ClaudeSession,
@@ -231,6 +232,12 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda
deps: this.deps,
emit: (session, event) => this.emit(session, event)
})
noteOptionPick: NonNullable<StructuredAgentSessionAdapter['noteOptionPick']> = (input) => {
const session = this.sessions.get(input.sessionId)
if (session?.fence === input.fence && input.key === 'model' && input.value) {
noteClaudeModelPick(session, input.value)
}
}
readOptions = (input: { sessionId: string; fence: number }) =>
readClaudeStructuredSessionOptions(this.session(input.sessionId))
releaseAcquisition = (input: ClaudeReleaseRequest): Promise<boolean> => {
@@ -135,6 +135,8 @@ export type ClaudeSession = {
fastModePerSessionOptIn?: boolean
/** Mutation sequence of the last model report; newer writes outrank it. */
reportedModelMutation: number
/** A saved model pick no turn of this process has carried; its reports predate the pick. */
modelPickAwaitingTurn?: string
/** `dispatchSequence` at the last model write; that turn's replies predate the pick. */
modelMutationDispatch?: number
/** Options whose recorded value the provider reported, not merely accepted. */
@@ -30,6 +30,10 @@ export async function applyClaudeMessageOptions(
): Promise<void> {
throwIfSignalAborted(signal)
const model = options.model
// Only a turn carrying the newest pick reports on it; earlier captured sends run the replaced model.
if (model === session.modelPickAwaitingTurn) {
delete session.modelPickAwaitingTurn
}
if (model && session.appliedInputOptions.get('model') !== model) {
await waitForPromiseWithSignal(
setClaudeStructuredOption(session, { key: 'model', value: model }, timeoutMs),
@@ -213,6 +213,7 @@ export function claudeStructuredSessionOptionsFrom(
const discovered = listedModels(catalog ? { models: catalog } : null)
const listed = discovered.length > 0 ? discovered : seedModels()
const current = readClaudeCurrentModel(session)
const reportsPick = !session.modelPickAwaitingTurn
const model = current.id === 'default' ? undefined : current.id
const models = structuredAgentSessionOptionModels(listed, model, (row) => ({
...row,
@@ -230,7 +231,7 @@ export function claudeStructuredSessionOptionsFrom(
session.reportedOptions.fastMode ??
(session.fastModeState === undefined ? undefined : session.fastModeState !== 'off')
const confirmed = [
...(current.confirmed ? ['model'] : []),
...(current.confirmed && reportsPick ? ['model'] : []),
...(effort && session.confirmedOptions.has('effort') ? ['effort'] : []),
...(fastMode !== undefined &&
(session.confirmedOptions.has('fastMode') || !session.options.has('fastMode'))
@@ -243,7 +244,7 @@ export function claudeStructuredSessionOptionsFrom(
...(changesLive ? {} : { effortFixed: true as const }),
current: {
model,
reportedModel: session.reportedOptions.reportedModel,
reportedModel: reportsPick ? session.reportedOptions.reportedModel : undefined,
reportedPermissionMode: session.reportedOptions.reportedPermissionMode,
...(effort ? { effort } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
@@ -106,4 +106,51 @@ describe('getPRCheckDetails', () => {
vi.useRealTimers()
}
})
it('reads a fine-grained token check from its Actions job when the check run is refused', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
const job = {
id: 71,
run_id: 7,
name: 'pytest',
status: 'completed',
conclusion: 'success',
html_url: 'https://github.com/acme/widgets/actions/runs/7/job/71',
started_at: '2026-11-10T10:00:00Z',
completed_at: '2026-11-10T10:05:00Z',
steps: []
}
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const path = args.at(-1) ?? ''
if (path.includes('/check-runs/71')) {
throw Object.assign(new Error(`Command failed: gh api ${path}`), {
stderr: 'gh: Resource not accessible by personal access token (HTTP 403)\n',
stdout: ''
})
}
if (path.endsWith('/actions/jobs/71')) {
return { stdout: JSON.stringify(job), stderr: '' }
}
if (path.includes('/actions/runs/7/jobs')) {
return { stdout: JSON.stringify({ jobs: [job] }), stderr: '' }
}
throw new Error(`unexpected ${path}`)
})
const details = await getPRCheckDetails('/repo-root', {
checkRunId: 71,
workflowRunId: 7,
checkName: 'pytest'
})
expect(details).toMatchObject({
name: 'pytest',
status: 'completed',
conclusion: 'success',
url: 'https://github.com/acme/widgets/actions/runs/7/job/71',
startedAt: '2026-11-10T10:00:00Z',
completedAt: '2026-11-10T10:05:00Z',
jobs: [{ id: 71, name: 'pytest', status: 'completed', conclusion: 'success' }]
})
})
})
@@ -0,0 +1,131 @@
import { describe, expect, it, vi } from 'vitest'
const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() }))
vi.mock('../../gh-utils', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
ghExecFileAsync: ghExecFileAsyncMock,
acquire: vi.fn(),
release: vi.fn()
}))
vi.mock('../../rate-limit', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
noteRepositoryRateLimitSpend: vi.fn()
}))
vi.mock('../lookup/pr-lookup-rate-limit', () => ({ assertRateLimitBudget: vi.fn() }))
import { getPRChecksViaRestFallback } from './get-pr-checks'
function forbidden(path: string): Error {
return Object.assign(new Error(`Command failed: gh api ${path}`), {
stderr: 'gh: Resource not accessible by personal access token (HTTP 403)\n',
stdout: '{"message":"Resource not accessible by personal access token","status":"403"}'
})
}
function reply(body: unknown): { stdout: string; stderr: string } {
return { stdout: JSON.stringify(body), stderr: '' }
}
describe('PR checks for a token without the Checks permission', () => {
it('lists the head commit Actions jobs when check runs are refused', async () => {
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const path = args.at(-1) ?? ''
if (path.includes('/check-runs') || path.includes('/check-suites')) {
throw forbidden(path)
}
if (path.includes('/actions/runs?head_sha=sha-1&')) {
return reply({
total_count: 2,
workflow_runs: [
{ id: 7, check_suite_id: 70, status: 'completed', conclusion: 'failure' },
{ id: 8, check_suite_id: 80, status: 'completed', conclusion: 'action_required' }
]
})
}
if (path.includes('/actions/runs/8/jobs?filter=latest&')) {
return reply({ total_count: 0, jobs: [] })
}
if (path.includes('/actions/runs/7/jobs?filter=latest&')) {
return reply({
total_count: 2,
jobs: [
{
id: 71,
run_id: 7,
name: 'pytest',
status: 'completed',
conclusion: 'failure',
html_url: 'https://github.com/acme/widgets/actions/runs/7/job/71'
},
{
id: 72,
run_id: 7,
name: 'compose',
status: 'queued',
conclusion: null,
html_url: 'https://github.com/acme/widgets/actions/runs/7/job/72'
}
]
})
}
if (path.includes('/status?')) {
return reply({
total_count: 1,
statuses: [{ context: 'ci/jenkins', state: 'success', target_url: null }]
})
}
throw new Error(`unexpected ${path}`)
})
const checks = await getPRChecksViaRestFallback(
{ owner: 'acme', repo: 'widgets', host: 'github.com' },
'sha-1',
{ cwd: '/repo-root' }
)
expect(
checks?.map(({ name, status, conclusion, url, checkRunId, workflowRunId }) => ({
name,
status,
conclusion,
url,
checkRunId,
workflowRunId
}))
).toEqual([
{
name: 'pytest',
status: 'completed',
conclusion: 'failure',
url: 'https://github.com/acme/widgets/actions/runs/7/job/71',
checkRunId: 71,
workflowRunId: 7
},
{
name: 'compose',
status: 'queued',
conclusion: 'pending',
url: 'https://github.com/acme/widgets/actions/runs/7/job/72',
checkRunId: 72,
workflowRunId: 7
},
{
name: 'ci/jenkins',
status: 'completed',
conclusion: 'success',
url: null,
checkRunId: undefined,
workflowRunId: undefined
},
{
name: 'GitHub Actions #80',
status: 'completed',
conclusion: 'action_required',
url: 'https://github.com/acme/widgets/commits/sha-1/checks#check-suite-80',
checkRunId: undefined,
workflowRunId: undefined
}
])
})
})
@@ -23,6 +23,7 @@ import {
runCheckDetailsCall
} from './check-details-admission-lifetime'
import { snapshotCheckJobLogExecution } from './check-job-log-execution'
import { isCheckRunsPermissionDenied } from './rest-pr-check-pages'
export async function getPRCheckDetails(
repoPath: string,
args: {
@@ -80,11 +81,20 @@ export async function getPRCheckDetails(
let checkRun: Record<string, unknown> | null = null
let output: Record<string, unknown> | null = null
let annotations: PRCheckRunDetails['annotations'] = []
let checkRunReadRefused = false
if (args.checkRunId) {
const { stdout } = await fetchMetadata([
'api',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/check-runs/${args.checkRunId}`
])
const checkRunPath = `repos/${ownerRepo.owner}/${ownerRepo.repo}/check-runs/${args.checkRunId}`
const { stdout } = await fetchMetadata(['api', checkRunPath]).catch((err: unknown) => {
if (!isCheckRunsPermissionDenied(err)) {
throw err
}
// Why: fine-grained tokens can't read check runs, but a job's id is its check run's id.
checkRunReadRefused = true
return fetchMetadata([
'api',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/actions/jobs/${args.checkRunId}`
])
})
const parsed: unknown = JSON.parse(stdout)
checkRun =
parsed && typeof parsed === 'object' && !Array.isArray(parsed)
@@ -94,7 +104,10 @@ export async function getPRCheckDetails(
checkRun?.output && typeof checkRun.output === 'object'
? Object.fromEntries(Object.entries(checkRun.output))
: null
if (checkRun?.status !== 'completed' || output?.annotations_count !== 0) {
if (
!checkRunReadRefused &&
(checkRun?.status !== 'completed' || output?.annotations_count !== 0)
) {
try {
const annotationsResult = await fetchMetadata([
'api',
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { extractExecError } from '../../../git/exec-error'
import { ghExecFileAsync } from '../../gh-utils'
import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
@@ -24,6 +25,12 @@ const commitStatusSchema = z.object({
target_url: z.string().nullish(),
created_at: z.string().nullish()
})
const workflowRunSchema = z.object({
id: z.number(),
check_suite_id: z.number().nullish(),
status: z.string().nullable(),
conclusion: z.string().nullable()
})
const checkSuiteSchema = z.object({
id: z.number().optional(),
status: z.string().nullable(),
@@ -33,7 +40,6 @@ const checkSuiteSchema = z.object({
async function readPages<T>(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
endpoint: string,
field: string,
@@ -48,7 +54,8 @@ async function readPages<T>(
let total: number | undefined
for (let page = 1; ; page++) {
await assertRateLimitBudget('core', repository, options)
const path = `repos/${repository.owner}/${repository.repo}/commits/${encodeURIComponent(headSha)}/${endpoint}?per_page=100&page=${page}`
const separator = endpoint.includes('?') ? '&' : '?'
const path = `repos/${repository.owner}/${repository.repo}/${endpoint}${separator}per_page=100&page=${page}`
const { stdout } = await ghExecFileAsync(
['api', ...(noCache ? [] : ['--cache', '60s']), path],
{ ...options, ...githubHostExecOptions(repository) }
@@ -74,23 +81,89 @@ async function readPages<T>(
}
}
export function readRestPRCheckRuns(
function commitEndpoint(headSha: string, endpoint: string): string {
return `commits/${encodeURIComponent(headSha)}/${endpoint}`
}
// Why: fine-grained tokens cannot be granted the Checks permission, but can read Actions.
export function isCheckRunsPermissionDenied(err: unknown): boolean {
const { stderr, stdout } = extractExecError(err)
const message = `${stderr}\n${stdout}\n${err instanceof Error ? err.message : ''}`
return message.toLowerCase().includes('resource not accessible by personal access token')
}
function readHeadWorkflowRuns(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache: boolean,
pageLimit?: number
) {
return readPages(
repository,
options,
`actions/runs?head_sha=${encodeURIComponent(headSha)}`,
'workflow_runs',
workflowRunSchema,
noCache,
pageLimit
)
}
/** The head commit's Actions jobs as check runs; a job's id is its check run's id. */
async function readActionsJobsAsCheckRuns(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache: boolean,
pageLimit?: number
): Promise<z.infer<typeof checkRunSchema>[]> {
const runs = await readHeadWorkflowRuns(repository, headSha, options, noCache, pageLimit)
const checkRuns: z.infer<typeof checkRunSchema>[] = []
for (const run of runs) {
const jobs = await readPages(
repository,
options,
`actions/runs/${run.id}/jobs?filter=latest`,
'jobs',
checkRunSchema,
noCache,
pageLimit
)
for (const job of jobs) {
checkRuns.push({
...job,
details_url: job.html_url,
check_suite: run.check_suite_id ? { id: run.check_suite_id } : null
})
}
}
return checkRuns
}
export async function readRestPRCheckRuns(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache = true,
pageLimit?: number
) {
return readPages(
repository,
headSha,
options,
'check-runs',
'check_runs',
checkRunSchema,
noCache,
pageLimit
)
try {
return await readPages(
repository,
options,
commitEndpoint(headSha, 'check-runs'),
'check_runs',
checkRunSchema,
noCache,
pageLimit
)
} catch (err) {
if (!isCheckRunsPermissionDenied(err)) {
throw err
}
return readActionsJobsAsCheckRuns(repository, headSha, options, noCache, pageLimit)
}
}
export function readRestPRCommitStatuses(
@@ -102,9 +175,8 @@ export function readRestPRCommitStatuses(
) {
return readPages(
repository,
headSha,
options,
'status',
commitEndpoint(headSha, 'status'),
'statuses',
commitStatusSchema,
noCache,
@@ -112,23 +184,36 @@ export function readRestPRCommitStatuses(
)
}
export function readRestPRCheckSuites(
export async function readRestPRCheckSuites(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache = true,
pageLimit?: number
) {
return readPages(
repository,
headSha,
options,
'check-suites',
'check_suites',
checkSuiteSchema,
noCache,
pageLimit
)
): Promise<z.infer<typeof checkSuiteSchema>[]> {
try {
return await readPages(
repository,
options,
commitEndpoint(headSha, 'check-suites'),
'check_suites',
checkSuiteSchema,
noCache,
pageLimit
)
} catch (err) {
if (!isCheckRunsPermissionDenied(err)) {
throw err
}
// Each workflow run is its own check suite, so approval blockers still surface.
const runs = await readHeadWorkflowRuns(repository, headSha, options, noCache, pageLimit)
return runs.map((run) => ({
id: run.check_suite_id ?? undefined,
status: run.status,
conclusion: run.conclusion,
app: { name: 'GitHub Actions' }
}))
}
}
/** REST rows in the GraphQL rollup's field names, so both reads give a check the same identity. */
@@ -0,0 +1,114 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import {
closeTestStores,
createStore,
makeRepo,
testState,
writeDataFile
} from '../persistence/persistence-test-harness'
import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments'
import { hostWorktreeTarget } from '../../shared/worktree/host-qualified-identity'
import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill'
vi.mock('electron', () => ({
app: { getPath: () => testState.dir },
safeStorage: { isEncryptionAvailable: () => false }
}))
vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() }))
const target = hostWorktreeTarget({ id: 'repo::/work', hostId: 'local' })
async function setup(readIssueTitle: () => Promise<string | null>) {
writeDataFile({ repos: [makeRepo({ id: 'repo', path: '/work' })] })
const store = await createStore()
const pending: (() => void)[] = []
const publish = vi.fn()
installGitHubIssueLinkTitleFill({
store,
readIssueTitle,
publish,
schedule: (run) => pending.push(run)
})
const settle = async (): Promise<void> => {
for (const run of pending.splice(0)) {
run()
}
await vi.waitFor(() => expect(readIssueTitle).toHaveBeenCalled())
await new Promise((resolve) => setImmediate(resolve))
}
return { store, settle, publish }
}
describe('GitHub issue link title fill', () => {
beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-issue-link-title-'))
})
afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('titles a bare linked issue without re-selecting a review the user had cleared', async () => {
const { store, settle, publish } = await setup(vi.fn(async () => 'Repair authentication'))
// A kept merge request with no review selected, as after the user clears the selection.
store.setWorktreeMeta(target, {
linkedItems: [{ provider: 'gitlab', type: 'mr', number: 5 }],
linkedPR: null,
linkedGitLabMR: null,
linkedBitbucketPR: null,
linkedAzureDevOpsPR: null,
linkedGiteaPR: null
})
store.setWorktreeMeta(target, { linkedIssue: 42 })
expect(store.getWorktreeMetaForHost('repo::/work', 'local')?.linkedGitLabMR ?? null).toBeNull()
await settle()
const meta = store.getWorktreeMetaForHost('repo::/work', 'local')
expect(getWorkspaceAttachments(meta)).toContainEqual(
expect.objectContaining({
provider: 'github',
type: 'issue',
number: 42,
title: 'Repair authentication'
})
)
expect(meta?.linkedIssue).toBe(42)
expect(meta?.linkedGitLabMR ?? null).toBeNull()
expect(publish).toHaveBeenCalledWith(
expect.objectContaining({ worktreeId: 'repo::/work', hostId: 'local' })
)
})
it('keeps a hidden branch PR hidden when titling a link beside the selected PR', async () => {
const { store, settle } = await setup(vi.fn(async () => 'Repair authentication'))
store.setWorktreeMeta(target, { linkedPR: 7 })
store.setWorktreeMeta(target, { suppressedGitHubPR: 7 })
store.setWorktreeMeta(target, { linkedIssue: 42 })
await settle()
const meta = store.getWorktreeMetaForHost('repo::/work', 'local')
expect(getWorkspaceAttachments(meta)).toContainEqual(
expect.objectContaining({ type: 'issue', number: 42, title: 'Repair authentication' })
)
expect(meta?.suppressedGitHubPR).toBe(7)
})
it('does not bring back a link removed while its title was being read', async () => {
let finish: (title: string) => void = () => {}
const read = vi.fn(() => new Promise<string | null>((resolve) => (finish = resolve)))
const { store, settle } = await setup(read)
store.setWorktreeMeta(target, { linkedIssue: 42 })
const settled = settle()
await vi.waitFor(() => expect(read).toHaveBeenCalled())
store.setWorktreeMeta(target, { linkedIssue: null })
finish('Repair authentication')
await settled
const links = getWorkspaceAttachments(store.getWorktreeMetaForHost('repo::/work', 'local'))
expect(links.filter((item) => item.provider === 'github' && item.type === 'issue')).toEqual([])
})
})
@@ -0,0 +1,166 @@
import type { ExecutionHostId } from '../../shared/execution-host'
import type { Repo } from '../../shared/repo-types'
import type { WorktreeMeta } from '../../shared/worktree/meta-types'
import type { WorkspaceAttachment } from '../../shared/worktree/types'
import type { WorkspaceAttachmentMutation } from '../../shared/workspace-attachments/workspace-attachment-mutation'
import { getWorkspaceAttachments } from '../../shared/workspace-attachments/workspace-attachments'
import { WORKSPACE_ATTACHMENT_NUMBER_SLOTS } from '../../shared/workspace-attachments/workspace-attachment-legacy'
import { getWorkspaceReferenceIdentity } from '../../shared/workspace-attachments/workspace-reference-identity'
import {
hostWorktreeTarget,
type HostWorktreeTarget
} from '../../shared/worktree/host-qualified-identity'
import { getRepoIdFromWorktreeId } from '../../shared/worktree/id'
import type { WorktreeMetaWriteListener } from '../persistence/loading-store/write-scheduling'
import { findRepoRowForHostScopedWrite } from '../persistence/tracking-repos/repo-update-operations'
export type GitHubIssueLinkTitleFillStore = {
onWorktreeMetaWritten: (listener: WorktreeMetaWriteListener) => () => void
getWorktreeMetaForHost: (worktreeId: string, hostId: ExecutionHostId) => WorktreeMeta | undefined
setWorktreeMeta: (
target: HostWorktreeTarget,
meta: Partial<WorktreeMeta> & WorkspaceAttachmentMutation
) => WorktreeMeta
getRepos: () => Repo[]
}
type Job = {
worktreeId: string
hostId: ExecutionHostId
instanceId: string | undefined
identity: string
link: WorkspaceAttachment
}
function untitledGitHubIssues(meta: WorktreeMeta | undefined): WorkspaceAttachment[] {
return getWorkspaceAttachments(meta).filter(
(item) => item.provider === 'github' && item.type === 'issue' && !item.title?.trim()
)
}
/**
* Links made without a title (CLI `--issue N`, phones, typed numbers) get the issue's title once, on the
* host that owns the workspace, so search can match it without a client re-reading every linked issue.
*/
export function installGitHubIssueLinkTitleFill(deps: {
store: GitHubIssueLinkTitleFillStore
readIssueTitle: (repo: Repo, link: WorkspaceAttachment) => Promise<string | null>
// Addressed to the one workspace whose links changed; never a repo-wide refresh.
publish: (change: { worktreeId: string; hostId: ExecutionHostId; meta: WorktreeMeta }) => void
schedule?: (run: () => void) => void
}): () => void {
const schedule = deps.schedule ?? ((run) => setImmediate(run))
const queue = new Map<string, Job>()
let draining = false
let disposed = false
// The job's link as it is now; null once removed, retitled or its workspace re-created.
const currentTarget = (job: Job) => {
const meta = deps.store.getWorktreeMetaForHost(job.worktreeId, job.hostId)
if (!meta || meta.instanceId !== job.instanceId) {
return null
}
const items = getWorkspaceAttachments(meta)
const index = items.findIndex(
(item) => getWorkspaceReferenceIdentity(item) === job.identity && !item.title?.trim()
)
return index === -1 ? null : { meta, items, index }
}
const apply = (job: Job, title: string): void => {
const target = currentTarget(job)
if (!target) {
return
}
const { meta, items, index } = target
const reviewSlots = WORKSPACE_ATTACHMENT_NUMBER_SLOTS.filter(([, , type]) => type !== 'issue')
// A cleared review selection must be restated or the merge re-picks one; a set one it keeps.
const keepClearedSelection = reviewSlots.every(([slot]) => (meta[slot] ?? null) === null)
? Object.fromEntries(reviewSlots.map(([slot]) => [slot, null]))
: {}
const updated = deps.store.setWorktreeMeta(
hostWorktreeTarget({ id: job.worktreeId, hostId: job.hostId }),
{
...keepClearedSelection,
linkedItemsBase: items,
linkedItems: items.map((item, i) => (i === index ? { ...item, title } : item))
}
)
deps.publish({ worktreeId: job.worktreeId, hostId: job.hostId, meta: updated })
}
const drain = async (): Promise<void> => {
if (draining) {
return
}
draining = true
try {
for (const [key, job] of queue) {
queue.delete(key)
if (disposed) {
return
}
try {
const repo = currentTarget(job)
? findRepoRowForHostScopedWrite(
deps.store.getRepos(),
getRepoIdFromWorktreeId(job.worktreeId),
job.hostId
)
: undefined
const title = repo ? await deps.readIssueTitle(repo, job.link).catch(() => null) : null
if (title?.trim() && !disposed) {
apply(job, title.trim())
}
} catch {
// One link whose target changed underneath it (e.g. an alias turned ambiguous) is skipped;
// the rest of the queue still drains.
}
}
} finally {
draining = false
}
}
const unsubscribe = deps.store.onWorktreeMetaWritten(({ worktreeId, hostId, previous, next }) => {
// Most writes (stamps, flags, comments) leave links untouched; skip them without normalizing.
// linkedWorkItem is re-created on every write and always titled, so it is not compared.
if (
previous &&
previous.instanceId === next.instanceId &&
previous.linkedItems === next.linkedItems &&
previous.linkedIssue === next.linkedIssue
) {
return
}
const known = new Set(
previous?.instanceId === next.instanceId
? untitledGitHubIssues(previous).map(getWorkspaceReferenceIdentity)
: []
)
let added = false
for (const link of untitledGitHubIssues(next)) {
const identity = getWorkspaceReferenceIdentity(link)
if (known.has(identity)) {
continue
}
queue.set(JSON.stringify([hostId, worktreeId, next.instanceId, identity]), {
worktreeId,
hostId,
instanceId: next.instanceId,
identity,
link
})
added = true
}
if (added) {
// Run after the caller's write returns; nothing the user asked for waits on GitHub.
schedule(() => void drain())
}
})
return () => {
disposed = true
queue.clear()
unsubscribe()
}
}
@@ -0,0 +1,103 @@
import type { Repo } from '../../shared/repo-types'
import { composeWorktreeHostIdentity } from '../../shared/worktree/host-qualified-identity'
import { getRepoIdFromWorktreeId } from '../../shared/worktree/id'
import {
workspaceMetadataSetRow,
type WorkspaceMetadataSet
} from '../../shared/worktree/workspace-metadata-set'
import type { WorkspaceAttachment } from '../../shared/worktree/types'
import { getRepoRoutingConnectionId } from '../../shared/execution-host'
import type { Store } from '../persistence/loading-store/store'
import { getLocalProjectGhExecOptions } from '../workspaces/execution-host/project-runtime-git-options'
import { getIssue } from './issues'
import { getWorkItemByOwnerRepo } from './client/fetch/get-work-item'
import { installGitHubIssueLinkTitleFill } from './github-issue-link-title-fill'
import { readGitHubRepoUnlessWslStopped } from '../ipc/source-control/github-repo-routing'
const GITHUB_ISSUE_PATH = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)$/
function sameIssueUrl(left: string, right: string): boolean {
try {
const a = new URL(left)
const b = new URL(right)
return (
a.hostname.toLowerCase() === b.hostname.toLowerCase() &&
a.pathname.replace(/\/+$/, '').toLowerCase() === b.pathname.replace(/\/+$/, '').toLowerCase()
)
} catch {
return false
}
}
/** Reads a link's issue the way its display does: a URL names its repo; a bare number uses the card's lookup. */
async function readGitHubIssueLinkTitle(
store: Store,
repo: Repo,
link: WorkspaceAttachment
): Promise<string | null> {
const connectionId = getRepoRoutingConnectionId(repo)
const options = getLocalProjectGhExecOptions(store, repo)
if (link.url) {
const url = new URL(link.url)
const route = GITHUB_ISSUE_PATH.exec(url.pathname)
if (!route || Number(route[3]) !== link.number) {
return null
}
const item = await getWorkItemByOwnerRepo(
repo.path,
{ owner: route[1], repo: route[2], host: url.hostname },
link.number,
'issue',
connectionId,
options,
{ preview: true }
)
return item?.type === 'issue' && item.number === link.number && sameIssueUrl(item.url, link.url)
? item.title
: null
}
const issue = await getIssue(repo.path, link.number, connectionId, options)
// The issues endpoint also answers PR numbers; a PR's title must not label an issue link.
return issue && issue.number === link.number && !/\/pull\/\d+$/.test(issue.url)
? issue.title
: null
}
export function wireGitHubIssueLinkTitleFill(
store: Store,
runtime: {
invalidateResolvedWorktreeCache: () => void
publishWorkspaceMetadataSet: (set: WorkspaceMetadataSet) => void
}
): () => void {
return installGitHubIssueLinkTitleFill({
store,
// Background reads never start a stopped WSL distro; the link just stays untitled.
readIssueTitle: (repo, link) =>
readGitHubRepoUnlessWslStopped(
store,
repo,
() => readGitHubIssueLinkTitle(store, repo, link),
{
wake: false
}
),
publish: ({ worktreeId, hostId, meta }) => {
// Resolved rows embed metadata; refresh them so the next listing read agrees.
runtime.invalidateResolvedWorktreeCache()
// Same turn as the title write, so a listing either read it or carries an older seq.
const { epoch, seq } = store.advanceWorkspaceMetadataCursor()
runtime.publishWorkspaceMetadataSet({
kind: 'set',
domain: 'workspaceMetadata',
hostId,
epoch,
seq,
id: composeWorktreeHostIdentity(hostId, worktreeId),
repoId: getRepoIdFromWorktreeId(worktreeId),
worktreeId,
row: workspaceMetadataSetRow(meta)
})
}
})
}
-2
View File
@@ -65,8 +65,6 @@ export type PtySpawnIpcArgs = {
spawnIntent?: unknown
// Only `true` counts: a window restore no user act asked for.
wslPassiveRestore?: unknown
// Only `true` counts: the user just chose to let agents ask, even if saving that answer failed.
skipAgentWorkspaceTrust?: unknown
// Validate untyped launch input through AgentLaunch.safeParse.
agentLaunch?: unknown
// Main validates renderer telemetry; retain unknown input types at the IPC boundary.
@@ -93,7 +93,6 @@ export type PtySpawnLaunchOptionsInput = {
connectionId?: string | null
shellOverride?: string
telemetry?: { agent_kind?: unknown }
skipAgentWorkspaceTrust?: unknown
}
env: Record<string, string> | undefined
/** Mutated: OpenCode prep may add the keys its launch must drop. */
@@ -210,7 +209,6 @@ export async function assemblePtySpawnLaunchOptions(input: PtySpawnLaunchOptions
launchAgent: args.launchAgent,
worktreeId: args.worktreeId,
trustWorktreeId: args.trustWorktreeId,
skipForThisLaunch: args.skipAgentWorkspaceTrust === true,
cwd: input.cwd,
store: input.store,
isFreshLaunch: !input.preAdoptedStablePane && launchCommand !== undefined,
@@ -18,6 +18,7 @@ export function registerWorkspaceSpaceWindowHandlers(store: Store): void {
'workspaceSpace:requestWindowState',
'workspaceSpace:revealWorktree',
'workspaceSpace:requestWorktreeRefresh',
'workspaceSpace:requestIssueRefresh',
'workspaceSpace:publishWindowAnalysis'
]) {
ipcMain.removeHandler(channel)
@@ -72,6 +73,27 @@ export function registerWorkspaceSpaceWindowHandlers(store: Store): void {
getTrustedUIRendererWebContents()?.send('workspaceSpace:worktreeRefreshRequested')
}
})
// Why: the main window owns issueCache and publishes it to the Space window; Space asks rather than writing its own copy.
ipcMain.handle(
'workspaceSpace:requestIssueRefresh',
(event, worktreeId: unknown, hostId: unknown): void => {
if (!isWorkspaceSpaceWindowRenderer(event.sender) || typeof worktreeId !== 'string') {
return
}
if (hostId !== undefined && typeof hostId !== 'string') {
return
}
const executionHostId = normalizeExecutionHostId(hostId)
if (hostId !== undefined && executionHostId === null) {
return
}
getTrustedUIRendererWebContents()?.send(
'workspaceSpace:issueRefreshRequested',
worktreeId,
executionHostId ?? undefined
)
}
)
ipcMain.handle('workspaceSpace:publishWindowAnalysis', (event, analysis: unknown): void => {
if (isWorkspaceSpaceWindowRenderer(event.sender) && analysis && typeof analysis === 'object') {
getTrustedUIRendererWebContents()?.send('workspaceSpace:windowAnalysis', analysis)
@@ -41,7 +41,7 @@ const localRepo: Repo = {
addedAt: 0
}
function createStore(repo: Repo) {
function createStore(repo: Repo, cursor?: { epoch: string; seq: number }) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the listing reads only these store methods; the pruning that would need more is mocked above.
return {
getRepo: () => repo,
@@ -55,7 +55,8 @@ function createStore(repo: Repo) {
getAllWorktreeLineage: () => ({}),
getAllWorkspaceLineage: () => ({}),
removeWorktreeLineage: vi.fn(),
captureNativeLocalWorktreeMetadataScanExpectation: () => undefined
captureNativeLocalWorktreeMetadataScanExpectation: () => undefined,
...(cursor ? { getWorkspaceMetadataCursor: () => ({ ...cursor }) } : {})
} as never
}
@@ -106,4 +107,26 @@ describe('the catalog version a listing carries', () => {
first && 'catalogVersion' in first ? first.catalogVersion : undefined
)
})
it('carries the metadata cursor it read with its metadata, not one advanced during the scan', async () => {
const cursor = { epoch: 'e1', seq: 4 }
// A title write lands while the scan is still running.
listRepoWorktreesMock.mockImplementation(async () => {
cursor.seq = 5
return [worktreeAt(localRepo, localRepo.path)]
})
const store = createStore(localRepo, cursor)
const during = await listDetectedWorktreesForCapturedRepo(store, localRepo, () => true)
const after = await listDetectedWorktreesForCapturedRepo(store, localRepo, () => true)
expect(during && 'workspaceMetadata' in during ? during.workspaceMetadata : null).toEqual({
epoch: 'e1',
seq: 4
})
expect(after && 'workspaceMetadata' in after ? after.workspaceMetadata : null).toEqual({
epoch: 'e1',
seq: 5
})
})
})
@@ -46,6 +46,13 @@ import {
wslDistroNotRunningForScanFailure
} from './wsl-stopped-worktree-listing'
// Partial stores (tests, embedders) may not publish workspace metadata; their listings carry no stamp.
function readWorkspaceMetadataCursor(store: {
getWorkspaceMetadataCursor?: () => { epoch: string; seq: number }
}): { epoch: string; seq: number } | undefined {
return store.getWorkspaceMetadataCursor?.()
}
export async function listDetectedWorktreesForCapturedRepo(
store: Store,
repo: Repo,
@@ -59,6 +66,8 @@ export async function listDetectedWorktreesForCapturedRepo(
? ({ providerAbortStatus: providerAbort.status() } as const)
: undefined
const allMeta = isFolderRepo(repo) ? undefined : readAllWorktreeMetaForRepo(store, repo)
// Read with the metadata, so clients can tell which published metadata records this listing includes.
const workspaceMetadata = readWorkspaceMetadataCursor(store)
try {
// Folder rows are read synchronously, leaving no mutation window that needs a re-scan.
@@ -75,7 +84,8 @@ export async function listDetectedWorktreesForCapturedRepo(
authoritative: false,
source: 'metadata-fallback',
worktrees: [],
catalogVersion: getLocalWorktreeCatalogVersion(repo.id)
catalogVersion: getLocalWorktreeCatalogVersion(repo.id),
...(workspaceMetadata ? { workspaceMetadata } : {})
}
}
return {
@@ -83,6 +93,7 @@ export async function listDetectedWorktreesForCapturedRepo(
authoritative: true,
source: 'git',
catalogVersion: getLocalWorktreeCatalogVersion(repo.id),
...(workspaceMetadata ? { workspaceMetadata } : {}),
worktrees: projectWorktreeLineageWithHostPeers(
store,
repo,
@@ -108,7 +119,8 @@ export async function listDetectedWorktreesForCapturedRepo(
authoritative: false,
source: 'metadata-fallback',
worktrees: buildDisconnectedDetectedWorktrees(store, repo, worktrees),
catalogVersion: getLocalWorktreeCatalogVersion(repo.id)
catalogVersion: getLocalWorktreeCatalogVersion(repo.id),
...(workspaceMetadata ? { workspaceMetadata } : {})
}
}
const pendingAtScan = snapshotPendingWorktreeRemovals()
@@ -140,7 +152,8 @@ export async function listDetectedWorktreesForCapturedRepo(
authoritative: false,
source: 'metadata-fallback',
worktrees: [],
catalogVersion: localWorktreeCatalogVersionAt(scan.generation)
catalogVersion: localWorktreeCatalogVersionAt(scan.generation),
...(workspaceMetadata ? { workspaceMetadata } : {})
}
}
if (freshScan) {
@@ -166,6 +179,7 @@ export async function listDetectedWorktreesForCapturedRepo(
authoritative: true,
source: 'git',
catalogVersion: localWorktreeCatalogVersionAt(scan.generation),
...(workspaceMetadata ? { workspaceMetadata } : {}),
worktrees: projectPendingWorktreeRemovals(
buildDetectedGitWorktrees(store, repo, localRows, allMeta),
(worktree) => worktree.id,
@@ -196,7 +210,8 @@ export async function listDetectedWorktreesForCapturedRepo(
unavailableReason,
failureKind,
wslDistroStopped,
catalogVersion: getLocalWorktreeCatalogVersion(repo.id)
catalogVersion: getLocalWorktreeCatalogVersion(repo.id),
...(workspaceMetadata ? { workspaceMetadata } : {})
}
}
warnOnce(
@@ -212,7 +227,8 @@ export async function listDetectedWorktreesForCapturedRepo(
worktrees: [],
unavailableReason,
failureKind,
catalogVersion: getLocalWorktreeCatalogVersion(repo.id)
catalogVersion: getLocalWorktreeCatalogVersion(repo.id),
...(workspaceMetadata ? { workspaceMetadata } : {})
}
}
}
@@ -0,0 +1,50 @@
import { expect, it, onTestFinished, vi } from 'vitest'
import { createAgentModelCatalogService } from './agent-model-catalog-service'
import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store'
it("reports a picked OMP model's menu discovery as a listing in progress", async () => {
const listings: PromiseWithResolvers<AgentModelCatalogSuccess>[] = []
const probe = vi.fn((_home: unknown, _options?: { selectedModels?: readonly string[] }) => {
const listing = Promise.withResolvers<AgentModelCatalogSuccess>()
listings.push(listing)
return listing.promise
})
const service = createAgentModelCatalogService({
store: new AgentModelCatalogStore(),
getConversation: () => undefined,
getRecord: () => undefined,
drivesRecord: () => true,
resolveAccountHome: async () => ({ variable: 'PI_CODING_AGENT_DIR', path: '/account' }),
probes: { omp: probe }
})
onTestFinished(() => {
for (const listing of listings) {
listing.resolve({ origin: 'probe', models: [] })
}
return service.stop()
})
const params = { agent: 'omp', workspacePath: '/work' }
void service.demand(params)
await vi.waitFor(() => expect(probe).toHaveBeenCalledOnce())
listings[0]!.resolve({
origin: 'probe',
models: [
{ id: 'wide', label: 'Wide', isDefault: false, efforts: [{ value: 'high', label: 'high' }] },
{ id: 'narrow', label: 'Narrow', isDefault: false, efforts: [], effortsKnown: false }
]
})
await vi.waitFor(async () =>
expect((await service.read(params)).listingInProgress).toBeUndefined()
)
// The picker reads once, as the RPC does, and waits for the listing only if told one runs.
const picked = { ...params, selectedModel: 'narrow' }
void service.demand(picked)
expect(await service.read(picked)).toMatchObject({ listingInProgress: true })
await vi.waitFor(() =>
expect(probe).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ selectedModels: ['narrow'] })
)
)
})
@@ -74,14 +74,16 @@ describe('a model whose newer chat listing does not know its efforts', () => {
expect(merged).not.toHaveProperty('defaultEffort')
})
it('keeps native suggestions unknown without a known model menu', () => {
it('drops an OMP menu an older build borrowed from the running model', () => {
const saved = unknownChat(1, menu('low', 'medium', 'max'))
expect(agentModelCatalogEntry('omp', 'fp', saved, null, null)?.models[0]).toMatchObject({
efforts: [],
effortsKnown: false
})
})
it('keeps an older unknown menu when the newer listing has none', () => {
const older = unknownChat(1, menu('low', 'high'))
const newer = unknownChat(2, menu('off', 'auto'))
for (const discovered of [null, { ...older, origin: 'probe' as const }]) {
const merged = agentModelCatalogEntry('omp', 'fp', discovered, newer, null)?.models[0]
expect(merged).toMatchObject({ efforts: menu('off', 'auto'), effortsKnown: false })
expect(merged).not.toHaveProperty('defaultEffort')
}
expect(model({ ...older, origin: 'probe' }, unknownChat(2))).toMatchObject({
efforts: menu('low', 'high'),
effortsKnown: false
@@ -28,7 +28,7 @@ export function mergedAgentModelCatalogModels(
// Coarser probe menus must not discard a chat-confirmed effort unless a newer chat menu does.
const keepsChatMenu =
older === live && !offersConfigured(model.efforts) && offersConfigured(olderEfforts)
const { efforts, effortsKnown } = modelSpecificEfforts
const { efforts: keptEfforts, effortsKnown } = modelSpecificEfforts
? model.effortsKnown === false && olderModel
? olderModel
: model
@@ -39,6 +39,8 @@ export function mergedAgentModelCatalogModels(
: model.efforts.length > 0 && !keepsChatMenu
? model
: (olderModel ?? model)
// An unobserved per-model menu is another model's; older builds saved such copies.
const efforts = modelSpecificEfforts && effortsKnown === false ? [] : keptEfforts
const defaultEffort = [configuredEffort, listed?.defaultEffort, reported?.defaultEffort].find(
(effort) => effort !== undefined && efforts.some((choice) => choice.value === effort)
)
@@ -239,7 +239,10 @@ export function projectAgentModelCatalogSnapshot(
...(!params.savedOnly &&
!params.verifiedOnly &&
(deps.store.isListing(bound.fingerprint) ||
(resolving && deps.store.probeDue(bound.fingerprint))) &&
(resolving &&
(deps.store.probeDue(bound.fingerprint) ||
// The picked model's menu is listed by the refresh this read just asked for.
deps.store.efforts.due(bound.fingerprint, params.selectedModel)))) &&
(independent || !listed || usesModelSpecificAcpEfforts(params.agent))
? { listingInProgress: true as const }
: {}),
@@ -106,7 +106,8 @@ export function piOptionRefreshHost(sessionId = 'session-1') {
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => conversation,
conversation: async () => conversation
conversation: async () => conversation,
sessions: new Map([[sessionId, conversation]])
} as unknown as StructuredAgentSessionMutationContext
return readStructuredAgentSessionOptions(context, sessionId, { readsWithoutModel: true })
},
@@ -0,0 +1,182 @@
import { expect, it } from 'vitest'
import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire'
import type { StructuredAgentSessionMutationContext } from '../../operations/structured-agent-session-mutation-context'
import type {
StructuredAgentSessionHostSession,
StructuredAgentSessionProviderChild
} from '../structured-agent-session-host-types'
import { readStructuredAgentSessionOptions } from '../../options/structured-agent-session-options-read'
import { noteStructuredAgentSessionOptionPick } from '../../options/structured-agent-session-option-intent'
import {
hostTestCatalogReadOperation,
hostTestOptionsReadStore,
hostTestRestingOptionsJournal,
hostTestRestingOptionsRecord,
HOST_TEST_NOW as NOW,
HOST_TEST_SESSION as SESSION,
hostTestOperationId
} from './structured-agent-session-host-test-data'
import {
createQueuedMessageTestRig,
QUEUED_RIG_CALLER
} from './structured-agent-session-queued-message-rig.test-fixture'
import { appendUsageLimitedTurn } from './structured-agent-session-rewind-usage-limit.test-fixture'
const RESPONSE_REPORT = { model: 'opus[1m]', reportedModel: 'claude-opus-4-8' }
// Claude's confirmed init model stands in for a report when no response named one.
const CONFIRMED_INIT = { model: 'opus[1m]', confirmed: ['model'] }
function claudeOptionsRead(answer: Record<string, unknown> = RESPONSE_REPORT) {
const record = {
...hostTestRestingOptionsRecord('session-1'),
provider: 'claude',
options: { model: 'opus[1m]' }
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the reader and pick counter use only the child's identity, fence and phase.
const child = { fence: 2, phase: 'ready' } as unknown as StructuredAgentSessionProviderChild
const conversation = {
child,
params: { provider: 'claude' },
journal: hostTestRestingOptionsJournal()
}
// Picks serialize with the live read, so they can land only after it, as the answer is assembled.
const entered = Promise.withResolvers<void>()
const assembled = Promise.withResolvers<void>()
const home: AgentSessionModelCatalogResult = { origin: 'probe', fetchedAt: 1, models: [] }
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: picks and the reader read only the session's current child.
const session = { child } as unknown as StructuredAgentSessionHostSession
const sessions = new Map([['session-1', session]])
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real reader accesses only these injected ports; no provider process is launched.
const context = {
deps: {
adapter: {
readOptions: async () => ({
models: [],
current: answer
})
},
agents: { definition: () => null, capabilities: () => null },
store: hostTestOptionsReadStore(() => record),
modelCatalog: {
captureRead: hostTestCatalogReadOperation,
read: async () => home
}
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => conversation,
conversation: async () => {
entered.resolve()
await assembled.promise
return conversation
},
sessions
} as unknown as StructuredAgentSessionMutationContext
const pick = (model: string) => {
record.options.model = model
noteStructuredAgentSessionOptionPick(
{ deps: { adapter: {} }, sessions },
{ sessionId: 'session-1', fence: 2 },
{ key: 'model', value: model },
true
)
}
/** Run `during` while the read is between its live snapshot and its answer. */
const read = async (during: () => void = () => {}) => {
const answer = readStructuredAgentSessionOptions(context, 'session-1', {
readsWithoutModel: true
})
await entered.promise
during()
assembled.resolve()
return (await answer).current
}
return { read, pick, sessions, session }
}
it('keeps a live fallback report that no pick has replaced', async () => {
expect(await claudeOptionsRead(CONFIRMED_INIT).read()).toMatchObject({
reportedModel: 'opus[1m]'
})
expect(await claudeOptionsRead().read()).toMatchObject({
model: 'opus[1m]',
reportedModel: 'claude-opus-4-8'
})
})
it.each([
['picks back to the same model', ['sonnet', 'opus[1m]'], RESPONSE_REPORT],
['re-picks the shown model', ['opus[1m]'], RESPONSE_REPORT],
['picks back while only the init model confirms', ['sonnet', 'opus[1m]'], CONFIRMED_INIT]
])(
'drops a report captured before the user %s while the read is in flight',
async (_, models, answer) => {
const host = claudeOptionsRead(answer)
const current = await host.read(() => models.forEach((model) => host.pick(model)))
expect(current.model).toBe('opus[1m]')
expect(current.reportedModel).toBeUndefined()
}
)
it('drops a report from a child that ended or was replaced while the read was in flight', async () => {
for (const next of [null, { fence: 3, phase: 'ready' }]) {
const host = claudeOptionsRead()
const current = await host.read(() => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only child identity matters to the reader.
host.sessions.set('session-1', {
...host.session,
child: next
} as unknown as StructuredAgentSessionHostSession)
})
expect(current.reportedModel).toBeUndefined()
}
})
it.each([
[
'retires the report when the user picks back to it',
QUEUED_RIG_CALLER,
['sonnet', 'opus[1m]'],
undefined
],
[
'keeps the report through an old client empty no-op',
{ ...QUEUED_RIG_CALLER, readsOptionsWithoutModel: false },
[''],
'claude-opus-4-8'
]
] as const)(
'after a usage-limited turn, a pick made while recovery choices load %s',
async (_, caller, models, reportedModel) => {
const rig = await createQueuedMessageTestRig({ agent: 'claude' })
try {
const pick = async (value: string) => {
const fields = { key: 'model', value }
return rig.host.setOption(caller, {
envelope: rig.envelope(fields, 'agentSession.setOption', hostTestOperationId()),
...fields
})
}
expect(await pick('opus[1m]')).toMatchObject({ ok: true })
rig.host.deps.adapter.readOptions = async () => ({ models: [], current: RESPONSE_REPORT })
const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal
await appendUsageLimitedTurn(journal, NOW, 'quota')
const recovering = Promise.withResolvers<void>()
const released = Promise.withResolvers<undefined>()
rig.host.deps.resolveLaunchEnv = () => {
recovering.resolve()
return released.promise
}
const answer = rig.host.readOptions(SESSION)
await recovering.promise
for (const model of models) {
expect(await pick(model)).toMatchObject({ ok: true })
}
released.resolve(undefined)
const { current } = await answer
expect(current.model).toBe('opus[1m]')
expect(current.reportedModel).toBe(reportedModel)
} finally {
await rig.dispose()
}
}
)
@@ -55,7 +55,10 @@ import { openWithReadyStructuredAgentSessionChild } from './structured-agent-ses
import type { StructuredAgentSessionCaller } from '../host/structured-agent-session-host-types'
import '../options/structured-agent-session-options-read'
import { recordStructuredAgentSessionOptionIntent } from '../options/structured-agent-session-option-intent'
import {
noteStructuredAgentSessionOptionPick,
recordStructuredAgentSessionOptionIntent
} from '../options/structured-agent-session-option-intent'
import { confirmIdleStructuredAgentSessionOption } from '../options/structured-agent-session-idle-option'
export function sendStructuredAgentSessionTurn(
@@ -265,6 +268,7 @@ export async function setStructuredAgentSessionOption(
readsWithoutModel: caller.readsOptionsWithoutModel !== false
})
if (picked.ok) {
noteStructuredAgentSessionOptionPick(context, ctx, params, !noChoice)
confirmIdleStructuredAgentSessionOption(context, ctx, params)
}
return picked
@@ -19,6 +19,10 @@ import {
} from './structured-agent-session-pick-reply'
import type { StructuredAgentSessionAdapter } from '../providers/structured-agent-session-adapter'
import { pickAgentSessionOption } from '../../../runtime/agent-session/records/agent-session-record-options'
import type {
StructuredAgentSessionHostSession,
StructuredAgentSessionProviderChild
} from '../host/structured-agent-session-host-types'
function acceptsOptionPick(
agents: Pick<StructuredAgentRegistry, 'definition'>,
@@ -103,3 +107,34 @@ export async function recordStructuredAgentSessionOptionIntent(
}
}
}
const modelPicks = new WeakMap<StructuredAgentSessionProviderChild, number>()
/** Counts saved model picks per child, so a read can tell its captured report predates one. */
export function structuredAgentSessionModelPicks(
child: StructuredAgentSessionProviderChild
): number {
return modelPicks.get(child) ?? 0
}
/** A saved pick retires the current child's earlier reports, including ones a read already captured. */
export function noteStructuredAgentSessionOptionPick(
context: {
deps: { adapter: Pick<StructuredAgentSessionAdapter, 'noteOptionPick'> }
sessions: ReadonlyMap<string, StructuredAgentSessionHostSession>
},
ctx: Pick<AgentSessionTurnContext, 'sessionId' | 'fence'>,
input: { key: string; value: string },
saved: boolean
): void {
const { sessionId, fence } = ctx
// An old client's empty model clears nothing, so it retires no report.
if (!saved) {
return
}
const child = context.sessions.get(sessionId)?.child
if (input.key === 'model' && child?.fence === fence) {
modelPicks.set(child, structuredAgentSessionModelPicks(child) + 1)
}
context.deps.adapter.noteOptionPick?.({ sessionId, fence, ...input })
}
@@ -30,12 +30,13 @@ import { structuredAgentSessionImmediatePermission } from './structured-agent-se
import type { StructuredAgentSessionMutationContext } from '../operations/structured-agent-session-mutation-context'
import { readStructuredSessionRecovery } from '../recovery/structured-agent-session-recovery-read'
import { fillUnknownModelEfforts } from '../../../../shared/agent-session/options/agent-session-model-efforts'
import { structuredAgentSessionModelPicks } from './structured-agent-session-option-intent'
/** A live child's own answer, or the answer at rest; the goal, usage and rewind either way. */
export async function readStructuredAgentSessionOptions(
context: Pick<
StructuredAgentSessionMutationContext,
'deps' | 'serialize' | 'openConversation' | 'conversation'
'deps' | 'serialize' | 'openConversation' | 'conversation' | 'sessions'
> &
Partial<Pick<StructuredAgentSessionMutationContext, 'deliveryOrder'>>,
sessionId: string,
@@ -71,6 +72,7 @@ export async function readStructuredAgentSessionOptions(
child && child.phase !== 'starting'
? await adapter.readOptions?.({ sessionId, fence: child.fence })
: undefined
const modelPicks = child ? structuredAgentSessionModelPicks(child) : 0
const scope = () =>
structuredAgentSessionCatalogScopeOwned(
context.deps,
@@ -93,7 +95,8 @@ export async function readStructuredAgentSessionOptions(
records,
session,
child,
options: observed ?? null
options: observed ?? null,
modelPicks
}
})
let started = await readCurrent(true)
@@ -132,6 +135,7 @@ export async function readStructuredAgentSessionOptions(
const floor = session.journal.context.floor()
const contextFloor = floor ? { contextFloor: floor } : {}
const restingOptions = await atRest()
const recovery = await readStructuredSessionRecovery(session, context, sessionId)
if (live && usesModelSpecificAcpEfforts(agent)) {
options = {
...options,
@@ -159,12 +163,17 @@ export async function readStructuredAgentSessionOptions(
const model = saved.model ?? (options.current.model || selected.current.model || displayDefault)
const projected = live?.projectCurrent?.({ ...saved, ...(model ? { model } : {}) })
const reportedEffort = projected?.confirmed?.includes('effort') ? projected.effort : undefined
const reportedModel = live
? (options.current.reportedModel ??
(agent === 'claude' && options.current.confirmed?.includes('model')
? options.current.model
: undefined))
: undefined
// After every await: a pick or a replaced child since the live read retires its report.
const reportedModel =
live &&
started.kind === 'live' &&
context.sessions.get(sessionId)?.child === started.child &&
started.modelPicks === structuredAgentSessionModelPicks(started.child)
? (options.current.reportedModel ??
(agent === 'claude' && options.current.confirmed?.includes('model')
? options.current.model
: undefined))
: undefined
const current = {
...selected.current,
...options.current,
@@ -236,7 +245,6 @@ export async function readStructuredAgentSessionOptions(
current.serviceTier = projected.options.serviceTier
}
}
const recovery = await readStructuredSessionRecovery(session, context, sessionId)
return {
...options,
...recovery,
@@ -258,7 +266,7 @@ export async function readStructuredAgentSessionOptions(
current: {
...current,
acceptedInputSources,
...(reportedModel ? { reportedModel } : {}),
reportedModel,
...(reportedEffort !== undefined ? { reportedEffort } : {}),
defaulted,
confirmed,
@@ -204,6 +204,8 @@ export class StructuredAgentSessionAdapterRouter implements Adapter {
canSetOptionWhileIdle: Adapter['canSetOptionWhileIdle'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.canSetOptionWhileIdle?.(input) === true
noteOptionPick: Adapter['noteOptionPick'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.noteOptionPick?.(input)
readAppliedInputOptions: Adapter['readAppliedInputOptions'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.readAppliedInputOptions?.(input) ?? null
@@ -304,6 +304,8 @@ export type StructuredAgentSessionAdapter = StructuredAgentSessionAdapterStop &
): Promise<void | Readonly<Record<string, string>>>
/** Opt in only when setOption can update idle metadata without a provider turn. */
canSetOptionWhileIdle?(input: StructuredAgentSessionSetOptionInput): boolean
/** A saved pick retires this child's earlier execution reports until a turn carries it. */
noteOptionPick?(input: { sessionId: string; fence: number; key: string; value: string }): void
/** Applied inputs for this exact child; observations never decide message admission. */
readAppliedInputOptions?(input: {
sessionId: string
+2
View File
@@ -226,6 +226,8 @@ async function startOrcadRuntime(
paneGridsForShutdown = runtime
accountLaunch?.attachToRuntime(runtime)
const { wireGitHubIssueLinkTitleFill } = await import('../github/github-issue-link-title-wiring')
registerCleanup(wireGitHubIssueLinkTitleFill(profileStore, runtime))
const { installOrcadEmulatorBridge } = await import('./orcad-emulator-bridge')
installOrcadEmulatorBridge(runtime, registerCleanup)
@@ -0,0 +1,59 @@
import { closeTestStores, testState, createStore, writeDataFile } from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { rmSync, mkdtempSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
vi.mock('electron', () => ({
app: { getPath: () => testState.dir },
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length)
}
}))
vi.mock('../../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../../telemetry/cohort-classifier', () => ({
getCohortAtEmit: () => ({ nth_repo_added: 2 })
}))
function writeSettings(settings: Record<string, unknown>): void {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings,
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
}
describe('artifact sharing default', () => {
beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-'))
})
afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('allows publishing on a new profile and keeps it after a reload', async () => {
const store = await createStore()
expect(store.getSettings().artifactSharingEnabled).toBe(true)
store.flush()
await closeTestStores()
expect((await createStore()).getSettings().artifactSharingEnabled).toBe(true)
})
it('keeps a stored opt-out', async () => {
writeSettings({ artifactSharingEnabled: false })
expect((await createStore()).getSettings().artifactSharingEnabled).toBe(false)
})
it('keeps publishing off for a stored profile saved before the setting existed', async () => {
writeSettings({ showArtifactsButton: false })
expect((await createStore()).getSettings().artifactSharingEnabled).toBe(false)
})
})
@@ -98,6 +98,8 @@ export function normalizeLoadedGlobalSettings(
),
worktreeVisibilityDefaults: migratedExternalVisibility.defaults,
prBotAuthorOverrides: normalizePRBotAuthorOverrides(parsed.settings?.prBotAuthorOverrides),
// Only fresh profiles take the on default; a stored profile saved before the key existed was off.
artifactSharingEnabled: parsed.settings?.artifactSharingEnabled === true,
// Carry the retired sidekick flag into pet settings.
experimentalPet: parsed.settings?.experimentalPet ?? readLegacySidekickFlag(parsed) ?? false,
// Migrate old platform defaults once; retain later opt-outs.
@@ -1,3 +1,4 @@
import { randomUUID } from 'node:crypto'
import { removeStaleDurableWriteTempFiles } from '../../filesystem/durable-file-write'
import type { GlobalSettings } from '../../../shared/global-settings-types'
import type { PersistedState } from '../../../shared/persisted-state-types'
@@ -6,7 +7,7 @@ import type {
WorkspaceSessionWriteListener
} from './workspace-session-write-listeners'
import type { ExecutionHostId } from '../../../shared/execution-host'
import type { StateWriteListener } from './write-scheduling'
import type { StateWriteListener, WorktreeMetaWriteListener } from './write-scheduling'
import type { PartitionEditorViews } from './layout-editor-views'
import type { ActiveViewPreference } from '../preferences/active-view-preference'
import {
@@ -114,6 +115,9 @@ export class StoreRuntimeState {
/** In-memory editor views by partition; layout-owner builds only. */
readonly layoutEditorViews = new Map<ExecutionHostId, PartitionEditorViews>()
readonly stateWriteListeners = new Set<StateWriteListener>()
readonly worktreeMetaWriteListeners = new Set<WorktreeMetaWriteListener>()
// This store's workspaceMetadata position: a new epoch per process, one seq per published record.
readonly workspaceMetadataCursor = { epoch: randomUUID(), seq: 0 }
projectHostOperations: ProjectHostPersistenceOperations | null = null
projectGroupOperations: ProjectGroupPersistenceOperations | null = null
folderWorkspaceOperations: FolderWorkspacePersistenceOperations | null = null
@@ -19,7 +19,8 @@ import {
worktreeMetaHostFor
} from '../../../shared/worktree/local-only-worktree-meta-ids'
type MetadataRuntime = Pick<StoreRuntimeState, 'state'>
type MetadataRuntime = Pick<StoreRuntimeState, 'state'> &
Partial<Pick<StoreRuntimeState, 'worktreeMetaWriteListeners'>>
type WorktreeMetaState = Pick<
PersistedState,
'worktreeMeta' | 'worktreeMetaByIdentity' | 'worktreeIdentityAliases'
@@ -265,5 +266,13 @@ export function setWorktreeMetaForHost(
state.worktreeMeta[worktreeId] = updated
}
scheduleSave(scheduling, WORKTREE_METADATA_DOMAINS)
for (const listener of runtime.worktreeMetaWriteListeners ?? []) {
try {
listener({ worktreeId, hostId: executionHostId, previous: existing, next: updated })
} catch (error) {
// The row is already written; an observer's failure must not report the write as failed.
console.error('[worktree-meta] write listener failed:', error)
}
}
return updated
}

Some files were not shown because too many files have changed in this diff Show More