Merge origin/main into model menus branch

This commit is contained in:
Brennan Benson
2026-11-09 17:30:37 -08:00
860 changed files with 12149 additions and 18619 deletions
@@ -19,7 +19,6 @@ on:
# Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts;
# without these a rename lands green and only breaks the next nightly.
- 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts'
- 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts'
- 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts'
- 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts'
- 'src/main/runtime/rpc/methods/projects/repo.test.ts'
+1
View File
@@ -282,6 +282,7 @@
1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts
1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts
1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts
1 src/main/ipc/floating-workspace-directory.ts
1 src/main/ipc/macos-keyboard-layout-snapshot.ts
1 src/main/ipc/notification-authorization-status.ts
1 src/main/ipc/pty/spawn-pane-env.ts
File diff suppressed because one or more lines are too long
@@ -5802,9 +5802,6 @@
"src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303,
"src/renderer/src/components/terminal-pane/session-fork/TerminalAgentSessionForkDialog.test.tsx": 266,
"src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx": 1104,
"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalPaneRecoveryPortals.test.tsx": 670,
"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalRemoteRuntimeReconnectBanner.test.tsx": 812,
"src/renderer/src/components/terminal-pane/pty-transport/recovery/ssh/TerminalSshReconnectOverlay.test.tsx": 2354,
"src/renderer/src/components/terminal-pane/account-restart/detached/account-restart-queue-progress.test.ts": 1988,
"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-attention-dispatch.test.ts": 301,
"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-completion-replay-guard.test.ts": 318,
@@ -5897,7 +5894,6 @@
"src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76,
"src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123,
"src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-kitty-file-reader.test.ts": 297,
"src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts": 1882,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/snapshot-covered-terminal-queries.test.ts": 150,
"src/renderer/src/components/terminal-pane/pty-connection/output/terminal-input-echo-delay.test.ts": 132,
"src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70,
@@ -5925,7 +5921,6 @@
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts": 683,
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts": 1636,
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-recycled-pty-incarnation.test.ts": 787,
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-errors.test.ts": 1218,
"src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts": 208,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-outcomes.test.ts": 2794,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-unavailable-banner.repro.test.ts": 2355,
@@ -5992,7 +5987,6 @@
"src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131,
"src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76,
"src/renderer/src/components/terminal-pane/parking/retention/terminal-cold-park-timer-rearm.test.tsx": 701,
"src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts": 111,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts": 638,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-image-path.test.ts": 61,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts": 800,
@@ -6265,8 +6259,8 @@
"src/renderer/src/hooks/useMacTccAttributionSeveredNotice.test.tsx": 2358,
"src/renderer/src/hooks/useMetadataListRequest.test.tsx": 266,
"src/renderer/src/hooks/useModalReturnFocus.test.tsx": 1938,
"src/renderer/src/hooks/usePrimarySelectionPaste.terminal-native-paste.test.tsx": 388,
"src/renderer/src/hooks/usePrimarySelectionPaste.test.tsx": 411,
"src/renderer/src/hooks/clipboard/primary-selection/usePrimarySelectionPaste.terminal-native-paste.test.tsx": 388,
"src/renderer/src/hooks/clipboard/primary-selection/usePrimarySelectionPaste.test.tsx": 411,
"src/renderer/src/hooks/useReadOnScreenAttention.away.test.ts": 2420,
"src/renderer/src/hooks/useReadOnScreenAttention.clock-skew.test.ts": 2093,
"src/renderer/src/hooks/useReadOnScreenAttention.floating-panel.test.ts": 2157,
@@ -6340,9 +6334,9 @@
"src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.test.ts": 408,
"src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync-inputs.test.ts": 476,
"src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync.test.ts": 925,
"src/renderer/src/lib/app-command-dispatch.test.ts": 64,
"src/renderer/src/lib/app-keyboard-router.test.ts": 187,
"src/renderer/src/lib/app-menu-paste.test.ts": 229,
"src/renderer/src/lib/app-commands/app-command-dispatch.test.ts": 64,
"src/renderer/src/lib/keyboard/app-keyboard-router.test.ts": 187,
"src/renderer/src/lib/clipboard/menu/app-menu-paste.test.ts": 229,
"src/renderer/src/lib/automation-session-reuse.test.ts": 70,
"src/renderer/src/lib/automation-terminal-ownership.test.ts": 1795,
"src/renderer/src/lib/bounded-generation-map.test.ts": 35,
@@ -6358,7 +6352,7 @@
"src/renderer/src/lib/source-control/checks/check-run-details-log-normalization.test.ts": 75,
"src/renderer/src/lib/claude-account-switch-sessions.test.ts": 782,
"src/renderer/src/lib/claude-session-account-move.test.ts": 1816,
"src/renderer/src/lib/clipboard-image-copy.test.ts": 243,
"src/renderer/src/lib/clipboard/images/clipboard-image-copy.test.ts": 243,
"src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts": 526,
"src/renderer/src/lib/cmd-j-linear-issue-intent.test.ts": 42,
"src/renderer/src/lib/code-host-error-copy.test.ts": 297,
@@ -6367,8 +6361,7 @@
"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts": 2039,
"src/renderer/src/lib/codex-stale-pane-account-identity.test.ts": 1823,
"src/renderer/src/lib/codex-stale-pane-sweep.test.ts": 1817,
"src/renderer/src/lib/comment-body-line-count.test.ts": 84,
"src/renderer/src/lib/comment-body-submit-state.test.ts": 55,
"src/renderer/src/lib/source-control/review/comments/comment-body-submit-state.test.ts": 55,
"src/renderer/src/lib/composer-submit-cancellation.test.ts": 41,
"src/renderer/src/lib/workspace/ownership/connection-context.test.ts": 1817,
"src/renderer/src/lib/crash-diagnostics.test.ts": 176,
@@ -6391,9 +6384,9 @@
"src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872,
"src/renderer/src/lib/focus-terminal-tab-surface.split-focus.test.ts": 331,
"src/renderer/src/lib/foreground-terminal-tabs.test.ts": 55,
"src/renderer/src/lib/github-links.test.ts": 76,
"src/renderer/src/lib/github-source-runtime-context.test.ts": 62,
"src/renderer/src/lib/gitlab-links.test.ts": 56,
"src/shared/new-workspace/github-links.test.ts": 76,
"src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62,
"src/shared/new-workspace/gitlab-links.test.ts": 56,
"src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1904,
"src/renderer/src/lib/host-chat-program.test.ts": 2419,
"src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706,
@@ -6401,11 +6394,10 @@
"src/renderer/src/lib/host-mirrored-pane-resume-replay.test.ts": 1814,
"src/renderer/src/lib/browser/navigation/http-link-completion.test.ts": 1760,
"src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts": 2211,
"src/renderer/src/lib/image-blob-png.test.ts": 253,
"src/renderer/src/lib/ime-composition-keyboard-event.test.ts": 274,
"src/renderer/src/lib/ime-text-field.test.tsx": 739,
"src/renderer/src/lib/text-input/ime/ime-composition-keyboard-event.test.ts": 274,
"src/renderer/src/lib/text-input/ime/ime-text-field.test.tsx": 739,
"src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts": 48,
"src/renderer/src/lib/large-text-control-paste.test.ts": 220,
"src/renderer/src/lib/text-input/paste/large-text-control-paste.test.ts": 220,
"src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session-launch-parity.test.ts": 2792,
"src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session.test.ts": 1040,
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts": 1821,
@@ -6422,11 +6414,10 @@
"src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts": 194,
"src/renderer/src/lib/lazy-with-retry.preload.test.tsx": 208,
"src/renderer/src/lib/lazy-with-retry.test.ts": 282,
"src/renderer/src/lib/linear-board-drag-payload.test.ts": 58,
"src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts": 55,
"src/renderer/src/lib/work-items/linear/linear-board-drag-payload.test.ts": 58,
"src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99,
"src/renderer/src/lib/link-source-local-open-owner.test.ts": 433,
"src/renderer/src/lib/linked-work-item-context.test.ts": 64,
"src/renderer/src/lib/work-items/linked-work-item-context.test.ts": 64,
"src/renderer/src/lib/editor/monaco/monaco-editor-gutter-disposal.test.ts": 295,
"src/renderer/src/lib/monaco-languages/markdown-heading-outline.test.ts": 70,
"src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts": 697,
@@ -6510,14 +6501,14 @@
"src/renderer/src/lib/pane-manager/xterm-write-callback-guard.test.ts": 53,
"src/renderer/src/lib/pane-spawn-deferral-drain.test.ts": 61,
"src/renderer/src/lib/parked-terminal-host-hydration.test.ts": 274,
"src/renderer/src/lib/paste-payload-metadata.test.ts": 53,
"src/renderer/src/lib/text-input/paste/paste-payload-metadata.test.ts": 53,
"src/renderer/src/lib/path-head-elision.test.ts": 53,
"src/renderer/src/lib/path.test.ts": 55,
"src/renderer/src/lib/plugin-command-keybindings.test.ts": 1909,
"src/renderer/src/lib/plugin-command-replacements.test.ts": 95,
"src/renderer/src/lib/plugin-icons/plugin-icon-svg.test.ts": 231,
"src/renderer/src/lib/plugin-monaco-token-rules.test.ts": 51,
"src/renderer/src/lib/pr-bot-author-overrides.test.ts": 349,
"src/renderer/src/lib/source-control/review/pr-bot-author-overrides.test.ts": 349,
"src/renderer/src/lib/source-control/review/comments/pr-comment-thread-resolution.test.ts": 48,
"src/renderer/src/lib/project-clone-url-prefill.test.ts": 61,
"src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts": 76,
@@ -6579,8 +6570,8 @@
"src/renderer/src/lib/task-provider-error-copy.test.ts": 363,
"src/renderer/src/lib/terminal-app-theme.test.ts": 301,
"src/renderer/src/lib/terminal-input-activity-coalescing.test.ts": 43,
"src/renderer/src/lib/text-control-paste-ownership.test.ts": 217,
"src/renderer/src/lib/text-control-paste.test.ts": 222,
"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,
-1
View File
@@ -6,7 +6,6 @@ import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-
const contracts = [
'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts',
'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts',
'src/main/runtime/rpc/methods/projects/repo.test.ts',
+1 -1
View File
@@ -44,7 +44,7 @@ Tokens pair a **surface** with a **foreground** that meets contrast on it; alway
- Body letter-spacing is set globally on `body`; don't override per component.
- Use Tailwind's scale. Common: 14px body/default buttons, 13px sidebar items and dense rows, 12px sub-text and paths, 11px uppercase meta/captions.
- Use `text-2xs` (11px) and `text-3xs` (10px), not `text-[11px]` / `text-[10px]`.
- Category labels: 11px, `font-semibold`, `uppercase`, `tracking-wider` (0.05em).
- Category labels: 11px, `font-semibold`, `uppercase`, `tracking-wider` (0.05em). Settings content uses sentence case without tracking: 14px row labels, `text-settings-detail` (12.5px) help, and `text-settings-heading` (15px) semibold section headings. Settings form rows use about 9px vertical padding (44px minimum), selects are 28px, and the centered content column is at most 720px with at least 32px side gutters. These density rules are scoped to `.settings-view-shell`; shared primitives retain their defaults elsewhere.
- Native chat has its own lint-enforced scale and colours: see [native-chat.md](./styleguide/native-chat.md).
## Radius and elevation
+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: 162m">
<title>downloads: 162m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 163m">
<title>downloads: 163m</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">162m</text>
<text x="93.5" y="14">162m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">163m</text>
<text x="93.5" y="14">163m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 KiB

After

Width:  |  Height:  |  Size: 473 KiB

@@ -73,3 +73,20 @@ it('records where a resumed process really started over the folder its seed name
expect(recordedSession()?.cwd).toBe('/elsewhere')
})
it('names the pane session from a --fork-session start, which Claude 2.1.214+ reports as fork', async () => {
// Captured from Claude 2.1.321 `claude --resume <id> --fork-session` before any message.
await claudeHook({
session_id: 'b47ec7fc-07e4-4012-8b28-1d5daa938f52',
transcript_path:
'/Users/u/.claude/projects/-private-tmp-w39942fork/b47ec7fc-07e4-4012-8b28-1d5daa938f52.jsonl',
cwd: '/private/tmp/w39942fork',
hook_event_name: 'SessionStart',
source: 'fork'
})
expect(recordedSession()).toMatchObject({
id: 'b47ec7fc-07e4-4012-8b28-1d5daa938f52',
cwd: '/private/tmp/w39942fork'
})
})
@@ -31,17 +31,28 @@ export type AgentModelCatalogListModels = (
owner: StructuredAgentResolutionOperation
) => Promise<AgentModelCatalogSuccess>
/** The refresh that starts a listing gives it its budget; joining never extends or shortens it. */
/** Covers the gap between one waiting read and the next, so a following reader keeps its place. */
const AGENT_MODEL_CATALOG_RELEASE_GRACE_MS = 5_000
/** Queued listings need a holder; admitted probes run to their own timeout. */
export type AgentModelCatalogListingBudget = {
/** Expiry withdraws it from admission, stops its process and drops its late answer. */
deadline?: number
/** This caller's interest; a queued listing is withdrawn a grace after no holder is left. */
signal?: AbortSignal
/** Service shutdown retires the listing immediately, without the holder release grace. */
lifetime?: AbortSignal
admission?: PrioritySemaphore
/** Execution time after admission. */
timeoutMs?: number
}
export type InFlightListing = {
agent: string
targets: Set<string>
current: () => boolean
/** Adds a queued holder until its signal aborts; admitted probes need none. */
hold: (signal: AbortSignal | undefined) => void
promise: Promise<AgentModelCatalogEntry | null>
finish: (entry: AgentModelCatalogEntry | null) => void
cleanup: () => void
@@ -93,47 +104,91 @@ export function refreshAgentModelCatalogListing(input: {
) => AgentModelCatalogEntry | null
}): Promise<AgentModelCatalogEntry | null> {
const { fingerprint, agent, listModels } = input
const { deadline, signal } = input.budget ?? {}
const { signal, lifetime, admission, timeoutMs, deadline: budgetDeadline } = input.budget ?? {}
let deadline = budgetDeadline
const existing = input.refreshes.get(fingerprint)
if (existing) {
existing.hold(signal)
demandAgentModelEfforts(existing, input.selectedModel, input.maxTargets)
return existing.promise
}
const result = Promise.withResolvers<AgentModelCatalogEntry | null>()
// Ending the flight (its budget, the account or CLI retired, shutdown) stops its process too.
const stopped = new AbortController()
const expiry =
deadline === undefined
? undefined
: setTimeout(() => retire(), Math.max(0, deadline - Date.now()))
let expiry: ReturnType<typeof setTimeout> | undefined
const holders = new Map<AbortSignal, () => void>()
// A listing started without a signal is held until it settles.
let held = signal === undefined
const setDeadline = (next: number | undefined): void => {
deadline = next
clearTimeout(expiry)
if (deadline !== undefined) {
expiry = setTimeout(retire, Math.max(0, deadline - Date.now()))
}
}
const flight: InFlightListing = {
agent,
targets: new Set(input.selectedModel ? [input.selectedModel] : []),
current: () => !signal?.aborted && (deadline === undefined || Date.now() < deadline),
current: () => !lifetime?.aborted && (deadline === undefined || Date.now() < deadline),
hold: (holder) => {
if (!held && holder && !holder.aborted && !holders.has(holder)) {
setDeadline(budgetDeadline)
const abandon = (): void => {
holders.delete(holder)
if (!held && holders.size === 0) {
setDeadline(
Math.min(
budgetDeadline ?? Infinity,
Date.now() + AGENT_MODEL_CATALOG_RELEASE_GRACE_MS
)
)
}
}
holders.set(holder, abandon)
holder.addEventListener('abort', abandon, { once: true })
}
},
promise: result.promise,
finish: result.resolve,
cleanup: () => {
clearTimeout(expiry)
signal?.removeEventListener('abort', retire)
lifetime?.removeEventListener('abort', retire)
for (const [holder, abandon] of holders) {
holder.removeEventListener('abort', abandon)
}
stopped.abort()
}
}
const retire = (): void =>
retireAgentModelCatalogListing(input.refreshes, input.listingWaiters, fingerprint, flight)
const current = (): boolean => input.refreshes.get(fingerprint) === flight && flight.current()
const owner: StructuredAgentResolutionOperation = { current, signal: stopped.signal, deadline }
input.refreshes.set(fingerprint, flight)
signal?.addEventListener('abort', retire, { once: true })
if (!flight.current()) {
setDeadline(budgetDeadline)
flight.hold(signal)
lifetime?.addEventListener('abort', retire, { once: true })
if (signal?.aborted || !flight.current()) {
retire()
}
const span = startSpan('agentModelCatalog.discovery', { attributes: { agent, lister: 'probe' } })
void Promise.resolve().then(async () => {
let release: (() => void) | undefined
try {
release = await admission?.acquire(0, stopped.signal)
if (!current()) {
span.end()
return
}
held = true
// Admission replaces the abandonment deadline with the probe's own execution budget.
setDeadline(
timeoutMs === undefined
? budgetDeadline
: Math.min(budgetDeadline ?? Infinity, Date.now() + timeoutMs)
)
const owner: StructuredAgentResolutionOperation = {
current,
signal: stopped.signal,
deadline
}
let targets = input.selectedModel ? [input.selectedModel] : undefined
let entry: AgentModelCatalogEntry | null = null
do {
@@ -165,6 +220,7 @@ export function refreshAgentModelCatalogListing(input: {
}
} finally {
retire()
release?.()
}
})
return flight.promise
@@ -172,20 +228,17 @@ export function refreshAgentModelCatalogListing(input: {
export function scopedAgentModelCatalogLister(input: {
legacy?: boolean
admission: PrioritySemaphore
signal: AbortSignal
resolved: AgentModelCatalogResolvedProbe | undefined
probe: AgentModelCatalogProbe | undefined
probeHome: AgentSessionAccountHome | null
workspacePath: string | undefined
}): AgentModelCatalogListModels {
const { legacy, admission, resolved, probe, probeHome, workspacePath } = input
const { legacy, resolved, probe, probeHome, workspacePath } = input
return async (selectedModels, operation) => {
const signal = operation.signal
? AbortSignal.any([input.signal, operation.signal])
: input.signal
// Waiting for a slot spends the listing's own budget; expiry withdraws it from the queue.
const release = legacy ? () => {} : await admission.acquire(0, signal)
const deadline = new AbortController()
// Share the retry budget and await bounded provider teardown before settling.
const timer = legacy ? setTimeout(() => deadline.abort(), 30_000) : undefined
@@ -211,8 +264,6 @@ export function scopedAgentModelCatalogLister(input: {
throw signal.aborted ? new AgentModelCatalogListingStoppedError(String(error)) : error
} finally {
clearTimeout(timer)
// The slot is held until the provider's teardown finishes.
release()
}
}
}
@@ -12,7 +12,7 @@ export type AgentModelCatalogReadOperation = {
deadline?: number
retirement: number
signal: AbortSignal
current: () => boolean
current: (options?: { ignoreDeadline: true }) => boolean
controller: AbortController
}
@@ -35,9 +35,9 @@ export function captureAgentModelCatalogRead(
retirement,
signal,
controller,
current: () =>
current: (options) =>
!signal.aborted &&
(deadline === undefined || Date.now() < deadline) &&
(options?.ignoreDeadline || deadline === undefined || Date.now() < deadline) &&
deps.store.retirementRevision(params.agent) === retirement &&
agentModelCatalogRequestKey(deps, original) === identity
}
@@ -16,6 +16,7 @@ import {
import { resolveAgentModelCatalogScope } from './agent-model-catalog-scope'
import { scopedAgentModelCatalogLister } from './agent-model-catalog-lister'
import { seedAccountList } from './agent-model-catalog-account-list'
import type { AgentModelCatalogEntry } from './agent-model-catalog-entry'
import {
agentModelCatalogReleasedOwner,
bindAgentModelCatalogScope,
@@ -23,7 +24,7 @@ import {
} from './agent-model-catalog-snapshot'
import { AGENT_MODEL_CATALOG_PICKER_WAIT_MS } from './agent-model-catalog-listing-waiters'
/** One budget for a whole refresh: setup, the folder's settings, admission and the listing. */
/** Bounds scope resolution and the folder's settings; listings own their execution budget. */
const AGENT_MODEL_CATALOG_REFRESH_MS = AGENT_MODEL_CATALOG_PICKER_WAIT_MS
/** What a refresh resolves, captured when it starts; no reader's session, deadline or callback. */
@@ -54,7 +55,7 @@ export type AgentModelCatalogRefresh = {
type Held = AgentModelCatalogRefresh & { workspaceId?: string; end: () => void }
/** Equivalent requests share one refresh that belongs to no reader. It ends when it finishes, at
* its fixed budget, on its agent's or workspace's retirement, or with the service; readers only
* its setup budget, on its agent's or workspace's retirement, or with the service; readers only
* wait on it, each until its own deadline or cancellation, and never extend or end it. */
export function createAgentModelCatalogRefreshes(context: {
deps: AgentModelCatalogServiceDeps
@@ -155,6 +156,7 @@ export function createAgentModelCatalogRefreshes(context: {
Object.assign(bound, { fingerprint, exact, cwd })
bindAgentModelCatalogScope(bindings, launch.bindingKey, bound, requestKey)
const probe = deps.probes?.[agent]
let completion: Promise<AgentModelCatalogEntry | null> | undefined
if (
!launch.passive &&
(exact || !agentModelCatalogReleasedOwner(scoped)) &&
@@ -163,7 +165,6 @@ export function createAgentModelCatalogRefreshes(context: {
) {
const lister = scopedAgentModelCatalogLister({
legacy: launch.legacy,
admission,
signal: lifetime,
resolved,
probe,
@@ -177,8 +178,8 @@ export function createAgentModelCatalogRefreshes(context: {
deps.store.efforts.due(fingerprint, model) ||
deps.store.isListing(fingerprint))
) {
// A listing another refresh started keeps that refresh's budget.
void deps.store.refresh(
// This refresh holds the listing while it runs; once admitted, the listing runs on.
completion = deps.store.refresh(
fingerprint,
agent,
(selected, owner) => {
@@ -187,7 +188,13 @@ export function createAgentModelCatalogRefreshes(context: {
void task.finally(() => tasks.delete(task)).catch(() => {})
return task
},
{ deadline, signal: lifetime },
{
signal,
lifetime,
...(launch.legacy
? { deadline }
: { admission, timeoutMs: AGENT_MODEL_CATALOG_REFRESH_MS })
},
model
)
}
@@ -195,16 +202,18 @@ export function createAgentModelCatalogRefreshes(context: {
for (const model of targets.size > 0 ? [...targets] : [undefined]) {
list(model)
}
listing.resolve()
await bounded(
deps.store.pendingListing(fingerprint, true, true, signal) ?? Promise.resolve(null)
)
}
listing.resolve()
if (launch.passive) {
await bound.projecting
} else if (current()) {
seedAccountList(deps, scope, agent)
} else {
// Discovery may finish after this refresh's setup budget ends.
const seeded = Promise.resolve(completion).then((entry) => {
if (entry !== null && bound.current()) {
seedAccountList(deps, scope, agent)
}
})
await bounded(seeded)
}
}
const end = (): void => ended.abort()
@@ -112,13 +112,26 @@ export function createAgentModelCatalogService(
binding: () => bindings.get(requestKey(params))
})
}
const result = snapshot(params)
// A waiting read that used its whole budget is final; work still running doesn't reopen it.
const { listingInProgress: _, ...settled } = result
const answer = waits && Date.now() >= deadline ? settled : result
return lifetime.signal.aborted
? answer
: readAccountList(deps, params, answer, () => memoryBinding({ agent: params.agent })?.base)
const expired = waits && Date.now() >= deadline
// Expiry ends the wait, but a still-current scope can describe the listing left behind.
const answerParams =
expired && params.operation?.current({ ignoreDeadline: true })
? { ...params, operation: undefined }
: params
const result = snapshot(answerParams)
const answer = lifetime.signal.aborted
? result
: readAccountList(
deps,
answerParams,
result,
() => memoryBinding({ agent: params.agent })?.base
)
if (!expired || !answer.listingInProgress) {
return answer
}
// Expiring a reader cannot settle the listing, including for clients predating waitExpired.
return { ...answer, waitExpired: true }
},
recordLiveListing: live.recordLiveListing,
async prewarm() {
@@ -6,10 +6,7 @@ import {
} from '../structured-agent-command-resolution'
import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store'
import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home'
import {
joinHostModelListingWait,
isHostModelListingWaitInFlight
} from '../../../shared/host-model-listing-waits'
import { agentModelCatalogFingerprint } from './agent-model-catalog-fingerprint'
function listing(id: string): AgentModelCatalogSuccess {
return {
@@ -98,7 +95,6 @@ it('finishes a shared listing for a folder that joined before the first reader g
vi.useRealTimers()
})
const h = sharedListingHarness()
const started = Date.now()
void h.service.demand({ agent: 'codex', workspacePath: '/a', deadline: Date.now() + 1_000 })
await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce())
const b = h.service.read({
@@ -110,8 +106,6 @@ it('finishes a shared listing for a folder that joined before the first reader g
await vi.advanceTimersByTimeAsync(2_000)
// The first reader is gone, but the listing it started is still running for the folder that joined.
expect(h.runs[0]?.signal?.aborted).toBe(false)
// Its requests carry the refresh's own budget, not the first reader's deadline.
expect(h.runs[0]?.deadline).toBe(started + 30_000)
h.discovery.resolve({ ...listing('shared'), complete: true, configured: {} })
await vi.advanceTimersByTimeAsync(0)
expect(await b).toMatchObject({ models: [{ id: 'shared' }] })
@@ -138,51 +132,79 @@ it.each(['retired', 'stopped'] as const)(
}
)
it('never starts a queued shared listing once its budget has run out, nor a replacement', async () => {
it('keeps a queued listing only while a refresh or reader still waits on it', async () => {
vi.useFakeTimers()
onTestFinished(() => {
vi.useRealTimers()
})
const h = sharedListingHarness()
// Two other CLIs hold both discovery slots past every budget below.
// Two other CLIs hold both discovery slots.
for (const busy of ['/busy-1', '/busy-2']) {
void h.service.demand({ agent: 'codex', workspacePath: busy })
}
await vi.waitFor(() => expect(h.run).toHaveBeenCalledTimes(2))
void h.service.demand({ agent: 'codex', workspacePath: '/a', deadline: Date.now() + 1_000 })
void h.service.demand({ agent: 'codex', workspacePath: '/b', deadline: Date.now() + 2_000 })
await vi.advanceTimersByTimeAsync(31_000)
void h.service.demand({ agent: 'codex', workspacePath: '/own-dropped' })
void h.service.demand({ agent: 'codex', workspacePath: '/own-waited' })
await vi.advanceTimersByTimeAsync(25_000)
void h.service.read({ agent: 'codex', workspacePath: '/own-waited', waitForListing: true })
await vi.advanceTimersByTimeAsync(15_000)
h.listingFor('/busy-1').resolve(listing('busy'))
h.listingFor('/busy-2').resolve(listing('busy'))
await vi.advanceTimersByTimeAsync(60_000)
expect(h.runs.map((entry) => entry.identity)).toEqual(['/busy-1', '/busy-2', '/own-waited'])
})
it('retires queued discovery before shutdown releases an admission slot', async () => {
vi.useFakeTimers()
onTestFinished(() => {
vi.useRealTimers()
})
const h = sharedListingHarness()
for (const workspacePath of ['/busy-1', '/busy-2', '/own-queued']) {
void h.service.demand({ agent: 'codex', workspacePath })
}
await vi.advanceTimersByTimeAsync(0)
expect(h.service.snapshot({ agent: 'codex', workspacePath: '/own-queued' })).toMatchObject({
listingInProgress: true
})
const stopped = h.service.stop()
h.listingFor('/busy-1').resolve(listing('busy'))
h.listingFor('/busy-2').resolve(listing('busy'))
await vi.advanceTimersByTimeAsync(0)
await stopped
expect(h.runs.map((entry) => entry.identity)).toEqual(['/busy-1', '/busy-2'])
})
it.each([5, 50])(
'runs two of %i folders with their own CLIs at a time, starts none after its budget, and leaves nothing behind',
async (folders) => {
vi.useFakeTimers()
onTestFinished(() => {
vi.useRealTimers()
})
const h = sharedListingHarness()
for (let index = 0; index < folders; index++) {
void h.service.demand({ agent: 'codex', workspacePath: `/own-${index}` })
}
await vi.advanceTimersByTimeAsync(0)
expect(h.run).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(30_000)
expect(h.runs.every((entry) => entry.signal?.aborted)).toBe(true)
// No reader asked again, so nothing replaces the expired work.
await vi.advanceTimersByTimeAsync(60_000)
expect(h.run).toHaveBeenCalledTimes(2)
for (let index = 0; index < folders; index++) {
expect(
h.service.snapshot({ agent: 'codex', workspacePath: `/own-${index}` })
).not.toHaveProperty('listingInProgress')
}
it('reports an expired captured wait and lets the next reader finish its queued listing', async () => {
vi.useFakeTimers()
onTestFinished(() => {
vi.useRealTimers()
})
const h = sharedListingHarness()
for (const workspacePath of ['/busy-1', '/busy-2']) {
void h.service.demand({ agent: 'codex', workspacePath })
}
)
await vi.advanceTimersByTimeAsync(0)
const params = { agent: 'codex', workspacePath: '/own-waited', waitForListing: true }
const operation = h.service.captureRead(params)
const request = { ...params, operation, deadline: operation.deadline }
const first = h.service.read(request)
await vi.advanceTimersByTimeAsync(30_000)
expect(await first).toEqual({ origin: 'unknown', listingInProgress: true, waitExpired: true })
operation.controller.abort()
expect(await h.service.read(request)).toEqual({ origin: 'unknown' })
const next = h.service.read(params)
await vi.advanceTimersByTimeAsync(0)
h.listingFor('/busy-1').resolve(listing('busy'))
h.listingFor('/own-waited').resolve(listing('fresh'))
await vi.advanceTimersByTimeAsync(0)
expect(await next).toMatchObject({ origin: 'probe', models: [{ id: 'fresh' }] })
expect(await next).not.toHaveProperty('waitExpired')
})
it("never answers a newly picked folder with the previous folder's late listing", async () => {
const h = sharedListingHarness()
@@ -326,98 +348,88 @@ it('settles each reader at its own deadline or cancellation, and stops the listi
expect(h.service.snapshot({ agent: 'codex', workspacePath: '/a' }).origin).toBe('unknown')
})
it.each(['cold', 'warm'] as const)(
'ends queued %s discovery within its original deadline and preserves existing observations',
async (mode) => {
vi.useFakeTimers()
const store = new AgentModelCatalogStore()
let failing = false
const run = vi.fn(
(
_home: AgentSessionAccountHome,
options?: { signal?: AbortSignal; workspacePath?: string }
) =>
new Promise<AgentModelCatalogSuccess>((resolve, reject) => {
const timer = setTimeout(
() =>
failing
? reject(new Error('offline'))
: resolve({
...listing(options?.workspacePath ?? 'listed'),
complete: true,
configured: {}
}),
12_000
)
options?.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new Error('stopped'))
},
{ once: true }
)
})
)
const service = createAgentModelCatalogService({
store,
getConversation: () => undefined,
getRecord: () => undefined,
drivesRecord: () => true,
resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: '/account' }),
// Each folder resolves its own CLI (a project-local install), so each lists separately.
probes: {
codex: Object.assign(run, {
resolve: async (
home: AgentSessionAccountHome,
_cwd: string,
_lookup?: unknown,
_operation?: unknown,
launchDirectory?: string
) => ({
identity: launchDirectory,
run: (signal?: AbortSignal) => run(home, { signal, workspacePath: launchDirectory })
})
})
}
})
const read = (path: string, waitForListing = false) =>
waitForListing
? service.read({ agent: 'codex', workspacePath: path, waitForListing })
: discover(service, { agent: 'codex', workspacePath: path })
const replies: unknown[] = []
let leave = () => {}
try {
if (mode === 'warm') {
const initial = read('/5', true)
await vi.advanceTimersByTimeAsync(12_000)
await initial
await vi.advanceTimersByTimeAsync(120_001)
}
failing = false
await Promise.all(['/1', '/2', '/3', '/4', '/5'].map((path) => read(path)))
const follow = vi.fn(() => read('/5', true))
const owner = { close() {} }
leave = joinHostModelListingWait('queued', follow, (reply) => replies.push(reply), owner)
const second = joinHostModelListingWait('queued', follow, () => {}, owner)
await vi.advanceTimersByTimeAsync(30_000)
expect(replies[0]).not.toHaveProperty('listingInProgress')
expect(follow).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(7_000)
expect(replies.at(-1)).not.toHaveProperty('listingInProgress')
expect(isHostModelListingWaitInFlight('queued', owner)).toBe(false)
if (mode === 'warm') {
expect(replies.at(-1)).toMatchObject({ models: [{ id: '/5' }] })
} else {
expect(replies.at(-1)).toEqual({ origin: 'unknown' })
}
expect(run).toHaveBeenCalledTimes(mode === 'warm' ? 6 : 5)
second()
} finally {
leave()
service.stop()
vi.useRealTimers()
it('publishes cached catalogs immediately and completes queued discoveries after admission', async () => {
vi.useFakeTimers()
const store = new AgentModelCatalogStore()
let warming = true
const probe =
(agent: string) => (_home: AgentSessionAccountHome, options?: { signal?: AbortSignal }) =>
new Promise<AgentModelCatalogSuccess>((resolve, reject) => {
// ast-grep-ignore: test-no-real-time-wait -- Fake timers simulate probe execution after queued admission.
const timer = setTimeout(
() =>
resolve({
...listing(warming ? 'saved' : `${agent}-fresh`),
complete: true,
configured: {}
}),
agent === 'pi' || agent === 'gemini' ? 20_000 : 15_000
)
options?.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new Error('stopped'))
},
{ once: true }
)
})
const service = createAgentModelCatalogService({
store,
getConversation: () => undefined,
getRecord: () => undefined,
drivesRecord: () => true,
resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: '/account' }),
probes: {
pi: probe('pi'),
gemini: probe('gemini'),
claude: probe('claude'),
codex: probe('codex')
}
})
try {
const saved = service.read({ agent: 'claude', waitForListing: true })
await vi.advanceTimersByTimeAsync(15_000)
await saved
warming = false
await vi.advanceTimersByTimeAsync(120_001)
for (const agent of ['pi', 'gemini', 'claude', 'codex']) {
await discover(service, { agent })
}
expect(await service.read({ agent: 'claude' })).toMatchObject({
models: [{ id: 'saved' }],
listingInProgress: true
})
const expired = service.read({
agent: 'claude',
waitForListing: true,
deadline: Date.now() + 5_000
})
await vi.advanceTimersByTimeAsync(5_000)
expect(await expired).toMatchObject({
models: [{ id: 'saved' }],
listingInProgress: true,
waitExpired: true
})
await vi.advanceTimersByTimeAsync(15_000)
const warm = service.read({ agent: 'claude', waitForListing: true })
const cold = service.read({ agent: 'codex', waitForListing: true })
await vi.advanceTimersByTimeAsync(15_000)
expect(await warm).toMatchObject({ models: [{ id: 'claude-fresh' }] })
expect(await cold).toMatchObject({ models: [{ id: 'codex-fresh' }] })
const account = agentModelCatalogFingerprint({
agent: 'claude',
accountHome: { variable: 'CODEX_HOME', path: '/account' },
wslDistro: null
})
expect(store.observation(account)).toMatchObject({
models: [{ id: 'claude-fresh', isDefault: false }]
})
} finally {
await service.stop()
vi.useRealTimers()
}
)
})
@@ -310,6 +310,8 @@ export class AgentModelCatalogStore {
pendingListing(
...wait: Parameters<AgentModelCatalogListingWaiters['wait']>
): ReturnType<AgentModelCatalogListingWaiters['wait']> {
// Waiting on a queued listing keeps it queued.
this.refreshes.get(wait[0])?.hold(wait[3])
return this.listingWaiters.wait(...wait)
}
@@ -1,5 +1,5 @@
import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome'
import { isEditableTarget, isNativeChatPromptTarget } from '@/lib/editable-target'
import { isEditableTarget, isNativeChatPromptTarget } from '@/lib/text-input/focus/editable-target'
export function createPluginsSettingsShortcutHandler(
target: EventTarget | null | undefined,
@@ -2,13 +2,13 @@ import { useAppStore } from '../store'
import { useClosedEditorTabCleanup } from '../components/editor/model-lifetime/retention/useClosedEditorTabCleanup'
import { useIpcEvents } from '../hooks/useIpcEvents'
import { useReadOnScreenAttention } from '../hooks/useReadOnScreenAttention'
import { useAppMenuPaste } from '../hooks/useAppMenuPaste'
import { useAppMenuSelectionActions } from '../hooks/useAppMenuSelectionActions'
import { useLargeTextControlPaste } from '../hooks/useLargeTextControlPaste'
import { useAppMenuPaste } from '../hooks/clipboard/menu/useAppMenuPaste'
import { useAppMenuSelectionActions } from '../hooks/app-commands/useAppMenuSelectionActions'
import { useLargeTextControlPaste } from '../hooks/text-input/paste/useLargeTextControlPaste'
import {
resolvePrimarySelectionMiddleClickPaste,
usePrimarySelectionPaste
} from '../hooks/usePrimarySelectionPaste'
} from '../hooks/clipboard/primary-selection/usePrimarySelectionPaste'
import { useRadixBodyPointerEventsRecovery } from '../hooks/useRadixBodyPointerEventsRecovery'
import { useOsc52ClipboardDefaultOnNotice } from '../components/terminal-pane/clipboard/osc52-clipboard-default-on-notice'
import { useWindowsTerminalFontWeightNotice } from '../components/terminal-pane/appearance/windows-terminal-font-weight-notice'
@@ -3,7 +3,7 @@ import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility'
import { getSelectedTextForFileSearch } from '../lib/file-search-selection'
import { registerAppCommandDispatcher } from '@/lib/app-command-dispatch'
import { registerAppCommandDispatcher } from '@/lib/app-commands/app-command-dispatch'
import { executePluginCommand } from '@/lib/plugin-command-execution'
import { runBuiltInOrReplacement } from '@/lib/plugin-command-replacements'
import {
@@ -34,7 +34,7 @@ import {
} from './app-command-handlers'
import type { AppChromeLayout } from './use-app-chrome-layout'
import type { FloatingWorkspacePanelState } from './use-floating-workspace-panel'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { textInputOwnsComposition } from '../../../shared/text-input-shortcut-policy'
import { isAgentTerminalPreviewTarget } from '../components/dashboard-popout/agent-terminal-preview-target'
+44 -1
View File
@@ -49,6 +49,10 @@
--text-2xs--line-height: calc(1 / 0.6875);
--text-3xs: 0.625rem;
--text-3xs--line-height: calc(0.875 / 0.625);
--text-settings-detail: 0.78125rem;
--text-settings-detail--line-height: 1.35;
--text-settings-heading: 0.9375rem;
--text-settings-heading--line-height: 1.4;
--text-chat-code: 0.75rem;
--text-chat-code--line-height: calc(1 / 0.75);
}
@@ -1059,7 +1063,9 @@ body[data-modal-overlay-open]
[data-slot='command-dialog-content'],
[data-slot='sheet-content'],
[data-onboarding-overlay]
):has(~ [data-slot='dialog-overlay'], ~ [data-slot='sheet-overlay']) {
):has(
~ :is([data-slot='dialog-overlay'], [data-slot='sheet-overlay']):not([data-state='closed'])
) {
filter: blur(2px);
}
@@ -2149,6 +2155,43 @@ html.native-shell .app-layout {
animation: settings-shell-enter 180ms ease-out;
}
/* Shared row primitives also render outside Settings; their density stays local to this page. */
.settings-view-shell > :not(aside) [data-slot='label'],
.settings-view-shell > :not(aside) [data-source-title] {
font-size: var(--text-sm);
line-height: 1.4;
}
.settings-view-shell > :not(aside) p.text-xs,
.settings-view-shell > :not(aside) p.text-2xs,
.settings-view-shell > :not(aside) p[class~='text-[10px]'],
.settings-view-shell > :not(aside) p[class~='text-[11px]'],
.settings-view-shell > :not(aside) p[class~='text-[12px]'],
.settings-view-shell > :not(aside) p[class~='text-[13px]'],
.settings-view-shell > :not(aside) [data-source-path] {
font-size: var(--text-settings-detail);
line-height: 1.35;
}
.settings-view-shell > :not(aside) [data-slot='select-trigger'],
.settings-view-shell > :not(aside) button[role='combobox'] {
min-height: 28px;
height: 28px;
}
.settings-view-shell > :not(aside) [data-settings-row]:not(:has([data-settings-row])) {
padding-block: 9px;
min-height: 44px;
}
.settings-view-shell > :not(aside) [data-settings-group-heading] {
font-size: var(--text-settings-heading);
}
.settings-view-shell > :not(aside) [data-settings-group-description] {
font-size: var(--text-settings-detail);
}
.repo-icon-emoji-picker .EmojiPickerReact {
--epr-bg-color: var(--card);
--epr-category-label-bg-color: var(--card);
@@ -2,7 +2,7 @@ import React, { useCallback, useMemo } from 'react'
import { toast } from 'sonner'
import * as VisuallyHidden from 'radix-ui/visually-hidden'
import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet'
import { hasBoundedCommentBodyText } from '@/lib/comment-body-submit-state'
import { hasBoundedCommentBodyText } from '@/lib/source-control/review/comments/comment-body-submit-state'
import { useAppStore } from '@/store'
import {
jiraGetIssueForTarget,
@@ -20,7 +20,7 @@ import { JiraIssueCommentComposer, JiraIssueWorkspaceContent } from './jira-issu
import { useJiraIssueWorkspaceActions } from './jira-issue-workspace-actions'
import { getJiraReadIdentity } from '@/store/slices/jira/jira-read-coordination'
import { defaultScopeHost } from '@/runtime/hosts/selection/default-creation-host'
import { taskSourceRuntimeTarget } from '@/lib/task-source-runtime-target'
import { taskSourceRuntimeTarget } from '@/lib/work-items/task-source-runtime-target'
import { getEnvironmentRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context'
import { runtimeTargetEnvironmentId } from '@/runtime/rpc/targets/runtime-client-target'
import { editedJiraIssueFields } from './jira-issue-workspace-hydration'
@@ -1,6 +1,6 @@
import { writeLinearIssue } from '@/lib/work-items/linear/linear-issue-write'
import { taskProviderErrorMessage } from '@/lib/task-provider-error-copy'
import { ImeTextarea } from '@/lib/ime-text-field'
import { taskProviderErrorMessage } from '@/lib/work-items/task-provider-error-copy'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import React, { useCallback, useRef, useState } from 'react'
import { LoaderCircle } from 'lucide-react'
import { toast } from 'sonner'
@@ -43,7 +43,7 @@ import { getWorkspaceComposerInitialFocusTarget } from '@/lib/workspace-composer
import '@/components/sidebar/workspace-creation/folder/folder-workspace-source-repos'
import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/workspace-creation/folder/folder-workspace-source-selection'
import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
// Keep Add Project’s clone/SSH machinery outside the composer entry render, matching App loading.
const HostedAddRepoDialog = lazyWithRetry(
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import { Copy } from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { addViewportSizeChangeListener } from '@/hooks/viewport-size-change-listener'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
type SelectedTextCopyMenuProps = {
children: React.ReactNode
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import { useEffect, useState, useCallback } from 'react'
import { ChevronUp, ChevronDown, X, CaseSensitive, Regex } from 'lucide-react'
import type { SearchAddon } from '@xterm/addon-search'
@@ -21,7 +21,7 @@ import {
useActivityTerminalPortalStatus
} from './activity-terminal-portal-status'
import type { ActivityTerminalPortalSlotId } from './activity-thread-types'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import {
selectDetectedWorktreesByRepo,
selectFolderWorkspaces,
@@ -13,6 +13,23 @@ import type {
ActivityLiveAgentState
} from './activity-thread-types'
import { buildPaneActivityEvents } from './activity-pane-events'
import {
buildActivityTabContext,
buildActivityTabHostIndex,
type ActivityTabContext,
type ActivityTabHostIndex
} from './activity-event-builder-context'
import type { BuildActivityEventsArgs } from './activity-event-builder'
type ActivityTabInputs = Pick<
BuildActivityEventsArgs,
'tabsByWorktree' | 'unifiedTabsByWorktree' | 'chatNames'
>
type ActivityTabIndexes = ActivityTabInputs & {
context: Map<string, ActivityTabContext>
hosts: ActivityTabHostIndex
}
type PaneActivityCacheEntry = {
source: unknown
@@ -29,12 +46,46 @@ type PaneActivityCacheEntry = {
export type ActivityEventBuildCache = {
panes: Map<string, PaneActivityCacheEntry>
tabs?: ActivityTabIndexes
}
export function createActivityEventBuildCache(): ActivityEventBuildCache {
return { panes: new Map() }
}
export function resolveActivityTabIndexes(
args: ActivityTabInputs,
cache: ActivityEventBuildCache | undefined
): ActivityTabIndexes {
const previous = cache?.tabs
if (
previous &&
previous.tabsByWorktree === args.tabsByWorktree &&
previous.unifiedTabsByWorktree === args.unifiedTabsByWorktree &&
previous.chatNames === args.chatNames
) {
return previous
}
const next: ActivityTabIndexes = {
tabsByWorktree: args.tabsByWorktree,
unifiedTabsByWorktree: args.unifiedTabsByWorktree,
chatNames: args.chatNames,
context: buildActivityTabContext(
args.tabsByWorktree,
args.unifiedTabsByWorktree,
args.chatNames
),
hosts:
previous && previous.unifiedTabsByWorktree === args.unifiedTabsByWorktree
? previous.hosts
: buildActivityTabHostIndex(args.unifiedTabsByWorktree)
}
if (cache) {
cache.tabs = next
}
return next
}
export type PaneBuildRequest = {
cacheKey: string
source: unknown
@@ -18,14 +18,13 @@ import { capActivityEvents } from './activity-event-cap'
import { newestActivityHistoryEntries } from './activity-pane-events'
import {
createActivityEventBuildCache,
resolveActivityTabIndexes,
resolvePaneBuild,
type ActivityEventBuildCache
} from './activity-event-build-cache'
import { appendUnsupportedAndRetainedEvents } from './activity-event-builder-sources'
import {
attributedActivityTabContext,
buildActivityTabContext,
buildActivityTabHostIndex,
resolveActivityEventOwner,
type ActivityEventOwner
} from './activity-event-builder-context'
@@ -63,12 +62,7 @@ export function buildActivityEvents(
const events: ActivityEvent[] = []
const paneEntryByPaneKey: Record<string, AgentStatusEntry> = {}
const seenEventIds = new Set<string>()
const tabContext = buildActivityTabContext(
args.tabsByWorktree,
args.unifiedTabsByWorktree,
args.chatNames
)
const tabHostIndex = buildActivityTabHostIndex(args.unifiedTabsByWorktree)
const { context: tabContext, hosts: tabHostIndex } = resolveActivityTabIndexes(args, cache)
const ownerCache = new Map<string, ActivityEventOwner>()
const liveAgentByPaneKey: Record<string, ActivityLiveAgentSnapshot> = {}
const seenCacheKeys = cache ? new Set<string>() : null
@@ -11,7 +11,7 @@ import {
import { translate } from '@/i18n/i18n'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus'
import { formatClipboardFilePath } from '@/lib/clipboard-file-path'
import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path'
import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner'
import { useAppStore } from '@/store'
import {
@@ -9,7 +9,7 @@ import { getWorktreeGitIdentityDisplay } from '../../../../shared/worktree/git-i
import { jumpToWorktreeFromSidebar } from '@/lib/workspace/activation/worktree-jump-navigation'
import { translate } from '@/i18n/i18n'
import { useTranslate } from '@/i18n/use-translate'
import { formatClipboardFilePath } from '@/lib/clipboard-file-path'
import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path'
import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner'
import { cn } from '@/lib/utils'
import {
@@ -67,6 +67,7 @@ export function useAllAgentPaneThreads({ badgeOnly = false }: { badgeOnly?: bool
)
) {
eventBuildCacheRef.current.panes.clear()
eventBuildCacheRef.current.tabs = undefined
return EMPTY_ACTIVITY_BUILD
}
// Global history caps affect live-thread unread and search state.
@@ -6,7 +6,7 @@ import { cn } from '@/lib/utils'
import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo'
import { translate } from '@/i18n/i18n'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import type { NativeChatComposerHandle } from '../native-chat/composer/native-chat-composer-types'
import { AgentLaunchPromptComposer } from './AgentLaunchPromptComposer'
import {
@@ -23,7 +23,7 @@ import {
import { useTranslate } from '@/i18n/use-translate'
import { agentModelChoiceChips } from './launch-settings/agent-model-choice-chips'
import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut'
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event'
import { AgentDefaultArgsInput } from './launch-settings/AgentLaunchDefaultsEditor'
import { NativeChatSessionOptionRows } from '../native-chat/session/options/controls/NativeChatSessionOptionRows'
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'
@@ -1,4 +1,4 @@
import { expect, it } from 'vitest'
import { expect, it, onTestFinished, vi } from 'vitest'
import {
createAgentPickerInventorySource,
currentAgentPickerAcquisition,
@@ -87,8 +87,16 @@ it('settles closed catalog reads and resumes their refresh when the picker reope
models: [model('saved')]
})
await expect
.poll(() => currentAgentPickerAcquisition('closed-catalog')?.map((entry) => entry.catalogRead))
.toEqual(['settled', 'settled'])
.poll(() => currentAgentPickerAcquisition('closed-catalog')?.map((entry) => entry.catalog))
.toEqual([
{ origin: 'unknown', listingInProgress: true },
{
origin: 'probe',
fetchedAt: 1,
listingInProgress: true,
models: [{ id: 'saved', label: 'saved', isDefault: false, efforts: [] }]
}
])
const stopReopened = observeAgentPickerAcquisition('closed-catalog', entries, reads, observer)
expect(published.map((entry) => entry.catalogRead)).toEqual(['pending', 'pending'])
@@ -190,3 +198,99 @@ it('admits the selected agent’s usable CLI job before another agent after its
other.resolve({ origin: 'unknown' })
}
})
it('waits again only when a wait outlasted its budget, then stops once the listing has ended', async () => {
vi.useFakeTimers()
onTestFinished(() => {
vi.useRealTimers()
})
const saved = { origin: 'probe' as const, fetchedAt: 1, models: [model('saved')] }
// A floating folder's quick read always reports a listing; only waiting reads know it ended.
const waits = [{ ...saved, waitExpired: true as const }, saved]
const reads: boolean[] = []
let published: AgentPickerEntry[] = []
const stop = observeAgentPickerAcquisition(
'outlasting-listing',
[codex],
{
catalog: async (_entry, waitForListing) => {
reads.push(waitForListing)
return waitForListing ? (waits.shift() ?? saved) : { ...saved, listingInProgress: true }
},
support: async () => undefined
},
{ selected: () => undefined, publish: (entries) => (published = entries) }
)
try {
await vi.advanceTimersByTimeAsync(60_000)
expect(reads).toEqual([false, true, true])
expect(published[0]).toMatchObject({ catalogRead: 'settled', catalog: saved })
} finally {
stop()
}
})
it('publishes every saved catalog while earlier refreshes are still pending', async () => {
const fresh = Promise.withResolvers<AgentPickerEntry['catalog']>()
const entries: AgentPickerEntry[] = [
codex,
{ ...codex, agent: 'claude', label: 'Claude', rows: [{ agent: 'claude', kind: 'cli' }] },
{ ...codex, agent: 'gemini', label: 'Gemini', rows: [{ agent: 'gemini', kind: 'cli' }] }
]
let published: AgentPickerEntry[] = []
const stop = observeAgentPickerAcquisition(
'independent-saved-catalogs',
entries,
{
catalog: async (entry, waitForListing) =>
waitForListing
? fresh.promise
: {
origin: 'probe',
fetchedAt: 1,
listingInProgress: true,
models: [model(entry.agent)]
},
support: async () => undefined
},
{ selected: () => 'codex', publish: (next) => (published = next) }
)
try {
await expect
.poll(() => published.map((entry) => entry.catalog))
.toMatchObject([
{ models: [{ id: 'codex' }] },
{ models: [{ id: 'claude' }] },
{ models: [{ id: 'gemini' }] }
])
} finally {
stop()
fresh.resolve({ origin: 'probe', fetchedAt: 2, models: [model('fresh')] })
}
})
it('keeps an unflagged saved catalog provisional when its read fails', async () => {
const fresh = Promise.withResolvers<AgentPickerEntry['catalog']>()
let published: AgentPickerEntry[] = []
const stop = observeAgentPickerAcquisition(
'failed-unflagged-catalog',
[{ ...codex, catalog: { origin: 'probe', fetchedAt: 1, models: [model('saved')] } }],
{ catalog: () => fresh.promise, support: async () => undefined },
{ selected: () => undefined, publish: (next) => (published = next) }
)
try {
expect(published[0]).toMatchObject({
catalogRead: 'pending',
catalog: { models: [{ id: 'saved' }] }
})
fresh.reject(new Error('refresh failed'))
await expect
.poll(() => published[0])
.toMatchObject({
catalogRead: 'failed',
catalog: { models: [{ id: 'saved' }] }
})
} finally {
stop()
}
})
@@ -19,6 +19,7 @@ import type {
/** Pending local IPC outlives observers; matching menus must retain its physical owner. */
const pending = new Map<string, AgentPickerAcquisition>()
type ReadKind = 'catalog' | 'refresh' | 'support'
type SupportRead = {
state: 'queued' | 'pending' | 'settled'
value?: AgentPickerEntry['structured']
@@ -28,9 +29,8 @@ class AgentPickerAcquisition {
readonly observers = new Set<Observer>()
entries: AgentPickerEntry[]
settingsPending = false
private outstanding = { catalog: 0, support: 0 }
private queued: Record<'catalog' | 'support', Set<number>>
private deferredCatalogs = new Set<number>()
private outstanding = { catalog: 0, refresh: 0, support: 0 }
private queued: Record<ReadKind, Set<number>>
private supports = new Map<number, SupportRead>()
private jobs: AgentPickerCatalogJob[]
private defaults: AgentPickerEntry[]
@@ -54,6 +54,7 @@ class AgentPickerAcquisition {
}
this.queued = {
catalog: new Set(this.jobs.map((_, index) => index)),
refresh: new Set(),
support: new Set(this.supports.keys())
}
}
@@ -84,9 +85,9 @@ class AgentPickerAcquisition {
const view = agentPickerSourceView(this.entries[job.index], job.source)
if (
view.catalogRead !== 'pending' &&
(this.deferredCatalogs.has(index) ||
view.catalog.origin === 'unknown' ||
(view.catalog.origin === 'unknown' ||
view.catalogRead === 'failed' ||
view.catalogRead === 'unsupported' ||
view.catalog.unavailable !== undefined ||
view.catalog.listingInProgress)
) {
@@ -106,9 +107,13 @@ class AgentPickerAcquisition {
}
this.entries = this.project()
}
const stopDemand = observer.subscribeDemand?.(() => this.admit('catalog'))
const stopDemand = observer.subscribeDemand?.(() => {
this.admit('catalog')
this.admit('refresh')
})
observer.publish(this.entries)
this.admit('catalog')
this.admit('refresh')
this.admit('support')
return () => {
stopDemand?.()
@@ -174,28 +179,26 @@ class AgentPickerAcquisition {
})
}
private async readCatalog(entry: AgentPickerEntry, index: number) {
this.deferredCatalogs.delete(index)
private async readCatalog(entry: AgentPickerEntry, index: number, waitForListing: boolean) {
const job = this.jobs[index]
const saved = await this.reads.catalog(entry, false, job.source)
if (!saved?.listingInProgress) {
return saved
const catalog = await this.reads.catalog(entry, waitForListing, job.source)
// An open picker waits on a running listing, and again when a wait used its whole budget.
const refresh =
this.observers.size > 0 &&
(waitForListing ? catalog?.waitExpired : catalog?.listingInProgress) === true
if (refresh) {
this.queued.refresh.add(index)
}
if (saved.origin !== 'unknown') {
this.entries = updateAgentPickerCatalog(this.entries, job, { catalog: saved })
this.publish()
}
if (!this.observers.size) {
this.deferredCatalogs.add(index)
return saved
}
return this.reads.catalog(entry, true, job.source)
this.entries = updateAgentPickerCatalog(this.entries, job, {
...(catalog ? { catalog } : {}),
catalogRead: !catalog ? 'failed' : refresh ? 'pending' : 'settled'
})
}
private admit(kind: 'catalog' | 'support') {
private admit(kind: ReadKind) {
while (this.observers.size && this.outstanding[kind] < 2 && this.queued[kind].size) {
const usable = [...this.queued[kind]].filter((index) => {
if (kind !== 'catalog') {
if (kind === 'support') {
return true
}
const job = this.jobs[index],
@@ -214,7 +217,7 @@ class AgentPickerAcquisition {
const index =
usable.find((index) =>
priorities.includes(
this.entries[kind === 'catalog' ? this.jobs[index].index : index].agent
this.entries[kind !== 'support' ? this.jobs[index].index : index].agent
)
) ?? usable[0]
if (index === undefined) {
@@ -222,35 +225,24 @@ class AgentPickerAcquisition {
}
this.queued[kind].delete(index)
this.outstanding[kind]++
const entry = this.entries[kind === 'catalog' ? this.jobs[index].index : index]
const entry = this.entries[kind !== 'support' ? this.jobs[index].index : index]
if (kind === 'support') {
this.supports.set(index, { state: 'pending' })
}
const read =
kind === 'catalog'
? this.readCatalog(entry, index)
.then((catalog) => {
const resume = this.deferredCatalogs.has(index) && this.observers.size > 0
if (resume) {
this.queued.catalog.add(index)
}
this.entries = updateAgentPickerCatalog(this.entries, this.jobs[index], {
...(catalog ? { catalog } : {}),
catalogRead: resume ? 'pending' : 'settled'
})
})
.catch((error: unknown) => {
const unsupported =
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error.code === 'method_not_found' ||
error.code === 'structured_agent_session_unsupported' ||
error.code === 'forbidden')
this.entries = updateAgentPickerCatalog(this.entries, this.jobs[index], {
catalogRead: unsupported ? 'unsupported' : 'failed'
})
kind !== 'support'
? this.readCatalog(entry, index, kind === 'refresh').catch((error: unknown) => {
const unsupported =
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error.code === 'method_not_found' ||
error.code === 'structured_agent_session_unsupported' ||
error.code === 'forbidden')
this.entries = updateAgentPickerCatalog(this.entries, this.jobs[index], {
catalogRead: unsupported ? 'unsupported' : 'failed'
})
})
: this.reads
.support(entry)
.catch(() => undefined)
@@ -264,6 +256,9 @@ class AgentPickerAcquisition {
this.outstanding[kind]--
this.publish()
this.admit(kind)
if (kind === 'catalog') {
this.admit('refresh')
}
this.retire()
})
}
@@ -274,6 +269,7 @@ class AgentPickerAcquisition {
!this.observers.size &&
!this.settingsPending &&
!this.outstanding.catalog &&
!this.outstanding.refresh &&
!this.outstanding.support
) {
pending.delete(this.key)
@@ -54,11 +54,13 @@ export function agentPickerModelCatalogReads(input: {
return {
catalog: async (
entry: AgentPickerEntry,
_wait = false,
waitForListing = false,
source: ModelCatalogSource = 'structured'
) =>
resolveScope(entry, source).then((scope) =>
scope ? hostModelMenuCatalog(scope).read(source === 'cli') : { origin: 'unknown' as const }
scope
? hostModelMenuCatalog(scope).read(source === 'cli', waitForListing)
: { origin: 'unknown' as const }
),
observeCatalog: (
entry: AgentPickerEntry,
@@ -0,0 +1,93 @@
import { expect, it, vi } from 'vitest'
import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker'
import type { AgentSessionModelCatalogResult } from '../../../../shared/agent-session/agent-session-wire'
const transport = vi.hoisted(() => ({ call: vi.fn() }))
vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: transport.call
}))
import { agentPickerModelCatalogReads } from './agent-launch-picker-host-reads'
import { observeAgentPickerAcquisition } from './agent-launch-picker-acquisition'
import { resetHostModelCatalogSnapshotsForTests } from '@/runtime/native-chat/model-catalogs/host-model-catalog-snapshots'
it('publishes all saved source catalogs before waiting, and follows an expired wait through the host adapter', async () => {
resetHostModelCatalogSnapshotsForTests()
const expired = Promise.withResolvers<AgentSessionModelCatalogResult>()
const fresh = Promise.withResolvers<AgentSessionModelCatalogResult>()
let codexWaited = false
transport.call.mockImplementation((_target, _method, params) => {
if (params.waitForListing) {
if (params.agent === 'codex' && !codexWaited) {
codexWaited = true
return expired.promise
}
return fresh.promise
}
return Promise.resolve({
origin: 'probe',
fetchedAt: 1,
listingInProgress: true,
listingNamesConfiguredModel: false,
models: [{ id: `${params.agent}-saved`, label: 'Saved', isDefault: false, efforts: [] }]
})
})
const entries: AgentPickerEntry[] = (['codex', 'claude', 'gemini'] as const).map((agent) => ({
agent,
label: agent,
rows: [],
surfaces: ['chat'],
defaultSurface: 'chat',
terminal: {},
structured: {},
catalog: { origin: 'unknown' }
}))
let published = entries
const stop = observeAgentPickerAcquisition(
'queued-waits-through-host-owner',
entries,
{
...agentPickerModelCatalogReads({
target: { kind: 'local' },
nativeRuntime: true,
selector: 'id:queued',
settings: {}
}),
support: async () => undefined
},
{ selected: () => 'codex', publish: (next) => (published = next) }
)
try {
await expect
.poll(() =>
published.map((entry) =>
entry.catalog.origin !== 'unknown' ? entry.catalog.models[0]?.id : undefined
)
)
.toEqual(['codex-saved', 'claude-saved', 'gemini-saved'])
expired.resolve({ origin: 'unknown', listingInProgress: true, waitExpired: true })
await expect
.poll(() =>
transport.call.mock.calls
.filter(([, , params]) => params.agent === 'codex')
.map(([, , params]) => params.waitForListing ?? false)
)
.toEqual([false, true, true])
fresh.resolve({
origin: 'probe',
fetchedAt: 2,
listingNamesConfiguredModel: false,
models: [{ id: 'fresh', label: 'Fresh', isDefault: false, efforts: [] }]
})
await expect
.poll(() => published.map((entry) => entry.catalogRead))
.toEqual(['settled', 'settled', 'settled'])
expect(
published.map((entry) =>
entry.catalog.origin !== 'unknown' ? entry.catalog.models[0]?.id : undefined
)
).toEqual(['fresh', 'fresh', 'fresh'])
} finally {
stop()
expired.resolve({ origin: 'unknown' })
fresh.resolve({ origin: 'unknown' })
}
})
@@ -0,0 +1,144 @@
import { expect, it } from 'vitest'
import type { AgentPickerRetainedSetup } from '../../../../shared/agent-launch/picker/agent-launch-picker-authority'
import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker'
import { retireAgentPickerSetups } from './agent-launch-picker-retirement'
const entry: AgentPickerEntry = {
agent: 'codex',
label: 'Codex',
rows: [{ agent: 'codex', kind: 'cli' }],
surfaces: ['terminal'],
defaultSurface: 'terminal',
terminal: {},
structured: {},
catalog: {
origin: 'probe',
fetchedAt: 1,
models: [{ id: 'saved', label: 'Saved', isDefault: false, efforts: [] }]
}
}
it('preserves edited presets until a completed catalog confirms their model or effort was removed', () => {
const setups = new Map<string, AgentPickerRetainedSetup>([
[
'missing-model',
{
target: undefined,
agent: 'codex',
preset: { model: 'fresh' },
source: undefined,
draft: {
agent: 'codex',
surface: 'terminal',
choices: { model: 'saved' },
arguments: '--add-dir model-edits'
},
active: false
}
],
[
'missing-effort',
{
target: undefined,
agent: 'codex',
preset: { model: 'saved', effort: 'high' },
source: undefined,
draft: {
agent: 'codex',
surface: 'terminal',
choices: { model: 'saved', options: { effort: 'low' } },
arguments: '--add-dir effort-edits'
},
active: false
}
]
])
for (const catalogRead of ['pending', 'failed', 'unsupported'] as const) {
retireAgentPickerSetups([{ ...entry, catalogRead }], setups, undefined, 'select')
expect([...setups.values()].map(({ draft }) => draft.arguments)).toEqual([
'--add-dir model-edits',
'--add-dir effort-edits'
])
}
retireAgentPickerSetups(
[
{
...entry,
catalogRead: 'settled',
catalog: {
origin: 'probe',
fetchedAt: 2,
models: [
{ id: 'fresh', label: 'Fresh', isDefault: false, efforts: [] },
{
id: 'saved',
label: 'Saved',
isDefault: false,
efforts: [{ value: 'high', label: 'High' }]
}
]
}
}
],
setups,
undefined,
'select'
)
expect([...setups.values()].map(({ draft }) => draft.arguments)).toEqual([
'--add-dir model-edits',
'--add-dir effort-edits'
])
retireAgentPickerSetups([{ ...entry, catalogRead: 'settled' }], setups, undefined, 'select')
expect([...setups.keys()]).toEqual([])
})
it('retires a terminal preset only after that source completes, independently of its chat catalog', () => {
const pending: AgentPickerEntry = {
...entry,
agent: 'antigravity',
surfaces: ['chat', 'terminal'],
defaultSurface: 'chat',
sourceCatalogs: {
cli: {
catalog: { origin: 'probe', fetchedAt: 1, models: [] },
catalogRead: 'pending'
}
}
}
const setups = new Map<string, AgentPickerRetainedSetup>([
[
'terminal',
{
target: undefined,
agent: 'antigravity',
preset: { model: 'saved' },
source: undefined,
draft: {
agent: 'antigravity',
surface: 'terminal',
choices: { model: 'saved' },
arguments: '--kept'
},
active: false
}
]
])
retireAgentPickerSetups([pending], setups, undefined, 'select')
expect(setups.get('terminal')?.draft.arguments).toBe('--kept')
retireAgentPickerSetups(
[
{
...pending,
sourceCatalogs: {
cli: { catalog: { origin: 'probe', fetchedAt: 2, models: [] }, catalogRead: 'settled' }
}
}
],
setups,
undefined,
'select'
)
expect([...setups.keys()]).toEqual([])
})
@@ -1,5 +1,8 @@
import { agentPickerCatalogView } from '../../../../shared/agent-launch/picker/agent-launch-picker-source'
import type { AgentPickerRetainedSetup } from '../../../../shared/agent-launch/picker/agent-launch-picker-authority'
import {
agentPickerCatalogAuthoritative,
type AgentPickerRetainedSetup
} from '../../../../shared/agent-launch/picker/agent-launch-picker-authority'
import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker'
import { launchDraftSources } from '../native-chat/drafts/native-chat-launch-draft-source'
@@ -28,9 +31,10 @@ export function retireAgentPickerSetups(
const entry = entriesByKey.get(
currentKey ?? JSON.stringify([retained.target?.key, retained.agent])
)
const catalog = entry && agentPickerCatalogView(entry, retained.draft.surface).catalog
const view = entry && agentPickerCatalogView(entry, retained.draft.surface)
const catalog = view && agentPickerCatalogAuthoritative(view) ? view.catalog : undefined
let models = catalog && memberships.get(catalog)
if (!models && catalog && catalog.origin !== 'unknown' && !catalog.listingInProgress) {
if (!models && catalog) {
models = new Map(
catalog.models.map((model) => [
model.id,
@@ -1,3 +1,4 @@
import { agentPickerCatalogAuthoritative } from '../../../../shared/agent-launch/picker/agent-launch-picker-authority'
import { agentPickerCatalogView } from '../../../../shared/agent-launch/picker/agent-launch-picker-source'
import { agentPickerModelMenu } from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog'
import {
@@ -264,13 +265,7 @@ export function agentLaunchSetupCatalogState(
agent: entry.label
})
: null
const canSearch =
hasModels &&
entry.catalog.origin !== 'unknown' &&
!entry.catalog.listingInProgress &&
entry.catalogRead !== 'pending' &&
entry.catalogRead !== 'failed' &&
entry.catalogRead !== 'unsupported'
const canSearch = hasModels && agentPickerCatalogAuthoritative(entry)
return { hasModels, catalogPending, catalogMessage, canSearch }
}
@@ -1,4 +1,4 @@
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import React from 'react'
import { Pencil } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import React from 'react'
import { Clock } from 'lucide-react'
import { cn } from '@/lib/utils'
@@ -1,5 +1,5 @@
import type { AutomationRun } from '../../../../shared/automations/history/automation-run'
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event'
export type AutomationRunHistoryArrowKey = 'ArrowUp' | 'ArrowDown'
@@ -2,7 +2,7 @@ import { useEffect } from 'react'
import { hasVisibleOverlay } from '@/lib/visible-overlay'
import type { AutomationsPageLocalState } from './use-automations-page-local-state'
import type { AutomationsPageStoreState } from './use-automations-page-store-state'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
export function useAutomationsPageEscape({
store,
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import React, { useCallback, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Check, X } from 'lucide-react'
@@ -1,4 +1,4 @@
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import { useState } from 'react'
import {
ChevronDown,
@@ -8,7 +8,7 @@ import {
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
import { imageCopyFailedMessage } from '@/lib/clipboard-image-copy'
import { imageCopyFailedMessage } from '@/lib/clipboard/images/clipboard-image-copy'
import type {
BrowserPageGrabAnnotations,
BrowserPageGrabToastState
@@ -1,4 +1,4 @@
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import { useEffect, useState } from 'react'
import { CornerDownLeft, MessageSquarePlus } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react
import { translate } from '@/i18n/i18n'
import { useMountedRef } from '@/hooks/useMountedRef'
import { useAppStore } from '@/store'
import { imageCopyFailedMessage } from '@/lib/clipboard-image-copy'
import { imageCopyFailedMessage } from '@/lib/clipboard/images/clipboard-image-copy'
import {
isBrowserAnnotationPageFull,
type BrowserAnnotationIntent,
@@ -7,7 +7,7 @@ import type {
import { useMountedRef } from '@/hooks/useMountedRef'
import { translate } from '@/i18n/i18n'
import { isEditableKeyboardTarget } from '../host-guest/browser-keyboard'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { useGuestEscape } from '../host-guest/use-guest-escape'
export type GrabModeState = 'idle' | 'armed' | 'awaiting' | 'confirming' | 'error'
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import { useCallback, useEffect, useRef, useState } from 'react'
import { ChevronUp, ChevronDown, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -9,7 +9,7 @@ import {
} from 'react'
import { createPortal } from 'react-dom'
import type { BrowserPageContextMenuState } from '../describe-page/browser-page-types'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { BrowserPageContextMenuItems } from './browser-page-context-menu-items'
export function BrowserPageContextMenu({
@@ -1,5 +1,5 @@
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event'
import { requestBrowserFocus } from '../host-guest/browser-focus'
/** Escape in the bar, in the order of Chromium's OmniboxEditModel::OnEscapeKeyPressed. */
@@ -20,7 +20,7 @@ import { browserChromeShortcutOwnsEvent } from '../describe-page/browser-overlay
import type { BrowserChromeShortcutScope } from '../describe-page/browser-page-types'
import type { BrowserAddressBarSelection } from './browser-address-bar-edit-session'
import type { BrowserPageGuestFocus } from './browser-page-guest-focus'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { useBrowserHistoryShortcut } from '../history/use-browser-history-shortcut'
import { useWebviewDragPassthroughActive } from '../host-guest/use-webview-drag-passthrough-active'
@@ -4,7 +4,7 @@ import { useAppStore } from '@/store'
import { keybindingMatchesAction } from '../../../../../shared/keybindings'
import { browserChromeShortcutOwnsEvent } from '../describe-page/browser-overlay-shortcut-target'
import type { BrowserChromeShortcutScope } from '../describe-page/browser-page-types'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
export function useBrowserPageFindShortcuts({
browserTabId,
@@ -1,5 +1,5 @@
import { useCallback } from 'react'
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event'
import { useAppStore } from '@/store'
import type { BrowserAddressBarSuggestion } from '../assemble-chrome/browser-address-bar-suggestions'
@@ -1,7 +1,7 @@
import { useEffect } from 'react'
import { useAppStore } from '@/store'
import { getShortcutPlatform } from '@/hooks/useShortcutLabel'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { keybindingMatchesAction } from '../../../../../shared/keybindings'
import { browserChromeShortcutOwnsEvent } from '../describe-page/browser-overlay-shortcut-target'
import type { BrowserChromeShortcutScope } from '../describe-page/browser-page-types'
@@ -7,7 +7,7 @@ import type { BrowserChromeShortcutScope } from '../describe-page/browser-page-t
import type { GrabIntent } from '../../../../../shared/browser/element-grab/browser-grab-types'
import { isEditableKeyboardTarget } from './browser-keyboard'
import { useBrowserPageWebviewShortcuts } from './use-browser-page-webview-shortcuts'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
export function useBrowserPageKeyboardShortcuts({
browserTabId,
@@ -10,7 +10,7 @@ import {
publishBrowserPageSiteDisplay,
type BrowserPageZoomCommand
} from './browser-page-zoom'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
/** Handle chrome chords in the renderer and guest chords through main’s IPC; focused guests own a separate WebContents. */
export function useBrowserPageWebviewShortcuts({
@@ -16,7 +16,7 @@ import {
type RemoteBrowserPaneNotice,
type RemoteBrowserRuntimeTarget
} from './remote-browser-page-input-model'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
export function useRemoteBrowserPageContextMenu({
busy,
@@ -10,7 +10,7 @@ import {
REMOTE_BROWSER_FIND_UNAVAILABLE_NOTICE_ID,
type RemoteBrowserPaneNotice
} from './remote-browser-page-input-model'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
const FIND_UNAVAILABLE_NOTICE_MS = 4000
@@ -34,7 +34,7 @@ import { useDocPreviewWebviewHistory } from './doc-preview-webview-history'
import { useDocPreviewGuestFocus } from './use-doc-preview-guest-focus'
import { useDocPreviewGuestTools } from './use-doc-preview-guest-tools'
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
import { formatClipboardFilePath } from '@/lib/clipboard-file-path'
import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path'
import { getOpenFileRevealOwner } from '@/lib/reveal-in-file-manager'
import { subscribeDocPreviewExternalLinkConfirmation } from './doc-preview-external-link-confirmation'
@@ -1,7 +1,7 @@
import { Check, FileCode2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useClipboardTextCopyFeedback } from '@/hooks/use-clipboard-text-copy-feedback'
import { useClipboardTextCopyFeedback } from '@/hooks/clipboard/use-clipboard-text-copy-feedback'
import { useTranslate } from '@/i18n/use-translate'
import type { DocPreviewDocumentIdentity } from './doc-preview-document-identity'
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useVirtualizer } from '@tanstack/react-virtual'
import { Check, ChevronLeft, SearchIcon } from 'lucide-react'
@@ -1,4 +1,4 @@
import { gitGraphSupport, openGitGraph } from '@/lib/git-graph-tab'
import { gitGraphSupport, openGitGraph } from '@/lib/source-control/graph/git-graph-tab'
import {
GitGraph,
FileText,
@@ -11,7 +11,7 @@ import {
getLinkedWorkItemSuggestedName,
type LinkedWorkItemSummary
} from '@/lib/new-workspace'
import { buildLinearIssueLinkedWorkItem } from '@/lib/linear-linked-work-item'
import { buildLinearIssueLinkedWorkItem } from '@/lib/work-items/linear/linear-linked-work-item'
import type { Worktree } from '../../../../shared/worktree/types'
import {
haveConflictingTaskSourceAccounts,
@@ -8,7 +8,7 @@ import { jiraStatusForTarget } from '@/runtime/jira/runtime-jira-project-client'
import { ipcOrRuntimeTargetForHostId } from '@/runtime/rpc/targets/runtime-client-target'
import { gitLabApiFor } from '@/runtime/repository-gitlab/gitlab-owner-api'
import { resolveJiraSourceHostId } from '../../../../shared/jira/jira-source-host'
import { getJiraAccountLabel } from '@/lib/jira-account-label'
import { getJiraAccountLabel } from '@/lib/work-items/jira/jira-account-label'
import {
getRepoExecutionHostId,
parseExecutionHostId,
@@ -28,7 +28,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types'
import type { PaletteFilterState } from './palette-filter'
import { getTaskEligibleRepos } from '../task-page/task-page-default-repo-selection'
import { getRepoBackedProviderAvailability } from '../task-source-provider-availability'
import { getTaskPageRepoSourceContext } from '../../lib/task-repo-source-context'
import { getTaskPageRepoSourceContext } from '../../lib/work-items/task-repo-source-context'
import { searchJiraIssuesByKeyOrText } from '../jira-key-or-text-search'
import { bindTaskPageJiraItemSourceContext } from '../task-page/jira/task-page-jira-item-source-context'
import { makeCmdJTaskSearchResult, type CmdJTaskSearchResult } from './task-search-results'
@@ -28,7 +28,7 @@ import {
type ContextualTourFloatingPosition
} from './contextual-tour-floating-position'
import { useTranslate } from '@/i18n/use-translate'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { hasVisibleOverlay } from '@/lib/visible-overlay'
import { getMeasurableContextualTourTarget } from './contextual-tour-gate'
@@ -1,5 +1,5 @@
import { translate } from '@/i18n/i18n'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import type { ContextualTourStepId } from '../../../../shared/contextual-tours'
export type LocalizedContextualTourStepCopy = {
@@ -4,16 +4,10 @@ import '@testing-library/jest-dom/vitest'
import type { ITerminalOptions } from '@xterm/xterm'
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
TERMINAL_PASTE_CHUNK_MAX_BYTES,
TERMINAL_PASTE_DIRECT_MAX_BYTES
} from '@/components/terminal-pane/input/paste/terminal-paste-limits'
import '@/components/terminal-pane/input/paste/terminal-bracketed-paste'
import {
BRACKETED_PASTE_END,
BRACKETED_PASTE_START
} from '../../../../shared/terminal/input/terminal-bracketed-paste-text'
import { dispatchAppMenuPasteEvent } from '@/lib/app-menu-paste'
import { dispatchAppMenuPasteEvent } from '@/lib/clipboard/menu/app-menu-paste'
const terminalHarness = vi.hoisted(() => ({
instances: [] as {
@@ -117,7 +111,7 @@ vi.mock('@/components/terminal-pane/input/terminal-user-input-signal', () => ({
vi.mock('@/hooks/theme/use-system-prefers-dark', () => ({
useSystemPrefersDark: () => false
}))
vi.mock('@/lib/shortcut-platform', () => ({
vi.mock('@/lib/keyboard/shortcut-platform', () => ({
getShortcutPlatform: () => platformState.value
}))
vi.mock('@/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder', () => ({
@@ -238,58 +232,4 @@ describe('AgentTerminalPreview clipboard routes', () => {
expect(terminal.paste).not.toHaveBeenCalled()
expect(input).not.toHaveBeenCalled()
})
it('streams large pastes as bounded IPC payloads instead of one renderer-blocking write', async () => {
const encoder = new TextEncoder()
const multibytePrefix = '😀'.repeat(TERMINAL_PASTE_DIRECT_MAX_BYTES / 4 + 1)
const largePaste = `${multibytePrefix}\r\nnext\n`
const expectedPaste = `${multibytePrefix}\rnext\r`
readClipboardText.mockResolvedValueOnce(largePaste)
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
focusInsidePreview(view.container)
act(() => {
dispatchAppMenuPasteEvent()
})
const expectedChunks = Math.ceil(
encoder.encode(expectedPaste).byteLength / TERMINAL_PASTE_CHUNK_MAX_BYTES
)
await waitFor(() => expect(input).toHaveBeenCalledTimes(expectedChunks))
const payloads = input.mock.calls.map(([, data]) => data as string)
expect(terminal.paste).not.toHaveBeenCalled()
expect(payloads.join('')).toBe(expectedPaste)
expect(
payloads.every(
(payload) => encoder.encode(payload).byteLength <= TERMINAL_PASTE_CHUNK_MAX_BYTES
)
).toBe(true)
})
it('closes a bracketed large paste when focus changes between chunks', async () => {
readClipboardText.mockResolvedValueOnce('x'.repeat(TERMINAL_PASTE_DIRECT_MAX_BYTES + 1))
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
terminal.modes.bracketedPasteMode = true
focusInsidePreview(view.container)
const outsideInput = document.createElement('input')
view.container.appendChild(outsideInput)
input.mockImplementationOnce(async () => {
outsideInput.focus()
return true
})
act(() => {
dispatchAppMenuPasteEvent()
})
await waitFor(() => expect(input).toHaveBeenCalledTimes(2))
expect(input.mock.calls.map(([, data]) => data)).toEqual([
BRACKETED_PASTE_START,
BRACKETED_PASTE_END
])
})
})
@@ -109,7 +109,7 @@ vi.mock('@/components/terminal-pane/input/terminal-user-input-signal', () => ({
vi.mock('@/hooks/theme/use-system-prefers-dark', () => ({
useSystemPrefersDark: () => false
}))
vi.mock('@/lib/shortcut-platform', () => ({
vi.mock('@/lib/keyboard/shortcut-platform', () => ({
getShortcutPlatform: () => platformState.value
}))
vi.mock('@/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder', () => ({
@@ -384,28 +384,4 @@ describe('AgentTerminalPreview', () => {
expect(terminalHarness.userInputDispose).toHaveBeenCalledTimes(1)
expect(unsubscribe).toHaveBeenCalledWith('pty-1')
})
it('delays repeated capture after an overflow and cancels the retry on unmount', async () => {
vi.useFakeTimers()
connect.mockResolvedValue({
snapshot: { data: 'screen', cols: 80, rows: 24, seq: 1 },
replay: [],
resyncRequired: true
})
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
await vi.waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
const terminal = terminalHarness.instances[0]!
expect(connect).toHaveBeenCalledTimes(1)
act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback()))
await vi.advanceTimersByTimeAsync(149)
expect(connect).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(connect).toHaveBeenCalledTimes(2)
act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback()))
view.unmount()
await vi.advanceTimersByTimeAsync(150)
expect(connect).toHaveBeenCalledTimes(2)
})
})
@@ -1,5 +1,5 @@
import { useAppMenuPaste } from '@/hooks/useAppMenuPaste'
import { useAppMenuSelectionActions } from '@/hooks/useAppMenuSelectionActions'
import { useAppMenuPaste } from '@/hooks/clipboard/menu/useAppMenuPaste'
import { useAppMenuSelectionActions } from '@/hooks/app-commands/useAppMenuSelectionActions'
import { AgentKanbanBoard } from './AgentKanbanBoard'
import { useDashboardSnapshot } from './useDashboardSnapshot'
import { useAgentDashboardTelemetry } from './use-agent-dashboard-telemetry'
@@ -54,86 +54,6 @@ export function installPreviewDomFixture(): () => void {
return () => style.remove()
}
export function observePreviewListeners(elements: HTMLElement[]) {
type Registration = {
target: EventTarget
type: string
listener: EventListenerOrEventListenerObject
capture: boolean
wrapped: EventListener
}
const active = new Set<Registration>()
let callbacks = 0
const spies = [document, window, ...elements].flatMap((target) => {
const nativeAdd: EventTarget['addEventListener'] = target.addEventListener
const nativeRemove: EventTarget['removeEventListener'] = target.removeEventListener
const add = vi.spyOn(target, 'addEventListener').mockImplementation(function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions
) {
if (!listener) {
return
}
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture)
if (
Array.from(active).some(
(r) =>
r.target === this && r.type === type && r.listener === listener && r.capture === capture
)
) {
return
}
const wrapped: EventListener = function (this: EventTarget, event) {
if (this === document || this === window) {
callbacks++
}
if (typeof listener === 'function') {
listener.call(this, event)
} else {
listener.handleEvent(event)
}
}
active.add({ target: this, type, listener, capture, wrapped })
nativeAdd.call(this, type, wrapped, options)
})
const remove = vi.spyOn(target, 'removeEventListener').mockImplementation(function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | EventListenerOptions
) {
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture)
const registration = Array.from(active).find(
(r) =>
r.target === this && r.type === type && r.listener === listener && r.capture === capture
)
if (registration) {
nativeRemove.call(this, type, registration.wrapped, options)
active.delete(registration)
} else {
nativeRemove.call(this, type, listener, options)
}
})
return [add, remove]
})
return {
active,
get callbacks() {
return callbacks
},
resetCallbacks: () => {
callbacks = 0
},
restore: () => {
for (const spy of spies) {
spy.mockRestore()
}
}
}
}
export function mountPreviewLinkInteraction(
source: DashboardPreviewLinkSource,
readSettings: () => GlobalSettings | null,
@@ -8,17 +8,14 @@ import {
} from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { RemoteRuntimeMultiplexedTerminalCallbacks } from '@/runtime/hosted-terminals/streams/remote-terminal-stream-contracts'
import { TooltipProvider } from '@/components/ui/tooltip'
import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
import { resetRemoteRuntimeTerminalPreviewSessionsForTests } from './remote-runtime-terminal-preview-api'
import {
installPreviewDomFixture,
mountPreviewLinkInteraction
} from './dashboard-preview-dom-test-fixture'
import { verifyPreviewLinkPopulation } from './dashboard-preview-link-population-test-fixture'
import { toast } from 'sonner'
import { runtimeStatuses } from '@/store/slices/browser/browser-slice-test-harness'
import type { openStandaloneTerminal } from '../standalone-terminal/open-standalone-terminal'
import { getDefaultSettings } from '../../../../shared/constants'
@@ -33,14 +30,12 @@ import {
registerWorkspaceHttpLinkBrowserOpener
} from '@/lib/browser/navigation/http-link-routing'
import { openWorkspaceBrowserTabForLink } from '@/lib/browser/workspace/workspace-browser-tab-open'
import { AgentTerminalPreview } from './AgentTerminalPreview'
import { terminalPreviewApiFor } from './terminal-preview-api'
import { AgentKanbanBoard } from './AgentKanbanBoard'
import type { DashboardCard } from '../../../../shared/dashboard-snapshot'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import type { DashboardPreviewLinkSource } from './dashboard-preview-http-actions'
const mocks = vi.hoisted(() => ({
getState: vi.fn(),
@@ -76,9 +71,7 @@ vi.mock(
})
})
)
function render(ui: React.ReactElement) {
return renderWithoutApp(ui, { wrapper: TooltipProvider })
}
vi.mock('@/store', () => ({
useAppStore: Object.assign(
(selector: (state: ReturnType<typeof mocks.getState>) => unknown) => selector(mocks.getState()),
@@ -88,7 +81,7 @@ vi.mock('@/store', () => ({
vi.mock('@/hooks/theme/use-system-prefers-dark', () => ({
useSystemPrefersDark: () => false
}))
vi.mock('@/lib/shortcut-platform', () => ({ getShortcutPlatform: () => 'linux' }))
vi.mock('@/lib/keyboard/shortcut-platform', () => ({ getShortcutPlatform: () => 'linux' }))
vi.mock('sonner', () => ({
toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn() }
}))
@@ -215,104 +208,6 @@ async function output(data: string, ptyId = 'pty-1') {
}
const osc = `\x1b]8;;${URL_TO_OPEN}\x07hidden label\x1b]8;;\x07`
it.each(['actions', 'open'] as const)(
'retains the provider-owned hidden OSC target across unrelated live row output for %s and context',
async (behavior) => {
store.setState((state) => ({
settings: { ...state.settings!, terminalLinkClickBehavior: behavior }
}))
const view = render(<AgentTerminalPreview ptyId="pty-1" linkSource={source} />)
await waitFor(() => screenFor(view.container))
await output(`\x1b[?1000h\x1b[?1006h${osc}\x1b[3;1Hprogress 1`)
const screen = screenFor(view.container)
const terminal = view.container.querySelector('.xterm')!
pointer(screen, 'mousemove', { buttons: 0 })
await waitFor(() => expect(terminal.getAttribute('title')).toBe(URL_TO_OPEN))
await output('\x1b[3;1Hprogress 2')
await waitFor(() => expect(view.container.textContent).toContain('progress 2'))
expect(terminal.getAttribute('title')).toBe(URL_TO_OPEN)
// Keep the pointer stationary: the retained provider does not emit another hover.
pointer(screen, 'mousedown')
pointer(screen, 'mouseup')
if (behavior === 'actions') {
const system = await view.findByRole('button', { name: /System Browser/ })
expect(document.querySelector('[data-terminal-link-destination]')?.textContent).toBe(
URL_TO_OPEN
)
fireEvent.click(system)
}
await waitFor(() => expect(openUrl).toHaveBeenCalledExactlyOnceWith(URL_TO_OPEN))
expect(input.mock.calls.map(([, data]) => data)).toEqual([])
await output('\x1b[3;1Hprogress 3')
const context = pointer(screen, 'contextmenu', { button: 2, buttons: 0 })
expect(context.defaultPrevented).toBe(true)
const copy = await view.findByRole('button', { name: 'Copy link' })
expect(document.querySelector('[data-terminal-link-destination]')?.textContent).toBe(
URL_TO_OPEN
)
fireEvent.click(copy)
await waitFor(() => expect(window.api.ui.writeClipboardText).toHaveBeenCalledWith(URL_TO_OPEN))
pointer(screen, 'mouseleave', { buttons: 0 })
expect(terminal.hasAttribute('title')).toBe(false)
}
)
function seedRemoteWorkspace(
hostId: ExecutionHostId,
environmentId: string,
streaming: boolean
): void {
store.setState((state) => ({
activeWorkspaceExecutionHostId: hostId,
worktreesByRepo: {
repo1: state.worktreesByRepo.repo1!.map((row) => ({
...row,
hostId,
runtimeOwnerEnvironmentId: environmentId
}))
},
unifiedTabsByWorktree: {
[WORKSPACE]: state.unifiedTabsByWorktree[WORKSPACE]!.map((tab) => ({
...tab,
executionHostId: hostId
}))
},
runtimeStatusByEnvironmentId: new Map([
[environmentId, runtimeStatuses(streaming ? ['browser.screencast.v1'] : []).get('env-1')!]
]),
settings: { ...state.settings!, browserClientHostedRemoteEnabled: false, openLinksInApp: true }
}))
}
it('gives one useful refusal when a real saved chooser action loses runtime browser eligibility', async () => {
const hostId = 'runtime:e'
const ptyId = 'remote:e@@handle-1'
const linkSource = {
...source,
executionHostId: hostId,
ptyId
} satisfies DashboardPreviewLinkSource
const foreground = vi.fn()
seedRemoteWorkspace(hostId, 'e', true)
const props = { ptyId, linkSource, onBrowserForeground: foreground }
const view = render(<AgentTerminalPreview {...props} />)
await waitFor(() => screenFor(view.container))
await output(osc, ptyId)
const screen = screenFor(view.container)
pointer(screen, 'mousedown')
pointer(screen, 'mouseup')
const savedAction = await view.findByRole('button', { name: /Orca Browser/ })
// Actual failed-status refresh shape, after the real request has captured its action.
store.setState({ runtimeStatusByEnvironmentId: new Map([['e', { status: null, checkedAt: 2 }]]) })
fireEvent.click(savedAction)
await waitFor(() => expect(toast.error).toHaveBeenCalledExactlyOnceWith('Unable to open URL.'))
expect(document.querySelector('[data-link-action-popover]')).toBeNull()
expect(store.getState().browserPagesByWorkspace).toEqual({})
expect(openUrl).not.toHaveBeenCalled()
expect(foreground).not.toHaveBeenCalled()
expect(input.mock.calls.map(([, data]) => data)).toEqual([])
})
function mountedInteraction() {
return mountPreviewLinkInteraction(
source,
@@ -321,22 +216,6 @@ function mountedInteraction() {
)
}
it.each([10, 100])(
'bounds actual registration, document callbacks and target input/output at P=%s; reset/dispose leave zero adapter residue',
async (population) => {
await verifyPreviewLinkPopulation(
population,
source,
() => store.getState().settings,
(instance) => instances.push(instance),
osc,
URL_TO_OPEN,
pointer,
screenFor
)
}
)
it('retains actual boolean/Promise forwarding results and flushes unclaimed reports in order, with finite overflow and cleanup', async () => {
const preview = mountedInteraction()
const interaction = preview.install()
@@ -1,267 +0,0 @@
import { expect, vi } from 'vitest'
import { waitFor } from '@testing-library/react'
import { Terminal } from '@xterm/xterm'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import type { openStandaloneTerminal } from '../standalone-terminal/open-standalone-terminal'
import type { DashboardPreviewLinkSource } from './dashboard-preview-http-actions'
import {
mountPreviewLinkInteraction,
observePreviewListeners
} from './dashboard-preview-dom-test-fixture'
function observePreviewTimers() {
type NativeId = ReturnType<typeof window.setTimeout>
type Callback = Parameters<typeof window.setTimeout>[0]
type Record = {
callback: Callback
callbackId: number
name: string
delay: number | undefined
stack: string | undefined
id?: NativeId
executed: number
canceled: number
}
const records: Record[] = []
const callbackIds = new Map<Callback, number>()
const clears: Parameters<typeof window.clearTimeout>[0][] = []
let peakFallbacks = 0
const ownerOf = (record: Record) => {
if (
record.name === 'finishDeferredInput' &&
record.stack?.includes('terminal-link-pty-mouse-suppression.ts')
) {
return 'adapter-fallback'
}
if (
record.delay === 300000 &&
record.stack?.includes('/@xterm/xterm/') &&
record.stack.includes('_resetIdleTimer')
) {
return 'xterm-cursor-idle'
}
return 'unattributed'
}
const microtasks: { name: string; executed: boolean }[] = []
const nativeSet = window.setTimeout
const nativeClear = window.clearTimeout
const nativeQueue = globalThis.queueMicrotask
const set = vi.spyOn(window, 'setTimeout').mockImplementation(function (
this: Window,
callback,
delay,
...args
) {
let callbackId = callbackIds.get(callback)
if (callbackId === undefined) {
callbackId = callbackIds.size + 1
callbackIds.set(callback, callbackId)
}
const record: Record = {
callback,
callbackId,
name: typeof callback === 'function' ? callback.name : 'string',
delay,
stack: new Error('Preview timer owner registration').stack,
executed: 0,
canceled: 0
}
records.push(record)
const wrapped =
typeof callback === 'function'
? function (this: unknown, ...values: Parameters<Callback>) {
try {
return callback.apply(this, values)
} finally {
record.executed++
}
}
: callback
record.id = nativeSet.call(this, wrapped, delay, ...args)
peakFallbacks = Math.max(
peakFallbacks,
records.filter(
(r) => ownerOf(r) === 'adapter-fallback' && r.canceled === 0 && r.executed === 0
).length
)
return record.id
})
const clear = vi.spyOn(window, 'clearTimeout').mockImplementation(function (this: Window, id) {
clears.push(id)
for (const record of records) {
if (record.id === id) {
record.canceled++
}
}
return nativeClear.call(this, id)
})
const queue = vi.spyOn(globalThis, 'queueMicrotask').mockImplementation(function (
this: typeof globalThis,
callback
) {
const record = { name: callback.name, executed: false }
microtasks.push(record)
return nativeQueue.call(this, function (this: unknown) {
try {
return callback.call(this)
} finally {
record.executed = true
}
})
})
const summary = () => ({
timers: records.map((record, index) => ({
id: index + 1,
callbackId: record.callbackId,
name: record.name,
delay: record.delay,
stack: record.stack,
owner: ownerOf(record),
canceled: record.canceled,
executed: record.executed,
matchingClearCalls: clears.filter((id) => id === record.id).length
})),
microtasks
})
return {
records,
microtasks,
ownerOf,
get peakFallbacks() {
return peakFallbacks
},
summary,
restore: () => {
set.mockRestore()
clear.mockRestore()
queue.mockRestore()
}
}
}
export async function verifyPreviewLinkPopulation(
population: number,
source: DashboardPreviewLinkSource,
readSettings: () => GlobalSettings | null,
trackInstance: (instance: ReturnType<typeof openStandaloneTerminal>) => void,
osc: string,
uri: string,
pointer: (screen: HTMLElement, type: string, options?: MouseEventInit) => MouseEvent,
screenFor: (container: HTMLElement) => HTMLElement
) {
const baseline = Array.from({ length: population }, () =>
mountPreviewLinkInteraction(source, readSettings, trackInstance, false)
)
const defaultFirst = baseline[0]!
await new Promise<void>((resolve) =>
defaultFirst.instance.write(osc, { live: true, onDone: resolve })
)
const defaultScreen = screenFor(defaultFirst.container)
pointer(defaultScreen, 'mousemove', { buttons: 0 })
await waitFor(() =>
expect(defaultFirst.instance.terminal.element?.getAttribute('title')).toBe(uri)
)
const defaults = observePreviewTimers()
pointer(defaultScreen, 'mousedown')
pointer(defaultScreen, 'mouseup')
for (const preview of baseline) {
preview.instance.dispose()
}
await Promise.resolve()
const defaultSummary = defaults.summary()
expect(defaults.records.every((record) => defaults.ownerOf(record) === 'xterm-cursor-idle')).toBe(
true
)
expect(defaults.records.every((record) => record.canceled > 0 || record.executed > 0)).toBe(true)
defaults.restore()
const provider = vi.spyOn(Terminal.prototype, 'registerLinkProvider')
const previews = Array.from({ length: population }, () =>
mountPreviewLinkInteraction(source, readSettings, trackInstance)
)
expect(provider).toHaveBeenCalledTimes(population)
const observation = observePreviewListeners(previews.map((p) => p.instance.terminal.element!))
const { active } = observation
const interactions = previews.map((preview) => preview.install())
expect(provider).toHaveBeenCalledTimes(population)
expect(active.size).toBe(9 * population)
document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }))
expect(observation.callbacks).toBe(population)
observation.resetCallbacks()
const first = previews[0]!
await new Promise<void>((resolve) => first.instance.write(osc, { live: true, onDone: resolve }))
const gettersBefore = previews.map((p) => [
p.getSource.mock.calls.length,
p.getSettings.mock.calls.length
])
for (let i = 0; i < 10; i++) {
first.instance.terminal.input('typed')
}
expect(first.sink).toHaveBeenCalledTimes(10)
expect(previews.slice(1).every((p) => p.sink.mock.calls.length === 0)).toBe(true)
await new Promise<void>((resolve) =>
first.instance.write(' output', { live: true, onDone: resolve })
)
expect(
previews.map((p) => [p.getSource.mock.calls.length, p.getSettings.mock.calls.length])
).toEqual(gettersBefore)
expect(first.instance.terminal.buffer.active.getLine(0)?.translateToString(true)).toContain(
'output'
)
const screen = screenFor(first.container)
const timers = observePreviewTimers()
try {
pointer(screen, 'mousedown')
expect(active.size).toBeLessThanOrEqual(9 * population + 16)
pointer(screen, 'mouseup')
expect(first.request).toHaveBeenCalledOnce()
const adapterTimers = timers.records.filter(
(record) => timers.ownerOf(record) === 'adapter-fallback'
)
const nativeTimers = timers.records.filter(
(record) => timers.ownerOf(record) === 'xterm-cursor-idle'
)
expect(timers.records.some((record) => timers.ownerOf(record) === 'unattributed')).toBe(false)
expect(adapterTimers.length).toBeGreaterThan(0)
expect(adapterTimers.length).toBeLessThanOrEqual(3)
expect(timers.peakFallbacks).toBeLessThanOrEqual(1)
expect(nativeTimers).toHaveLength(defaultSummary.timers.length)
for (const interaction of interactions) {
interaction.dispose()
}
expect(adapterTimers.every((record) => record.canceled > 0)).toBe(true)
expect(active.size).toBe(0)
const reset = previews.map((p) => p.install())
expect(provider).toHaveBeenCalledTimes(population)
expect(active.size).toBe(9 * population)
for (const interaction of reset) {
interaction.dispose()
}
expect(active.size).toBe(0)
for (const preview of previews) {
preview.instance.dispose()
}
await Promise.resolve()
expect(nativeTimers.every((record) => record.canceled > 0 || record.executed > 0)).toBe(true)
const gestureClears = timers.microtasks.filter((task) => task.name === 'clear')
expect(gestureClears).toHaveLength(population)
expect(gestureClears.every((task) => task.executed)).toBe(true)
console.info(
'TIMER-OWNER-IDENTITIES',
JSON.stringify({
population,
default: defaultSummary,
adapter: timers.summary(),
peakFallbacks: timers.peakFallbacks
})
)
} finally {
for (const interaction of interactions) {
interaction.dispose()
}
for (const preview of previews) {
preview.instance.dispose()
}
timers.restore()
observation.restore()
}
}
@@ -1,10 +1,10 @@
import type { Terminal } from '@xterm/xterm'
import { isEditableTarget } from '@/lib/editable-target'
import { APP_MENU_PASTE_EVENT } from '@/lib/app-menu-paste'
import { isEditableTarget } from '@/lib/text-input/focus/editable-target'
import { APP_MENU_PASTE_EVENT } from '@/lib/clipboard/menu/app-menu-paste'
import {
APP_MENU_SELECTION_ACTION_EVENT,
type AppMenuSelectionAction
} from '@/lib/app-menu-selection-actions'
} from '@/lib/app-commands/app-menu-selection-actions'
import { copyTerminalSelection } from '@/components/terminal-pane/clipboard/terminal-selection-copy'
import type { PreviewTerminalPasteSource } from './preview-terminal-paste'
@@ -3,7 +3,7 @@ import { Terminal } from '@xterm/xterm'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { installPreviewImeBridge } from './preview-terminal-ime-bridge'
vi.mock('@/lib/shortcut-platform', () => ({
vi.mock('@/lib/keyboard/shortcut-platform', () => ({
getShortcutPlatform: () => 'darwin'
}))
@@ -11,13 +11,10 @@ const COMMA = { key: ',', code: 'Comma', keyCode: 188 }
type Session = {
emitted: string[]
flagReads: number
setFlags: (flags: number) => void
keydown: (init?: { shiftKey?: boolean; repeat?: boolean; key?: string; code?: string }) => void
keyup: (init?: { shiftKey?: boolean; key?: string; code?: string }) => void
commit: (text: string) => void
/** An input event the text system produced without committing text. */
swallow: () => void
dispose: () => void
}
@@ -28,12 +25,8 @@ function open(initialFlags: number): Session {
terminal.open(container)
const textarea = terminal.textarea!
let flags = initialFlags
let flagReads = 0
const bridge = installPreviewImeBridge(terminal, {
getKittyKeyboardFlags: () => {
flagReads += 1
return flags
}
getKittyKeyboardFlags: () => flags
})!
terminal.attachCustomKeyEventHandler((event) => !bridge.claimKeyEvent(event))
const emitted: string[] = []
@@ -66,16 +59,12 @@ function open(initialFlags: number): Session {
return {
emitted,
get flagReads() {
return flagReads
},
setFlags: (next) => {
flags = next
},
keydown: (init = {}) => key('keydown', init),
keyup: (init = {}) => key('keyup', init),
commit: (text) => input(text),
swallow: () => input(null),
dispose: () => {
bridge.dispose()
terminal.dispose()
@@ -94,70 +83,6 @@ describe('preview IME bridge outbound bytes', () => {
document.body.replaceChildren()
})
describe.each([
['keydown -> insertText -> keyup', false],
// Some macOS input sources commit after keyup; preserve press ownership until then.
['keydown -> keyup -> insertText', true]
])('in %s order', (_name, keyupFirst) => {
const type = (session: Session): void => {
session.keydown()
if (keyupFirst) {
session.keyup()
session.commit(',')
} else {
session.commit(',')
session.keyup()
}
}
it.each([
['no flags', 0, ','],
['disambiguate only', 1, ','],
['event types', 2, ',\x1b[44;1:3u'],
['all keys as escape codes', 8, '\x1b[44u'],
['all keys + event types', 10, '\x1b[44u\x1b[44;1:3u']
])('emits the %s byte shape', (_flagName, flags, expected) => {
const session = open(flags)
type(session)
expect(session.emitted.join('')).toBe(expected)
session.dispose()
})
it('reads the mutable getter exactly once, at commit time', () => {
const session = open(0)
session.keydown()
expect(session.flagReads).toBe(0)
session.setFlags(8)
if (keyupFirst) {
session.keyup()
expect(session.flagReads).toBe(0)
session.commit(',')
} else {
session.commit(',')
session.keyup()
}
expect(session.flagReads).toBe(1)
// The commit-time read is what both the press AND its release encode from.
expect(session.emitted.join('')).toBe('\x1b[44u')
session.dispose()
})
it('emits nothing when the input source swallowed the press', () => {
const session = open(10)
session.keydown()
if (keyupFirst) {
session.keyup()
session.swallow()
} else {
session.swallow()
session.keyup()
}
// A release describes a press the app received; none did.
expect(session.emitted.join('')).toBe('')
session.dispose()
})
})
it('encodes the release from the keyup state when Shift is released first', () => {
const session = open(10)
// `!` on Digit1: the press reports the base key with the Shift modifier.
@@ -1,5 +1,5 @@
import type { Terminal } from '@xterm/xterm'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import { installTerminalImeCompositionTracker } from '@/components/terminal-pane/input/ime/terminal-ime-composition-tracker'
import { installTerminalImeNativeTextForwarder } from '@/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder'
@@ -1,5 +1,5 @@
import type { Terminal } from '@xterm/xterm'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import { keybindingMatchesAction } from '../../../../shared/keybindings'
import { useAppStore } from '@/store'
import {
@@ -1,5 +1,5 @@
import type { Terminal } from '@xterm/xterm'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import { executeTerminalPastePlan } from '@/components/terminal-pane/input/paste/terminal-paste-executor'
import { planTerminalPasteWithYield } from '@/components/terminal-pane/input/paste/terminal-paste-coordinator'
import { resolveTerminalPasteRuntime } from '@/components/terminal-pane/input/paste/terminal-paste-runtime'
@@ -27,7 +27,7 @@ export function AgentDashboardExperimentalSetting({
'auto.components.settings.ExperimentalPane.agentDashboard.description',
'Kanban board for monitoring agents across worktrees, in-window or as a pop-out.'
)}
keywords={getExperimentalSearchEntry(t).agentDashboard.keywords}
keywords={getExperimentalSearchEntry().agentDashboard.keywords}
className="space-y-3 py-3"
id="experimental-agent-dashboard"
>
@@ -1,4 +1,4 @@
import { branchName } from '@/lib/git-utils'
import { branchName } from '@/lib/source-control/branches/branch-name'
import { getHostedReviewCacheKey } from '@/store/slices/hosted-review/hosted-review-cache-identity'
import type { AppState } from '@/store/types'
import type { DashboardCardReview } from '../../../../shared/dashboard-snapshot'
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
TEXT_CONTROL_PASTE_DIRECT_MAX_BYTES,
TEXT_CONTROL_PASTE_MAX_BYTES
} from '@/lib/text-control-paste'
} from '@/lib/text-input/paste/text-control-paste-model'
import { captureInsertionTarget, insertText } from './dictation-insertion-target'
type DocumentWithExecCommand = Document & {
@@ -3,11 +3,13 @@ import { getUtf8ChunkEndIndex } from '../../../../shared/utf8-byte-limits'
import {
TEXT_CONTROL_PASTE_CHUNK_MAX_BYTES,
TEXT_CONTROL_PASTE_DIRECT_MAX_BYTES,
TEXT_CONTROL_PASTE_MAX_BYTES,
TEXT_CONTROL_PASTE_MAX_BYTES
} from '@/lib/text-input/paste/text-control-paste-model'
import {
measureTextControlPasteByteLength,
measureTextControlPasteByteLengthWithYield,
pasteTextIntoTextControl
} from '@/lib/text-control-paste'
} from '@/lib/text-input/paste/text-control-paste'
import {
DICTATION_TEXT_BLOCK_SELECTOR,
dictationSeparators
@@ -1,6 +1,6 @@
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { describeClipboardWriteFailure } from '@/lib/clipboard-write-failure'
import { describeClipboardWriteFailure } from '@/lib/clipboard/clipboard-write-failure'
import { appendDictationText } from '../../../../shared/dictation-transcript-spacing'
import { insertText, type DictationInsertionTarget } from './dictation-insertion-target'
@@ -1,6 +1,6 @@
import { useEffect, useEffectEvent } from 'react'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event'
import { isPlainEscapeKeyEvent } from '../terminal-pane/input/keyboard/agent-interrupt-key-event'
import { DICTATION_CONTROL_EVENT, type DictationControlAction } from './dictation-control-events'
import type { DictationState } from '../../../../shared/speech-types'
@@ -1,5 +1,5 @@
import { useEffect, useEffectEvent, useRef } from 'react'
import { getShortcutPlatform } from '@/lib/shortcut-platform'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import {
keybindingMatchesAction,
normalizeTerminalShortcutPolicy,
@@ -8,7 +8,7 @@ import {
import { textInputOwnsComposition } from '../../../../shared/text-input-shortcut-policy'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import { dictationShortcutMode } from '../../../../shared/dictation-shortcut-mode'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification'
import { getKeybindingContext } from '../terminal-workspace-model'
@@ -1,4 +1,4 @@
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import { CornerDownLeft, Pencil, Trash } from 'lucide-react'
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import { Button } from '@/components/ui/button'
@@ -1,7 +1,7 @@
import { useGitHubTextareaImages } from '@/components/github/use-github-textarea-images'
import { useGitHubImagePending } from '@/components/github/use-github-image-uploads'
import type { GitHubImageIntake } from '@/components/github/use-github-image-uploads'
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { CornerDownLeft } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -10,7 +10,7 @@ import { useTranslate } from '@/i18n/use-translate'
import {
getCommentBodySubmitState,
hasBoundedCommentBodyText
} from '@/lib/comment-body-submit-state'
} from '@/lib/source-control/review/comments/comment-body-submit-state'
import { toast } from 'sonner'
import { installOpenDraftAddReviewNoteGuard } from '../editor/editor-shortcuts'
@@ -1,4 +1,4 @@
import { ImeTextarea } from '@/lib/ime-text-field'
import { ImeTextarea } from '@/lib/text-input/ime/ime-text-field'
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { CornerDownLeft } from 'lucide-react'
import { toast } from 'sonner'
@@ -7,7 +7,7 @@ import { useMountedRef } from '@/hooks/useMountedRef'
import {
getCommentBodySubmitState,
hasBoundedCommentBodyText
} from '@/lib/comment-body-submit-state'
} from '@/lib/source-control/review/comments/comment-body-submit-state'
import { useTranslate } from '@/i18n/use-translate'
import { installOpenDraftAddReviewNoteGuard } from '../editor/editor-shortcuts'
import { resolveDiffCommentPopoverTop } from './diff-comment-popover-position'
@@ -3,7 +3,7 @@
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { COMMENT_BODY_NONBLANK_SCAN_MAX_BYTES } from '@/lib/comment-body-submit-state'
import { COMMENT_BODY_NONBLANK_SCAN_MAX_BYTES } from '@/lib/source-control/review/comments/comment-body-submit-state'
import { DiffCommentPopover } from './DiffCommentPopover'
const roots: Root[] = []
@@ -6,7 +6,7 @@ import {
import { useCallback, useEffect, useMemo, useRef } from 'react'
import type { editor as monacoEditor } from 'monaco-editor'
import { createRoot, type Root } from 'react-dom/client'
import { getCommentBodyLayoutLineCount } from '@/lib/comment-body-line-count'
import { getCommentBodyLayoutLineCount } from '@/lib/source-control/review/comments/comment-body-line-count'
import { translate } from '@/i18n/i18n'
import { useAppStore } from '@/store'
import {
@@ -1,7 +1,7 @@
import React, { useCallback, useMemo, useRef, useState } from 'react'
import { useAppStore } from '@/store'
import { getConnectionId } from '@/lib/workspace/ownership/connection-context'
import { formatClipboardFilePath } from '@/lib/clipboard-file-path'
import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path'
import { getOpenFileRevealOwner } from '@/lib/reveal-in-file-manager'
import { canShowWorkspaceFileBrowserAction } from '@/lib/browser/documents/file-preview'
import { openEditorHtmlPreview } from './open-editor-html-preview'
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import { useEffect, useRef, useState } from 'react'
import { Eye, Pencil } from 'lucide-react'
import {
@@ -10,7 +10,7 @@ import {
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { useShortcutLabel } from '@/hooks/useShortcutLabel'
import { isImeCompositionKeyDown } from '@/lib/ime-composition-keyboard-event'
import { isImeCompositionKeyDown } from '@/lib/text-input/ime/ime-composition-keyboard-event'
import { useTranslate } from '@/i18n/use-translate'
import type { OpenFile } from '@/store/slices/editor/types/open-file'
import { isVirtualEditorFile } from '@/store/slices/editor/tabs/editor-tab-content-type'
@@ -13,7 +13,7 @@ import { getConnectionId } from '@/lib/workspace/ownership/connection-context'
import { findFirstIndexedWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner-index'
import { getRuntimeGitRemoteFileUrl } from '@/runtime/source-control/git/runtime-git-working-tree-client'
import { formatPathLineReference } from './line-copy-path'
import { formatClipboardFilePath } from '@/lib/clipboard-file-path'
import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path'
import { getOpenFileRevealOwner } from '@/lib/reveal-in-file-manager'
import { useTranslate } from '@/i18n/use-translate'
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
@@ -10,7 +10,7 @@ import { useAppStore } from '@/store'
import {
clipboardImageCopyErrorDescription,
imageCopyFailedMessage
} from '@/lib/clipboard-image-copy'
} from '@/lib/clipboard/images/clipboard-image-copy'
import { IMAGE_VIEWER_ZOOM_STEP } from './image-viewer-zoom'
import { imageClipboardPngDataUrl } from './image-png-export'
import type { PanZoomSize } from '../../../../shared/pan-zoom-view'
@@ -1,4 +1,4 @@
import { ImeInput } from '@/lib/ime-text-field'
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
import { useCallback, useEffect, useState } from 'react'
import { ChevronUp, ChevronDown, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -10,7 +10,7 @@ import {
} from './check-run-details-fix-context'
import { openSourceControlAiSettingsTarget } from '@/components/right-sidebar/source-control/panel/source-control-ai-settings-navigation'
import { getConnectionId } from '@/lib/workspace/ownership/connection-context'
import { startFixChecksAgent } from '@/lib/fix-checks-agent-launch'
import { startFixChecksAgent } from '@/lib/source-control/checks/fix-checks-agent-launch'
import { readSourceControlLaunchRecipeAgentId } from '../../../../../../shared/source-control/ai/source-control-launch-agent-selection'
import { resolveRepoWorktreeLaunchPlatform } from '@/runtime/hosts/platform/execution-host-facts'
import { useAppStore } from '@/store/index'
@@ -1,6 +1,6 @@
import React from 'react'
import { Check, Copy } from 'lucide-react'
import { useClipboardTextCopyFeedback } from '@/hooks/use-clipboard-text-copy-feedback'
import { useClipboardTextCopyFeedback } from '@/hooks/clipboard/use-clipboard-text-copy-feedback'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
@@ -1,6 +1,6 @@
import { createElement, memo } from 'react'
import { ChevronDown } from 'lucide-react'
import { STATUS_COLORS } from '@/lib/git-path-decoration'
import { STATUS_COLORS } from '@/lib/source-control/paths/git-path-decoration'
import { STATUS_LABELS } from '../../../../../../shared/git/status/git-status-labels'
import type { SourceControlTreeNode } from '../../../../../../shared/source-control/listing/source-control-tree'
import { FileTypeIcon, FolderIcon } from '@/components/FileTypeIcon'
@@ -9,7 +9,7 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { getDiffCommentLineLabel } from '@/lib/diff-comment-compat'
import { getDiffCommentLineLabel } from '@/lib/source-control/review/comments/diff-comment-compat'
import { useTranslate } from '@/i18n/use-translate'
import type { DiffComment } from '../../../../../../shared/diff-comment-types'

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