diff --git a/src/main/daemon/pty-subprocess/shell-launch-plan.ts b/src/main/daemon/pty-subprocess/shell-launch-plan.ts index bda3dd730ca..0626f3bb11c 100644 --- a/src/main/daemon/pty-subprocess/shell-launch-plan.ts +++ b/src/main/daemon/pty-subprocess/shell-launch-plan.ts @@ -63,8 +63,9 @@ export function createPtyShellLaunchPlan( opts: PtySubprocessOptions, env: Record ): PtyShellLaunchPlan { - const resolvedWslContext = resolveWslSessionContext(opts) - let shellPath = resolvedWslContext ? 'wsl.exe' : opts.shellOverride || resolvePtyShellPath(env) + const effectiveShell = opts.shellOverride || resolvePtyShellPath(env) + const resolvedWslContext = resolveWslSessionContext({ ...opts, shellOverride: effectiveShell }) + let shellPath = resolvedWslContext ? 'wsl.exe' : effectiveShell let shellArgs: string[] let startupCommandDeliveredInShellArgs = false let windowsFallbackAttempts: WindowsShellSpawnAttempt[] = [] diff --git a/src/main/daemon/pty-subprocess/wsl-session-context.ts b/src/main/daemon/pty-subprocess/wsl-session-context.ts index 6d301fbfd88..81eec93b7cf 100644 --- a/src/main/daemon/pty-subprocess/wsl-session-context.ts +++ b/src/main/daemon/pty-subprocess/wsl-session-context.ts @@ -1,9 +1,8 @@ import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' -import { isWslShellName } from '../../../shared/local-windows-terminal-runtime' +import { selectEffectiveTerminalExecutionContext } from '../../../shared/terminal/effective-terminal-execution-context' import { getDefaultWslDistro } from '../../wsl/discovery/distro-catalog' import { parseWslPath } from '../../wsl/filesystem/unc-path-access' import { parsePtySessionId } from '../../../shared/terminal/pty/lifecycle/pty-session-id-format' -import { parseWslUncPath } from '../../../shared/wsl-paths' export type WslSessionContext = { distro: string @@ -32,18 +31,19 @@ export function resolveWslSessionContext(args: { shellOverride?: string terminalWindowsWslDistro?: string | null }): WslSessionContext | undefined { - if (process.platform !== 'win32') { - return undefined + const inputs = { + platform: process.platform, + cwd: args.cwd, + worktreeContext: args.sessionId ? getWslContextFromSessionId(args.sessionId) : undefined, + shell: args.shellOverride, + preferredDistro: args.terminalWindowsWslDistro } - const cwdDistro = args.cwd ? parseWslUncPath(args.cwd)?.distro : undefined - if (cwdDistro) { - return { distro: cwdDistro, treatPosixCwdAsWsl: true } + let selected = selectEffectiveTerminalExecutionContext(inputs) + if (selected.kind === 'unresolved-wsl') { + selected = selectEffectiveTerminalExecutionContext({ + ...inputs, + defaultDistro: getDefaultWslDistro() + }) } - return ( - (args.sessionId ? getWslContextFromSessionId(args.sessionId) : undefined) ?? - (isWslShellName(args.shellOverride) - ? (getWslContextFromPreferredDistro(args.terminalWindowsWslDistro) ?? - getWslContextFromPreferredDistro(getDefaultWslDistro())) - : undefined) - ) + return selected.kind === 'wsl' ? selected.context : undefined } diff --git a/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts b/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts index 03ea1c0ebff..372f50fb14d 100644 --- a/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-model-discovery-handlers.ts @@ -1,3 +1,4 @@ +import { isProjectRuntimeRepairRefusal } from '../../../shared/project-runtime-repair-message' import { ipcMain } from 'electron' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import type { CommitMessageAgentRuntimeTarget } from '../../text-generation/commit-message-agent-environment' @@ -35,37 +36,50 @@ export function registerFilesystemGitModelDiscoveryHandlers( error: `No git provider for connection "${args.connectionId}"` } } - let localRuntimeTarget: CommitMessageAgentRuntimeTarget = { runtime: 'host' } - let localDiscoveryOptions: Parameters[3] - if (args.worktreePath) { - const worktreePath = await resolveModelDiscoveryLocalPath(store, args.worktreePath) - const gitOptions = getLocalGitOptionsForRegisteredWorktree( - store, - args.worktreePath, - worktreePath - ) - const wslDistro = gitOptions.wslDistro ?? parseWslPath(args.worktreePath)?.distro - localRuntimeTarget = wslDistro - ? { runtime: 'wsl', wslDistro } - : getLocalAgentRuntimeTarget(gitOptions) - localDiscoveryOptions = wslDistro ? { cwd: worktreePath, wslDistro } : { cwd: worktreePath } - } - const localEnv = await prepareLocalCommitMessageAgentEnv( - agentId, - commitMessageAgentEnv, - localRuntimeTarget - ) - if (!localEnv.ok) { - return { success: false, error: localEnv.error } - } - return localDiscoveryOptions - ? discoverCommitMessageModelsLocal( - agentId as TuiAgent, - localEnv.env, - agentCommandOverride, - localDiscoveryOptions + try { + let localRuntimeTarget: CommitMessageAgentRuntimeTarget = { runtime: 'host' } + let localDiscoveryOptions: Parameters[3] + if (args.worktreePath) { + const worktreePath = await resolveModelDiscoveryLocalPath(store, args.worktreePath) + const gitOptions = getLocalGitOptionsForRegisteredWorktree( + store, + args.worktreePath, + worktreePath ) - : discoverCommitMessageModelsLocal(agentId as TuiAgent, localEnv.env, agentCommandOverride) + const wslDistro = gitOptions.wslDistro ?? parseWslPath(args.worktreePath)?.distro + localRuntimeTarget = wslDistro + ? { runtime: 'wsl', wslDistro } + : getLocalAgentRuntimeTarget(gitOptions) + localDiscoveryOptions = wslDistro + ? { cwd: worktreePath, wslDistro } + : { cwd: worktreePath } + } + const localEnv = await prepareLocalCommitMessageAgentEnv( + agentId, + commitMessageAgentEnv, + localRuntimeTarget + ) + if (!localEnv.ok) { + return { success: false, error: localEnv.error } + } + return localDiscoveryOptions + ? await discoverCommitMessageModelsLocal( + agentId as TuiAgent, + localEnv.env, + agentCommandOverride, + localDiscoveryOptions + ) + : await discoverCommitMessageModelsLocal( + agentId as TuiAgent, + localEnv.env, + agentCommandOverride + ) + } catch (error) { + if (isProjectRuntimeRepairRefusal(error)) { + return { success: false, error: error.message } + } + throw error + } } ) } diff --git a/src/main/ipc/filesystem/filesystem-model-discovery-runtime.test.ts b/src/main/ipc/filesystem/filesystem-model-discovery-runtime.test.ts new file mode 100644 index 00000000000..a7d2724c3bd --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-model-discovery-runtime.test.ts @@ -0,0 +1,185 @@ +import type { DiscoveryIO } from './terminal-model-discovery.test-fixture' +import { expect, it, vi } from 'vitest' +const io = vi.hoisted(() => ({ + generateCommit: vi.fn(), + generatePr: vi.fn(), + handle: vi.fn(), + env: vi.fn(), + discover: vi.fn(), + materialize: vi.fn(), + distros: ['Ubuntu'], + distrosKnown: false, + rows: [], + mutations: vi.fn(), + userAct: vi.fn() +})) +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/pr40175-terminal-discovery', isPackaged: false }, + ipcMain: { handle: io.handle, removeHandler: vi.fn() } +})) +vi.mock('node:fs/promises', async (original) => ({ + ...(await original()), + stat: async () => ({ isDirectory: () => true }), + access: async () => {}, + realpath: async (path: string) => path, + mkdir: io.mutations +})) +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ + prepareLocalCommitMessageAgentEnv: io.env +})) +vi.mock('../../text-generation/commit-message-text-generation', async (original) => ({ + ...(await original()), + discoverCommitMessageModelsLocal: io.discover, + generateCommitMessageFromContext: io.generateCommit, + generatePullRequestFieldsFromContext: io.generatePr +})) +vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (original) => ({ + ...(await original()), + listWorktrees: async () => io.rows, + listWorktreesSharedStrict: async () => io.rows +})) +vi.mock('../../git/worktrees/catalog/worktree-listing', async (original) => ({ + ...(await original()), + listWorktreesStrict: async () => io.rows +})) +vi.mock('../worktree-remote', async (original) => ({ + ...(await original()), + materializeWorktreePushTargetRemote: io.materialize +})) +vi.mock('../../wsl/discovery/wsl-availability', () => ({ + hasCachedWslAvailability: () => false +})) +vi.mock('../../wsl/discovery/distro-catalog', () => ({ + hasCachedWslDistros: () => io.distrosKnown, + getCachedWslDistros: () => io.distros, + listWslDistrosAsync: async () => io.distros +})) +vi.mock('../../wsl/filesystem/wsl-unc-access-gate', async (original) => ({ + ...(await original()), + blockedWslDistroForPath: async () => null, + runAsWslUserAct: io.userAct +})) +vi.mock('../../git/source-control/staged-commit-context', () => ({ + getStagedCommitContext: async () => ({ patch: '+change', files: ['file.ts'] }) +})) +vi.mock('../../text-generation/pull-request-context', () => ({ + getPullRequestDraftContext: async () => ({ patch: '+change', branch: 'fix' }) +})) +vi.mock('../../source-control/pull-request-template', () => ({ + resolveHostedReviewBodyForGeneration: async () => '' +})) +vi.mock('../../source-control/pull-request-linked-issue', () => ({ + loadPullRequestLinkedIssue: async () => undefined +})) +import { createTerminalDiscoveryFixture } from './terminal-model-discovery.test-fixture' + +const fixture = createTerminalDiscoveryFixture(io) + +it.each([ + { + name: 'native shell with leftover distro', + shell: 'powershell.exe', + distro: 'Ubuntu', + model: 'native-model', + guest: undefined + }, + { name: 'default WSL shell', shell: 'wsl.exe', model: 'ubuntu-model', guest: 'Ubuntu' }, + { + name: 'UNC authority', + path: '\\\\wsl.localhost\\Ubuntu\\home\\me', + distro: 'Debian', + model: 'ubuntu-model', + guest: 'Ubuntu' + }, + { + name: 'mixed project repo', + repo: true, + runtime: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }, + model: 'ubuntu-model', + guest: 'Ubuntu' + }, + { + name: 'associated folder', + runtime: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }, + model: 'ubuntu-model', + guest: 'Ubuntu' + }, + { + name: 'forced host project', + repo: true, + shell: 'wsl.exe', + runtime: { kind: 'windows-host' }, + model: 'native-model', + guest: undefined + }, + { + name: 'Mac stale preference', + platform: 'darwin', + shell: 'wsl.exe', + distro: 'Ubuntu', + model: 'native-model', + guest: undefined + }, + { + name: 'Linux stale preference', + platform: 'linux', + shell: 'wsl.exe', + distro: 'Ubuntu', + model: 'native-model', + guest: undefined + } +] as const)('$name uses the effective terminal runtime through IPC and RPC', async (input) => { + const rig = fixture(input) + for (const read of [rig.ipc, rig.rpc]) { + expect(await read()).toMatchObject({ success: true, models: [{ id: input.model }] }) + expect(io.env.mock.calls.at(-1)?.[2]).toEqual( + input.guest ? { runtime: 'wsl', wslDistro: input.guest } : { runtime: 'host' } + ) + expect(io.discover.mock.calls.at(-1)?.[3]).toEqual( + input.guest ? { cwd: rig.path, wslDistro: input.guest } : { cwd: rig.path } + ) + } + expect(io.userAct).not.toHaveBeenCalled() +}) + +it('does not probe natively when the WSL default is unresolved, and retries when the catalog fills', async () => { + const rig = fixture({ shell: 'wsl.exe' }) + io.distros = [] + expect(await rig.ipc()).toEqual({ + success: false, + error: 'terminal_execution_context_unresolved' + }) + expect(io.env).not.toHaveBeenCalled() + expect(io.discover).not.toHaveBeenCalled() + io.distros = ['Ubuntu'] + expect(await rig.rpc()).toMatchObject({ success: true, models: [{ id: 'ubuntu-model' }] }) +}) + +it('refuses a foreign runtime folder-backed repo through IPC and RPC before local environment or probe work', async () => { + const foreign = fixture({ + repo: true, + repoId: 'foreign', + repoKind: 'folder', + path: 'C:\\work\\app', + executionHostId: 'runtime:other' + }) + for (const read of [foreign.ipc, foreign.rpc]) { + expect(await read()).toEqual({ + success: false, + error: 'Terminal model discovery is unavailable on this connection.' + }) + } + expect(io.env).not.toHaveBeenCalled() + expect(io.discover).not.toHaveBeenCalled() + const local = fixture({ + repo: true, + repoKind: 'folder', + path: 'C:\\work\\app', + executionHostId: 'local' + }) + for (const read of [local.ipc, local.rpc]) { + expect(await read()).toMatchObject({ success: true, models: [{ id: 'native-model' }] }) + } + expect(io.env).toHaveBeenCalledTimes(2) + expect(io.discover).toHaveBeenCalledTimes(2) +}) diff --git a/src/main/ipc/filesystem/terminal-model-discovery-purpose.test.ts b/src/main/ipc/filesystem/terminal-model-discovery-purpose.test.ts new file mode 100644 index 00000000000..c2b63bd6b5e --- /dev/null +++ b/src/main/ipc/filesystem/terminal-model-discovery-purpose.test.ts @@ -0,0 +1,162 @@ +import { GitDiscoverCommitMessageModels } from '../../../shared/rpc-contract/git-params' +import type { DiscoveryIO } from './terminal-model-discovery.test-fixture' +import { expect, it, vi } from 'vitest' +const io = vi.hoisted(() => ({ + generateCommit: vi.fn(), + generatePr: vi.fn(), + handle: vi.fn(), + env: vi.fn(), + discover: vi.fn(), + materialize: vi.fn(), + distros: ['Ubuntu'], + distrosKnown: false, + rows: [], + mutations: vi.fn(), + userAct: vi.fn() +})) +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/pr40175-terminal-discovery', isPackaged: false }, + ipcMain: { handle: io.handle, removeHandler: vi.fn() } +})) +vi.mock('node:fs/promises', async (original) => ({ + ...(await original()), + stat: async () => ({ isDirectory: () => true }), + access: async () => {}, + realpath: async (path: string) => path, + mkdir: io.mutations +})) +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ + prepareLocalCommitMessageAgentEnv: io.env +})) +vi.mock('../../text-generation/commit-message-text-generation', async (original) => ({ + ...(await original()), + discoverCommitMessageModelsLocal: io.discover, + generateCommitMessageFromContext: io.generateCommit, + generatePullRequestFieldsFromContext: io.generatePr +})) +vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (original) => ({ + ...(await original()), + listWorktrees: async () => io.rows, + listWorktreesSharedStrict: async () => io.rows +})) +vi.mock('../../git/worktrees/catalog/worktree-listing', async (original) => ({ + ...(await original()), + listWorktreesStrict: async () => io.rows +})) +vi.mock('../worktree-remote', async (original) => ({ + ...(await original()), + materializeWorktreePushTargetRemote: io.materialize +})) +vi.mock('../../wsl/discovery/wsl-availability', () => ({ + hasCachedWslAvailability: () => false +})) +vi.mock('../../wsl/discovery/distro-catalog', () => ({ + hasCachedWslDistros: () => io.distrosKnown, + getCachedWslDistros: () => io.distros, + listWslDistrosAsync: async () => io.distros +})) +vi.mock('../../wsl/filesystem/wsl-unc-access-gate', async (original) => ({ + ...(await original()), + blockedWslDistroForPath: async () => null, + runAsWslUserAct: io.userAct +})) +vi.mock('../../git/source-control/staged-commit-context', () => ({ + getStagedCommitContext: async () => ({ patch: '+change', files: ['file.ts'] }) +})) +vi.mock('../../text-generation/pull-request-context', () => ({ + getPullRequestDraftContext: async () => ({ patch: '+change', branch: 'fix' }) +})) +vi.mock('../../source-control/pull-request-template', () => ({ + resolveHostedReviewBodyForGeneration: async () => '' +})) +vi.mock('../../source-control/pull-request-linked-issue', () => ({ + loadPullRequestLinkedIssue: async () => undefined +})) +import { createTerminalDiscoveryFixture } from './terminal-model-discovery.test-fixture' +import { GIT_COMMIT_MESSAGE_GENERATION_METHODS } from '../../runtime/rpc/methods/source-control/git/git-commit-message-generation-methods' +import { registerFilesystemGitModelDiscoveryHandlers } from './filesystem-git-model-discovery-handlers' +import { resolveAgentLaunchRuntime } from '../../runtime/terminal/launch/agent-launch-scope-runtime' + +const fixture = createTerminalDiscoveryFixture(io) + +it('keeps terminal Ubuntu inventory separate from native Git discovery and commit/PR generation', async () => { + const rig = fixture({ + repo: true, + runtime: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } + }) + expect(await rig.rpc()).toMatchObject({ models: [{ id: 'ubuntu-model' }] }) + const git = GIT_COMMIT_MESSAGE_GENERATION_METHODS.find( + ( + method + ): method is Extract< + (typeof GIT_COMMIT_MESSAGE_GENERATION_METHODS)[number], + { params: typeof GitDiscoverCommitMessageModels } + > => method.params === GitDiscoverCommitMessageModels + )! + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each method reads the real runtime; dispatcher context ports are not needed. + const context = { runtime: rig.runtime } as never + expect( + await git.handler({ worktree: rig.selector, agentId: 'antigravity' }, context) + ).toMatchObject({ success: true, models: [{ id: 'native-model' }] }) + const override = { + sourceControlAiResolvedParams: { + agentId: 'antigravity' as const, + model: 'native-selected-literal' + } + } + await rig.runtime.generateRuntimeCommitMessage(rig.selector, override) + await rig.runtime.generateRuntimePullRequestFields( + rig.selector, + { base: 'main', title: '', body: '', draft: true, useTemplate: false }, + override + ) + for (const call of [io.generateCommit.mock.calls.at(-1), io.generatePr.mock.calls.at(-1)]) { + expect(call?.[1]).toEqual({ agentId: 'antigravity', model: 'native-selected-literal' }) + expect(call?.[2]).toEqual({ kind: 'local', cwd: rig.path, env: { MODEL_CONTEXT: 'native' } }) + } + // Local text-action cards deliberately use the unchanged host-global request shape. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler only reads this fixture's store and environment. + registerFilesystemGitModelDiscoveryHandlers({ store: rig.store } as never) + const local = io.handle.mock.calls.find( + ([name]) => name === 'git:discoverCommitMessageModels' + )![1] + expect( + await local(null, { agentId: 'antigravity', worktreePath: '', connectionId: undefined }) + ).toMatchObject({ models: [{ id: 'native-model' }] }) + expect(io.discover.mock.calls.at(-1)).toEqual([ + 'antigravity', + { MODEL_CONTEXT: 'native' }, + undefined + ]) +}) + +it('settles a terminal repair refusal before preparing an environment or probing', async () => { + const rig = fixture({ runtime: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } }) + io.distrosKnown = true + io.distros = [] + expect(await rig.ipc()).toMatchObject({ success: false }) + const target = await rig.runtime.resolveTerminalWorkspaceReadTarget(rig.selector) + expect(() => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read-port fixture supplies the launch resolver's store reads, as for the real runtime constructor. + return resolveAgentLaunchRuntime(rig.store as never, target.scope, undefined, 'antigravity') + }).toThrow('No agent was started.') + expect(io.env).not.toHaveBeenCalled() + expect(io.discover).not.toHaveBeenCalled() +}) + +it('settles the existing Git repair refusal without probing or falling back to host execution', async () => { + const runtime = { kind: 'wsl' as const, distro: 'Ubuntu', git: 'windows-host' as const } + const rig = fixture({ repo: true, runtime }) + expect( + await rig.runtime.discoverRuntimeCommitMessageModels(`path:${rig.path}`, 'antigravity') + ).toMatchObject({ success: true, models: [{ id: 'native-model' }] }) + io.env.mockClear() + io.discover.mockClear() + io.distrosKnown = true + io.distros = [] + expect( + await rig.runtime.discoverRuntimeCommitMessageModels(rig.selector, 'antigravity') + ).toMatchObject({ success: false }) + expect(io.env).not.toHaveBeenCalled() + expect(io.discover).not.toHaveBeenCalled() +}) diff --git a/src/main/ipc/filesystem/terminal-model-discovery-read-only.test.ts b/src/main/ipc/filesystem/terminal-model-discovery-read-only.test.ts new file mode 100644 index 00000000000..0cbcc9649a5 --- /dev/null +++ b/src/main/ipc/filesystem/terminal-model-discovery-read-only.test.ts @@ -0,0 +1,90 @@ +import type { DiscoveryIO } from './terminal-model-discovery.test-fixture' +import { expect, it, vi } from 'vitest' +const io = vi.hoisted(() => ({ + generateCommit: vi.fn(), + generatePr: vi.fn(), + handle: vi.fn(), + env: vi.fn(), + discover: vi.fn(), + materialize: vi.fn(), + distros: ['Ubuntu'], + distrosKnown: false, + rows: [], + mutations: vi.fn(), + userAct: vi.fn() +})) +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/pr40175-terminal-discovery', isPackaged: false }, + ipcMain: { handle: io.handle, removeHandler: vi.fn() } +})) +vi.mock('node:fs/promises', async (original) => ({ + ...(await original()), + stat: async () => ({ isDirectory: () => true }), + access: async () => {}, + realpath: async (path: string) => path, + mkdir: io.mutations +})) +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ + prepareLocalCommitMessageAgentEnv: io.env +})) +vi.mock('../../text-generation/commit-message-text-generation', async (original) => ({ + ...(await original()), + discoverCommitMessageModelsLocal: io.discover, + generateCommitMessageFromContext: io.generateCommit, + generatePullRequestFieldsFromContext: io.generatePr +})) +vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (original) => ({ + ...(await original()), + listWorktrees: async () => io.rows, + listWorktreesSharedStrict: async () => io.rows +})) +vi.mock('../../git/worktrees/catalog/worktree-listing', async (original) => ({ + ...(await original()), + listWorktreesStrict: async () => io.rows +})) +vi.mock('../worktree-remote', async (original) => ({ + ...(await original()), + materializeWorktreePushTargetRemote: io.materialize +})) +vi.mock('../../wsl/discovery/wsl-availability', () => ({ + hasCachedWslAvailability: () => false +})) +vi.mock('../../wsl/discovery/distro-catalog', () => ({ + hasCachedWslDistros: () => io.distrosKnown, + getCachedWslDistros: () => io.distros, + listWslDistrosAsync: async () => io.distros +})) +vi.mock('../../wsl/filesystem/wsl-unc-access-gate', async (original) => ({ + ...(await original()), + blockedWslDistroForPath: async () => null, + runAsWslUserAct: io.userAct +})) +vi.mock('../../git/source-control/staged-commit-context', () => ({ + getStagedCommitContext: async () => ({ patch: '+change', files: ['file.ts'] }) +})) +vi.mock('../../text-generation/pull-request-context', () => ({ + getPullRequestDraftContext: async () => ({ patch: '+change', branch: 'fix' }) +})) +vi.mock('../../source-control/pull-request-template', () => ({ + resolveHostedReviewBodyForGeneration: async () => '' +})) +vi.mock('../../source-control/pull-request-linked-issue', () => ({ + loadPullRequestLinkedIssue: async () => undefined +})) +import { createTerminalDiscoveryFixture } from './terminal-model-discovery.test-fixture' +import { readFloatingTerminalCwd } from '../floating-workspace-directory' + +const fixture = createTerminalDiscoveryFixture(io) + +it('read-only floating selection never creates or trusts a missing fallback directory', async () => { + fixture() + // Filesystem failure is the external boundary, not a replacement scope policy. + const spy = vi + .spyOn(await import('node:fs/promises'), 'stat') + .mockRejectedValue(new Error('ENOENT')) + await expect( + readFloatingTerminalCwd({ getSettings: () => ({}) }, { path: '/missing' }) + ).rejects.toThrow('floating_workspace_path_unavailable') + expect(io.mutations).not.toHaveBeenCalled() + spy.mockRestore() +}) diff --git a/src/main/ipc/filesystem/terminal-model-discovery.test-fixture.ts b/src/main/ipc/filesystem/terminal-model-discovery.test-fixture.ts new file mode 100644 index 00000000000..f27ff41f231 --- /dev/null +++ b/src/main/ipc/filesystem/terminal-model-discovery.test-fixture.ts @@ -0,0 +1,164 @@ +import { afterEach, beforeEach, vi, type Mock } from 'vitest' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { registerTerminalModelDiscoveryHandler } from '../terminal-model-discovery' +import { AGENT_MODEL_DISCOVERY_METHODS } from '../../runtime/rpc/methods/terminal/agent-model-discovery' + +export const FOLDER_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +export type DiscoveryIO = { + generateCommit: Mock + generatePr: Mock + handle: Mock + env: Mock + discover: Mock + materialize: Mock + distros: string[] + distrosKnown: boolean + rows: { + path: string + head: string + branch: string + isBare: boolean + isMainWorktree: boolean + }[] + mutations: Mock + userAct: Mock +} + +export function createTerminalDiscoveryFixture(io: DiscoveryIO) { + const platform = Object.getOwnPropertyDescriptor(process, 'platform')! + afterEach(() => { + Object.defineProperty(process, 'platform', platform) + vi.clearAllMocks() + }) + beforeEach(() => { + io.distros = ['Ubuntu'] + io.distrosKnown = false + io.rows = [] + io.materialize.mockResolvedValue(undefined) + io.generateCommit.mockResolvedValue({ success: true, message: 'Commit' }) + io.generatePr.mockResolvedValue({ success: true, fields: { title: 'PR', body: 'Body' } }) + io.env.mockImplementation(async (_agent, _resolver, target) => ({ + ok: true, + env: { MODEL_CONTEXT: target.wslDistro ?? 'native' } + })) + io.discover.mockImplementation(async (_agent, env) => ({ + success: true, + catalogOrigin: 'probe', + defaultModelId: '', + capability: {}, + models: [ + { + id: + env.MODEL_CONTEXT === 'Ubuntu' + ? 'ubuntu-model' + : env.MODEL_CONTEXT === 'Debian' + ? 'debian-model' + : 'native-model', + label: 'Listed' + } + ] + })) + }) + return function fixture( + options: { + platform?: NodeJS.Platform + path?: string + shell?: string + distro?: string + repo?: boolean + repoKind?: 'folder' + repoId?: string + executionHostId?: string + runtime?: { kind: 'wsl'; distro: string; git: 'windows-host' } | { kind: 'windows-host' } + } = {} + ) { + Object.defineProperty(process, 'platform', { + configurable: true, + value: options.platform ?? 'win32' + }) + const path = options.path ?? 'C:\\plain' + const repo = { + id: options.repoId ?? 'repo', + ...(options.repoKind ? { kind: options.repoKind } : {}), + path, + projectGroupId: 'group', + connectionId: null, + executionHostId: options.executionHostId ?? 'local' + } + const id = `${repo.id}::${path}` + const folder = { + id: FOLDER_ID, + folderPath: path, + projectGroupId: 'group', + executionHostId: 'local', + name: 'plain' + } + const settings = { + terminalWindowsShell: options.shell ?? 'powershell.exe', + terminalWindowsWslDistro: options.distro + } + io.rows = [{ path, head: 'abc', branch: 'fix', isBare: false, isMainWorktree: true }] + const metadata = new Map>() + const initialMeta = (): Partial => ({ + instanceId: 'fixture-instance' + }) + const getWorktreeMeta = (id: string) => metadata.get(id) ?? initialMeta() + const store = { + getSettings: () => settings, + getRepos: () => (options.repo || options.runtime ? [repo] : []), + getRepo: () => (options.repo || options.runtime ? repo : undefined), + getProjects: () => + options.runtime + ? [ + { + id: 'project', + sourceRepoIds: ['repo'], + localWindowsRuntimePreference: options.runtime + } + ] + : [], + getProjectGroups: () => [ + { id: 'group', name: 'Group', parentPath: path, connectionId: null } + ], + getFolderWorkspaces: () => [folder], + getWorktreeMeta, + getAllWorktreeMeta: () => + Object.fromEntries( + io.rows.map((row) => [`repo::${row.path}`, getWorktreeMeta(`repo::${row.path}`)]) + ), + setWorktreeMeta: (target: { id: string }, patch: Partial) => { + io.mutations(target, patch) + const meta = { ...getWorktreeMeta(target.id), ...patch, instanceId: 'fixture-instance' } + metadata.set(target.id, meta) + return meta + }, + updateSettings: io.mutations, + getWorkspaceSession: getDefaultWorkspaceSession, + getAllWorktreeLineage: () => ({}), + flushOrThrow: () => {} + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: discovery uses these read ports; mutations are recorded separately. + const runtime = new OrcaRuntimeService(store as never) + registerTerminalModelDiscoveryHandler(runtime) + const ipc = io.handle.mock.calls.at(-1)![1] + const selector = options.repo ? `id:${id}` : `id:folder:${FOLDER_ID}` + const rpc = () => + AGENT_MODEL_DISCOVERY_METHODS[0].handler( + { worktree: selector, agentId: 'antigravity' }, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real method only reads the runtime from this context. + { runtime } as never + ) + return { + runtime, + store, + settings, + path, + id, + selector, + rpc, + ipc: () => ipc(null, { worktree: selector, agentId: 'antigravity' }) + } + } +} diff --git a/src/main/ipc/floating-workspace-directory.ts b/src/main/ipc/floating-workspace-directory.ts index 3e2fb097c56..1404bbc03bf 100644 --- a/src/main/ipc/floating-workspace-directory.ts +++ b/src/main/ipc/floating-workspace-directory.ts @@ -111,29 +111,46 @@ export async function ensureDefaultFloatingWorkspacePath(): Promise { return cwd } +async function selectFloatingTerminalCwd( + store: { getSettings(): FloatingTerminalSettings }, + args?: FloatingTerminalCwdRequest +): Promise<{ path: string; prepare: boolean }> { + const fallback = { path: getDefaultFloatingWorkspacePath(), prepare: true } + const configuredPath = typeof args?.path === 'string' ? args.path.trim() : '' + if (!configuredPath) { + return args?.requireTrusted === true + ? fallback + : { path: resolveFloatingWorkspaceInput('~'), prepare: false } + } + const cwd = resolveFloatingWorkspaceInput(configuredPath) + const canonicalCwd = await canonicalizeAccessibleDirectory(cwd) + if (!canonicalCwd) { + return fallback + } + if (isTrustedFloatingWorkspaceDirectory(canonicalCwd, store.getSettings())) { + return { path: canonicalCwd, prepare: false } + } + return args?.requireTrusted === true ? fallback : { path: cwd, prepare: false } +} + +export async function readFloatingTerminalCwd( + store: { getSettings(): FloatingTerminalSettings }, + args?: FloatingTerminalCwdRequest +): Promise { + const selected = await selectFloatingTerminalCwd(store, args) + const accessible = await canonicalizeAccessibleDirectory(selected.path) + if (!accessible) { + throw new Error('floating_workspace_path_unavailable') + } + return selected.path +} + export async function resolveFloatingTerminalCwd( store: { getSettings(): FloatingTerminalSettings }, args?: FloatingTerminalCwdRequest ): Promise { - const configuredPath = typeof args?.path === 'string' ? args.path.trim() : '' - if (!configuredPath) { - return args?.requireTrusted === true - ? ensureDefaultFloatingWorkspacePath() - : resolveFloatingWorkspaceInput('~') - } - - const cwd = resolveFloatingWorkspaceInput(configuredPath) - const canonicalCwd = await canonicalizeAccessibleDirectory(cwd) - if (!canonicalCwd) { - return ensureDefaultFloatingWorkspacePath() - } - - // Only picker-approved directories may become terminal cwd. - if (isTrustedFloatingWorkspaceDirectory(canonicalCwd, store.getSettings())) { - return canonicalCwd - } - - return args?.requireTrusted === true ? ensureDefaultFloatingWorkspacePath() : cwd + const selected = await selectFloatingTerminalCwd(store, args) + return selected.prepare ? ensureDefaultFloatingWorkspacePath() : selected.path } export async function trustFloatingWorkspaceDirectory( diff --git a/src/main/ipc/runtime.ts b/src/main/ipc/runtime.ts index 7dadefd1eee..f4c9eaf3e9f 100644 --- a/src/main/ipc/runtime.ts +++ b/src/main/ipc/runtime.ts @@ -1,3 +1,4 @@ +import { registerTerminalModelDiscoveryHandler } from './terminal-model-discovery' import { BrowserWindow, ipcMain } from 'electron' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { @@ -27,6 +28,7 @@ function boundTerminalFitRestore(pending: Promise): Promise { } export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void { + registerTerminalModelDiscoveryHandler(runtime) const pendingTerminalFitRestores = new Map>() const desktopSenders = new DesktopRuntimeSenderLifecycle(runtime) ipcMain.removeHandler('runtime:syncWindowGraph') diff --git a/src/main/ipc/terminal-model-discovery.ts b/src/main/ipc/terminal-model-discovery.ts new file mode 100644 index 00000000000..e749368bd9c --- /dev/null +++ b/src/main/ipc/terminal-model-discovery.ts @@ -0,0 +1,10 @@ +import { ipcMain } from 'electron' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +export function registerTerminalModelDiscoveryHandler(runtime: OrcaRuntimeService): void { + ipcMain.removeHandler('agent:discoverTerminalModels') + ipcMain.handle( + 'agent:discoverTerminalModels', + (_event, args: { agentId: string; worktree?: string }) => + runtime.discoverTerminalModels(args.worktree, args.agentId) + ) +} diff --git a/src/main/providers/local-pty/local-pty-launch-plan.ts b/src/main/providers/local-pty/local-pty-launch-plan.ts index 2c8a710793f..bdc467b9af7 100644 --- a/src/main/providers/local-pty/local-pty-launch-plan.ts +++ b/src/main/providers/local-pty/local-pty-launch-plan.ts @@ -1,3 +1,4 @@ +import { selectEffectiveTerminalExecutionContext } from '../../../shared/terminal/effective-terminal-execution-context' import { win32 as pathWin32 } from 'node:path' import { recognizeAgentProcessFromCommandLine } from '../../../shared/agent-status/process/agent-process-recognition' import { WINDOWS_GIT_BASH_SHELL } from '../../../shared/windows-terminal-shell' @@ -114,9 +115,21 @@ function createWindowsLocalPtyLaunchPlan( process.env.COMSPEC || 'powershell.exe' const shellFamily = worktreeWslContext ? 'wsl.exe' : requestedShellFamily - if (!seed.launchWslContext && pathWin32.basename(shellFamily).toLowerCase() === 'wsl.exe') { - seed.launchWslContext = getWslContextFromPreferredDistro(getDefaultWslDistro()) + const inputs = { + platform: process.platform, + cwd, + worktreeContext: worktreeWslContext, + shell: shellFamily, + preferredDistro: args.terminalWindowsWslDistro } + let selected = selectEffectiveTerminalExecutionContext(inputs) + if (selected.kind === 'unresolved-wsl') { + selected = selectEffectiveTerminalExecutionContext({ + ...inputs, + defaultDistro: getDefaultWslDistro() + }) + } + seed.launchWslContext = selected.kind === 'wsl' ? selected.context : undefined const normalizedShellFamily = pathWin32.basename(shellFamily).toLowerCase() const resolvedGitBashPath = resolveWindowsGitBashShellPath(shellFamily) // Normalize family names and paths so PowerShell resolution can fall back to inbox powershell.exe. diff --git a/src/main/runtime/construction/runtime-construction-services.ts b/src/main/runtime/construction/runtime-construction-services.ts index d3ea3a29649..6ec43aad4d8 100644 --- a/src/main/runtime/construction/runtime-construction-services.ts +++ b/src/main/runtime/construction/runtime-construction-services.ts @@ -281,6 +281,7 @@ export abstract class RuntimeConstructionServices { protected abstract getTrackedDisplayTitleForPty(ptyId: string): string | null protected abstract getLeavesForPty(ptyId: string): readonly RuntimeLeafRecord[] abstract notifyMessageArrived(handle: string, messageType?: string): void + protected abstract resolveGitWorktreeReadSelector(selector: string): Promise protected abstract resolveGitWorktreeSelector( selector: string, requiredHostId?: ExecutionHostId diff --git a/src/main/runtime/construction/runtime-repository-command-state.ts b/src/main/runtime/construction/runtime-repository-command-state.ts index 5322d6433b7..04795926b92 100644 --- a/src/main/runtime/construction/runtime-repository-command-state.ts +++ b/src/main/runtime/construction/runtime-repository-command-state.ts @@ -1,3 +1,4 @@ +import type { RuntimeGitTarget } from '../integrations/git/runtime-git-command-target' import type { RuntimeTerminalAgentStatus } from '../../../shared/runtime-terminal-contracts' import { RuntimeGitCommands } from '../integrations/git/orca-runtime-git' import { RuntimeHostedReviewCommands } from '../integrations/reviews/runtime-hosted-review-commands' @@ -23,8 +24,11 @@ import { import { OrcaRuntimeWithFileCommands } from './runtime-file-command-state' export abstract class OrcaRuntimeWithRepositoryCommands extends OrcaRuntimeWithFileCommands { + protected abstract resolveRuntimeModelDiscoveryTarget(selector: string): Promise protected readonly gitCommands = new RuntimeGitCommands({ resolveRuntimeGitTarget: (selector) => this.resolveRuntimeGitTarget(selector), + resolveRuntimeModelDiscoveryTarget: (selector) => + this.resolveRuntimeModelDiscoveryTarget(selector), getRuntimeSettings: () => this.requireStore().getSettings(), getCommitMessageAgentEnvironment: () => this.accounts.getCommitMessageAgentEnvironment(), // Override the resolver's one-second linked-issue cache so template generation sees link/unlink immediately. diff --git a/src/main/runtime/integrations/git/runtime-git-command-target.ts b/src/main/runtime/integrations/git/runtime-git-command-target.ts index 6fba9ffdd0b..4f3b6e6fa59 100644 --- a/src/main/runtime/integrations/git/runtime-git-command-target.ts +++ b/src/main/runtime/integrations/git/runtime-git-command-target.ts @@ -31,6 +31,7 @@ export type RuntimeGitTarget = { export type RuntimeGitCommandHost = { resolveRuntimeGitTarget(selector: string): Promise + resolveRuntimeModelDiscoveryTarget?(selector: string): Promise getRuntimeSettings(): SourceControlAiSettingsInput getCommitMessageAgentEnvironment?(): CommitMessageAgentEnvironmentResolvers | undefined /** `undefined` keeps cached metadata; `null` is the authoritative unlinked answer. */ diff --git a/src/main/runtime/integrations/git/runtime-git-generation-commands.ts b/src/main/runtime/integrations/git/runtime-git-generation-commands.ts index bfc0007a147..c1f0d53c942 100644 --- a/src/main/runtime/integrations/git/runtime-git-generation-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-generation-commands.ts @@ -1,3 +1,4 @@ +import { isProjectRuntimeRepairRefusal } from '../../../../shared/project-runtime-repair-message' import { textGenerationFailure, textGenerationFailureCodeFields @@ -237,7 +238,16 @@ export class RuntimeGitGenerationCommands { agentId: string, settingsOverride?: Pick ): Promise { - const target = await this.host.resolveRuntimeGitTarget(worktreeSelector) + let target: Awaited> + try { + target = await (this.host.resolveRuntimeModelDiscoveryTarget?.(worktreeSelector) ?? + this.host.resolveRuntimeGitTarget(worktreeSelector)) + } catch (error) { + if (isProjectRuntimeRepairRefusal(error)) { + return { success: false, error: error.message } + } + throw error + } const typedAgentId = agentId as TuiAgent const agentCommandOverride = settingsOverride?.agentCmdOverrides?.[typedAgentId] ?? diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index 5b693508c20..056e75548dd 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -1,3 +1,4 @@ +import { AGENT_MODEL_DISCOVERY_METHODS } from './terminal/agent-model-discovery' import { STATUS_METHODS } from './host-management/status' import { SIDEBAR_INPUT_METHODS } from './sidebar-inputs/sidebar-inputs' import { ORCAD_TERMINAL_CENSUS_METHODS } from './orcad/orcad-terminal-census' @@ -97,6 +98,7 @@ export const ALL_RPC_METHODS = [ ...AGENT_ACTIVITY_METHODS, ...REFERENCE_METHODS, ...AGENT_SESSION_METHODS, + ...AGENT_MODEL_DISCOVERY_METHODS, ...STRUCTURED_AGENT_SESSION_METHODS, ...STRUCTURED_AGENT_SESSION_ATTACHMENT_METHODS, ...STRUCTURED_AGENT_SESSION_VISUAL_METHODS, diff --git a/src/main/runtime/rpc/methods/terminal/agent-model-discovery.ts b/src/main/runtime/rpc/methods/terminal/agent-model-discovery.ts new file mode 100644 index 00000000000..a6340774d10 --- /dev/null +++ b/src/main/runtime/rpc/methods/terminal/agent-model-discovery.ts @@ -0,0 +1,11 @@ +import { defineMethod } from '../../core' +import { AgentDiscoverTerminalModels } from '../../../../../shared/rpc-contract/agent-model-discovery-params' +export const AGENT_MODEL_DISCOVERY_METHODS = [ + defineMethod({ + name: 'agent.discoverTerminalModels', + permission: 'workspace', + params: AgentDiscoverTerminalModels, + handler: (params, { runtime }) => + runtime.discoverTerminalModels(params.worktree, params.agentId) + }) +] diff --git a/src/main/runtime/terminal/catalog/runtime-terminal-model-discovery.ts b/src/main/runtime/terminal/catalog/runtime-terminal-model-discovery.ts new file mode 100644 index 00000000000..81d2cfa82f0 --- /dev/null +++ b/src/main/runtime/terminal/catalog/runtime-terminal-model-discovery.ts @@ -0,0 +1,103 @@ +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' +import { + selectEffectiveTerminalExecutionContext, + TERMINAL_EXECUTION_CONTEXT_UNRESOLVED +} from '../../../../shared/terminal/effective-terminal-execution-context' +import { isWslShellName } from '../../../../shared/local-windows-terminal-runtime' +import { isProjectRuntimeRepairRefusal } from '../../../../shared/project-runtime-repair-message' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { ResolvedTerminalWorkspaceLaunchTarget } from '../launch/terminal-workspace-launch-target' +import { resolveAgentLaunchRuntime } from '../launch/agent-launch-scope-runtime' +import { getWslContextFromWorktreeId } from '../../../providers/local-pty/local-pty-launch-context' +import { listWslDistrosAsync } from '../../../wsl/discovery/distro-catalog' +import { + prepareLocalCommitMessageAgentEnv, + type CommitMessageAgentEnvironmentResolvers +} from '../../../text-generation/commit-message-agent-environment' +import { + discoverCommitMessageModelsLocal, + type DiscoverCommitMessageModelsResult +} from '../../../text-generation/commit-message-text-generation' + +export async function discoverTerminalModels( + context: { + store: RuntimeStore + resolveTarget: () => Promise + hostGlobal?: true + environment?: CommitMessageAgentEnvironmentResolvers + }, + agentId: string +): Promise { + if (!isTuiAgent(agentId)) { + return { success: false, error: 'Unknown agent.' } + } + try { + const target = context.hostGlobal ? undefined : await context.resolveTarget() + const scope = target?.scope ?? { + id: '', + path: '', + connectionId: null, + repo: null, + folderWorkspace: null + } + const owner = scope.folderWorkspace ?? scope.repo + if ( + !isRepoOnCatalogHost({ + executionHostId: target?.managedWorktree?.hostId ?? owner?.executionHostId, + connectionId: scope.connectionId ?? owner?.connectionId + }) + ) { + return { + success: false, + error: 'Terminal model discovery is unavailable on this connection.' + } + } + const runtime = resolveAgentLaunchRuntime(context.store, scope, undefined, agentId) + const shell = runtime.pty.shellOverride || process.env.COMSPEC || 'powershell.exe' + const inputs = { + platform: process.platform, + cwd: scope.path, + worktreeContext: getWslContextFromWorktreeId(scope.id), + shell, + preferredDistro: runtime.pty.terminalWindowsWslDistro + } + let selected = selectEffectiveTerminalExecutionContext(inputs) + if (selected.kind === 'unresolved-wsl' && isWslShellName(shell)) { + selected = selectEffectiveTerminalExecutionContext({ + ...inputs, + defaultDistro: (await listWslDistrosAsync())[0] + }) + } + if (selected.kind === 'unresolved-wsl') { + return { success: false, error: TERMINAL_EXECUTION_CONTEXT_UNRESOLVED } + } + const wslDistro = selected.kind === 'wsl' ? selected.context.distro : undefined + const env = await prepareLocalCommitMessageAgentEnv( + agentId, + context.environment, + wslDistro ? { runtime: 'wsl', wslDistro } : { runtime: 'host' } + ) + if (!env.ok) { + return { success: false, error: env.error } + } + return await discoverCommitMessageModelsLocal( + agentId, + env.env, + context.store.getSettings().agentCmdOverrides?.[agentId], + { + ...(scope.path ? { cwd: scope.path } : {}), + ...(wslDistro ? { wslDistro } : {}) + } + ) + } catch (error) { + if ( + isProjectRuntimeRepairRefusal(error) || + (error instanceof Error && + ['floating_workspace_path_unavailable', 'selector_not_found'].includes(error.message)) + ) { + return { success: false, error: error.message } + } + throw error + } +} diff --git a/src/main/runtime/terminal/launch/terminal-workspace-scope.ts b/src/main/runtime/terminal/launch/terminal-workspace-scope.ts index 2935cfcc8d9..f7547d80e63 100644 --- a/src/main/runtime/terminal/launch/terminal-workspace-scope.ts +++ b/src/main/runtime/terminal/launch/terminal-workspace-scope.ts @@ -16,10 +16,7 @@ import { import { resolveRuntimeBrowserNetworkExecutionHost } from '../../browser/network/runtime-browser-network-execution-host' import { resolveLocalProjectRuntimeForWorktreeId } from '../../../workspaces/execution-host/local-project-runtime-resolution' import { getRegisteredSshState } from '../../../ssh/targets/ssh-target-registry' -import { - resolveWorktreeHostRouting, - resolveWorktreeLaunchHost -} from '../../workspaces/catalog/worktree-launch-host-repo' +import { resolveWorktreeHostRouting } from '../../workspaces/catalog/worktree-launch-host-repo' import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' @@ -29,7 +26,6 @@ import type { TerminalWorkspaceLaunchScope } from '../../orchestration/terminal- import { resolveTerminalStartupCwd } from '../../../../shared/shell/launch/terminal-startup-cwd' import type { ResolvedTerminalWorkspaceLaunchTarget } from './terminal-workspace-launch-target' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { homedir } from 'node:os' import { getExplicitWorktreeIdSelector } from '../../workspaces/catalog/runtime-worktree-selection' import { getRepoIdFromWorktreeId, worktreeIdsEqual } from '../../../../shared/worktree/id' @@ -37,7 +33,7 @@ import { WORKTREE_ID_SEPARATOR } from '../../../../shared/terminal/pty/lifecycle import { getPtyExecutionHost } from '../../../../shared/terminal/pty/lifecycle/terminal-execution-host' import { WorktreeIdRequiresFullPathError } from '../../workspaces/lineage/worktree-id-requires-full-path-error' import { triggerTerminalSpawnPushTargetMaterialization } from './runtime-terminal-spawn-push-target-materialization' -import { resolveCreatedWorktreeTerminalTarget } from './runtime-created-worktree-terminal-target' +import { resolveTerminalWorkspaceTarget } from './terminal-workspace-target-resolution' const AGENT_HOOK_RUNTIME_ENV_KEYS = [ 'ORCA_AGENT_HOOK_PORT', 'ORCA_AGENT_HOOK_TOKEN', @@ -156,65 +152,69 @@ export abstract class OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktr resolvedFolder?: FolderWorkspace, checkPath = true ): Promise { - if (isFloatingWorkspaceSelector(selector)) { - // Why no managed worktree: the floating sentinel has no repo or worktree record behind it. - return { - scope: { - id: FLOATING_TERMINAL_WORKTREE_ID, - path: await this.resolveFloatingWorkspacePath(), - connectionId: null, - repo: null, - folderWorkspace: null - }, - managedWorktree: null - } - } - - const folderScope = await this.resolveFolderWorkspaceLaunchScope( + const target = await this.resolveTerminalWorkspaceTarget( selector, + createdWorktree, options, + resolvedWorktree, resolvedFolder, - checkPath + checkPath, + isFloatingWorkspaceSelector(selector) ? await this.resolveFloatingWorkspacePath() : undefined ) - if (folderScope) { - return { - scope: folderScope, - managedWorktree: this.folderWorkspaceToResolvedWorktree(folderScope.folderWorkspace) - } + const worktree = target.managedWorktree + if (worktree && !target.scope.folderWorkspace) { + triggerTerminalSpawnPushTargetMaterialization( + worktree.path, + worktree.pushTarget, + target.scope.repo, + this.store, + worktree.repoId, + worktree.id + ) } + return target + } - const workspaceSelector = selector.startsWith('id:') ? selector.slice(3) : selector - const parsed = parseWorkspaceKey(workspaceSelector) - const worktreeSelector = parsed?.type === 'worktree' ? `id:${parsed.worktreeId}` : selector - const worktree = - resolvedWorktree ?? - resolveCreatedWorktreeTerminalTarget(this.store, selector, createdWorktree) ?? - (await this.resolveGitWorktreeSelector(worktreeSelector)) - // Repo ids are host-blind; resolve the worktree owner or refuse as unresolved rather than spawn locally with a remote cwd (#11163). - const resolution = resolveWorktreeLaunchHost(this.store?.getRepos() ?? [], worktree) - if (resolution.kind === 'ambiguous') { - throw new Error('worktree_execution_host_unresolved') - } - // Metadata only (display name, hook settings); the routing decision is `resolution.connectionId`. - const repo = resolution.repo ?? this.store?.getRepo(worktree.repoId) ?? null - triggerTerminalSpawnPushTargetMaterialization( - worktree.path, - worktree.pushTarget, - repo, - this.store, - worktree.repoId, - worktree.id - ) - return { - scope: { - id: worktree.id, - path: worktree.path, - connectionId: resolution.connectionId, - repo, - folderWorkspace: null + async resolveTerminalWorkspaceReadTarget( + selector: string + ): Promise { + return resolveTerminalWorkspaceTarget( + { + store: this.store, + resolveFolder: (selector, options, folder, check) => + this.resolveFolderWorkspaceLaunchScope(selector, options, folder, check), + folderWorktree: (folder) => this.folderWorkspaceToResolvedWorktree(folder), + resolveWorktree: (selector) => this.resolveGitWorktreeReadSelector(selector) }, - managedWorktree: worktree - } + selector + ) + } + + private resolveTerminalWorkspaceTarget( + selector: string, + createdWorktree?: Worktree, + options: { wslUserAct?: boolean } = {}, + resolvedWorktree?: ResolvedWorktree, + resolvedFolder?: FolderWorkspace, + checkPath = true, + preparedFloatingPath?: string + ): Promise { + return resolveTerminalWorkspaceTarget( + { + store: this.store, + resolveFolder: (selector, options, folder, check) => + this.resolveFolderWorkspaceLaunchScope(selector, options, folder, check), + folderWorktree: (folder) => this.folderWorkspaceToResolvedWorktree(folder), + resolveWorktree: (selector) => this.resolveGitWorktreeSelector(selector) + }, + selector, + createdWorktree, + options, + resolvedWorktree, + resolvedFolder, + checkPath, + preparedFloatingPath + ) } protected buildTerminalWorkspaceEnv( diff --git a/src/main/runtime/terminal/launch/terminal-workspace-target-resolution.ts b/src/main/runtime/terminal/launch/terminal-workspace-target-resolution.ts new file mode 100644 index 00000000000..c7145b4a113 --- /dev/null +++ b/src/main/runtime/terminal/launch/terminal-workspace-target-resolution.ts @@ -0,0 +1,89 @@ +import { homedir } from 'node:os' +import { isFloatingWorkspaceSelector } from '../../../../shared/floating-workspace-worktree' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' +import { readFloatingTerminalCwd } from '../../../ipc/floating-workspace-directory' +import { resolveWorktreeLaunchHost } from '../../workspaces/catalog/worktree-launch-host-repo' +import { resolveCreatedWorktreeTerminalTarget } from './runtime-created-worktree-terminal-target' +import type { ResolvedTerminalWorkspaceLaunchTarget } from './terminal-workspace-launch-target' +import type { TerminalWorkspaceLaunchScope } from '../../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' + +type TargetHost = { + store: RuntimeStore | null | undefined + resolveFolder: ( + selector: string, + options: { wslUserAct?: boolean }, + folder: FolderWorkspace | undefined, + check: boolean + ) => Promise<(TerminalWorkspaceLaunchScope & { folderWorkspace: FolderWorkspace }) | null> + folderWorktree: (folder: FolderWorkspace) => ResolvedWorktree + resolveWorktree: (selector: string) => Promise +} + +export async function resolveTerminalWorkspaceTarget( + host: TargetHost, + selector: string, + createdWorktree?: Worktree, + options: { wslUserAct?: boolean } = {}, + resolvedWorktree?: ResolvedWorktree, + resolvedFolder?: FolderWorkspace, + checkPath = true, + preparedFloatingPath?: string +): Promise { + if (isFloatingWorkspaceSelector(selector)) { + // Why no managed worktree: the floating sentinel has no repo or worktree record behind it. + return { + scope: { + id: FLOATING_TERMINAL_WORKTREE_ID, + path: + preparedFloatingPath ?? + (host.store + ? await readFloatingTerminalCwd(host.store, { + path: host.store.getSettings().floatingTerminalCwd + }) + : homedir()), + connectionId: null, + repo: null, + folderWorkspace: null + }, + managedWorktree: null + } + } + + const folderScope = await host.resolveFolder(selector, options, resolvedFolder, checkPath) + if (folderScope) { + return { + scope: folderScope, + managedWorktree: host.folderWorktree(folderScope.folderWorkspace) + } + } + + const workspaceSelector = selector.startsWith('id:') ? selector.slice(3) : selector + const parsed = parseWorkspaceKey(workspaceSelector) + const worktreeSelector = parsed?.type === 'worktree' ? `id:${parsed.worktreeId}` : selector + const worktree = + resolvedWorktree ?? + resolveCreatedWorktreeTerminalTarget(host.store, selector, createdWorktree) ?? + (await host.resolveWorktree(worktreeSelector)) + // Repo ids are host-blind; resolve the worktree owner or refuse as unresolved rather than spawn locally with a remote cwd (#11163). + const resolution = resolveWorktreeLaunchHost(host.store?.getRepos() ?? [], worktree) + if (resolution.kind === 'ambiguous') { + throw new Error('worktree_execution_host_unresolved') + } + // Metadata only (display name, hook settings); the routing decision is `resolution.connectionId`. + const repo = resolution.repo ?? host.store?.getRepo(worktree.repoId) ?? null + return { + scope: { + id: worktree.id, + path: worktree.path, + connectionId: resolution.connectionId, + repo, + folderWorkspace: null + }, + managedWorktree: worktree + } +} diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts index 44542d4fff1..4c7b4c672a9 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts @@ -109,7 +109,7 @@ export function listStoredWorktreeRowsForRepo( export type RepoWorktreeRowsScan = { ok: boolean; worktrees: GitWorktreeInfo[] } /** The scan half of `resolveRepoWorktreeRows`: slow, and the only part that awaits. */ -export async function scanRepoWorktreeRows( +export async function readRepoWorktreeRowsScan( deps: Pick, repo: Repo, projectRuntimeByRepoId: ReadonlyMap, @@ -130,12 +130,23 @@ export async function scanRepoWorktreeRows( listStoredWorktreeRowsForRepo(store, repo, repoOwnerCount) } const gitWorktrees = preserveFolderUpgradeWorktreePath(repo, scan.worktrees) - if (scan.ok) { - pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees) - } return { ok: scan.ok, worktrees: gitWorktrees } } +/** Catalog maintenance belongs to launch/listing owners, not read-only inventory. */ +export async function scanRepoWorktreeRows( + deps: Pick, + repo: Repo, + projectRuntimeByRepoId: ReadonlyMap, + repoOwnerCount?: number +): Promise { + const scan = await readRepoWorktreeRowsScan(deps, repo, projectRuntimeByRepoId, repoOwnerCount) + if (scan.ok) { + pruneLineageForMissingRepoWorktrees(deps.store, repo, scan.worktrees) + } + return scan +} + /** The join half: a repo's rows from a scan and the metadata as it is now. Synchronous. */ export function projectRepoWorktreeRows( deps: Pick, diff --git a/src/main/runtime/workspaces/catalog/workspace-catalog.ts b/src/main/runtime/workspaces/catalog/workspace-catalog.ts index 63f9a666def..95d1bc25581 100644 --- a/src/main/runtime/workspaces/catalog/workspace-catalog.ts +++ b/src/main/runtime/workspaces/catalog/workspace-catalog.ts @@ -1,3 +1,4 @@ +import { isFolderRepo } from '../../../../shared/repo-kind' import { OrcaRuntimeWithReadKittyFile } from '../../files/paths/orca-runtime-read-kitty-file' import type { RuntimeWorkspaceRepoScanRefresh } from './workspace-repo-scan-refresh' import type { ResolvedWorktree } from './runtime-worktree-path-identity' @@ -9,6 +10,8 @@ import { getWorktreeScanMutationRevision } from '../../../workspaces/catalog/loc import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution' import { resolveRepoWorktreeRows, + readRepoWorktreeRowsScan, + projectRepoWorktreeRows, resolveScopedWorktreeIdRow, type RepoWorktreeRowDeps } from './repo-worktree-row-resolution' @@ -178,6 +181,31 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi } } + protected async listReadOnlyResolvedWorktrees(worktreeId?: string): Promise { + const store = this.requireStore() + const repoId = worktreeId ? splitWorktreeIdForFilesystem(worktreeId)?.repoId : undefined + const repos = store.getRepos().filter((repo) => !repoId || repo.id === repoId) + const runtimes = resolveLocalProjectRuntimesForRepos(store, repos) + const meta = store.getAllWorktreeMeta() ?? {} + const deps = { + ...this.repoWorktreeRowDeps(), + scanRepo: (repo: Repo) => this.listRepoWorktreesForResolution(repo, runtimes), + listFolderWorkspaces: (repo: Repo, count: number) => + projectRuntimeFolderWorkspaces(store, repo, count) + } + const rows = await Promise.all( + repos.map(async (repo) => + projectRepoWorktreeRows( + deps, + repo, + isFolderRepo(repo) ? null : await readRepoWorktreeRowsScan(deps, repo, runtimes), + meta + ) + ) + ) + return projectResolvedWorktreeLineage(rows.flat(), store.getAllWorktreeLineage?.() ?? {}) + } + protected async resolveExplicitWorktreeIdScoped( worktreeId: string, requiredHostId?: ExecutionHostId diff --git a/src/main/runtime/workspaces/workspace-file-session-targets.ts b/src/main/runtime/workspaces/workspace-file-session-targets.ts index 5e28f2c78d3..0e87098d071 100644 --- a/src/main/runtime/workspaces/workspace-file-session-targets.ts +++ b/src/main/runtime/workspaces/workspace-file-session-targets.ts @@ -1,3 +1,6 @@ +import { discoverTerminalModels } from '../terminal/catalog/runtime-terminal-model-discovery' +import type { ResolvedTerminalWorkspaceLaunchTarget } from '../terminal/launch/terminal-workspace-launch-target' +import { parseWslUncPath } from '../../../shared/wsl-paths' import type { OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktree } from '../terminal/launch/terminal-workspace-scope' import type { OrcaRuntimeWithTransitionGraphReloadToTerminalState } from '../session-graph/session-graph-authority' import type { ResolvedWorktree } from './catalog/runtime-worktree-path-identity' @@ -36,6 +39,22 @@ export abstract class RuntimeWorkspaceFileTargets extends RuntimeMarkdownTabOper OrcaRuntimeWithTransitionGraphReloadToTerminalState['resolveFolderWorkspaceLaunchScope'] > + abstract resolveTerminalWorkspaceReadTarget( + selector: string + ): Promise + + async discoverTerminalModels(worktree?: string, agentId = '') { + return discoverTerminalModels( + { + store: this.requireStore(), + resolveTarget: () => this.resolveTerminalWorkspaceReadTarget(worktree ?? 'floating'), + ...(worktree ? {} : { hostGlobal: true }), + environment: this.accounts.getCommitMessageAgentEnvironment() + }, + agentId + ) + } + // Route by worktree host before repo id: same-id host twins and runtime-nested targets cannot use this client's arbitrary repo row (#11163). protected async resolveRuntimeGitTarget(worktreeSelector: string): Promise<{ worktree: ResolvedWorktree @@ -60,6 +79,19 @@ export abstract class RuntimeWorkspaceFileTargets extends RuntimeMarkdownTabOper return { worktree, repo, executionHostId, localGitOptions } } + protected async resolveRuntimeModelDiscoveryTarget(worktreeSelector: string) { + const scope = await this.resolveFolderWorkspaceLaunchScope(worktreeSelector) + if (!scope?.folderWorkspace) { + return this.resolveRuntimeGitTarget(worktreeSelector) + } + const wsl = parseWslUncPath(scope.path) + return { + worktree: this.folderWorkspaceToResolvedWorktree(scope.folderWorkspace), + executionHostId: getConnectionExecutionHostId(scope.connectionId), + ...(wsl ? { localGitOptions: { wslDistro: wsl.distro } } : {}) + } + } + // Resolve the worktree's filesystem host; getRepo(id) conflates host twins, runtime targets, unresolved owners and local paths (#11163). async resolveRuntimeFileTarget(worktreeSelector: string): Promise<{ worktree: ResolvedWorktree diff --git a/src/main/runtime/workspaces/workspace-selectors.ts b/src/main/runtime/workspaces/workspace-selectors.ts index 1ecdc202f8b..366601170ec 100644 --- a/src/main/runtime/workspaces/workspace-selectors.ts +++ b/src/main/runtime/workspaces/workspace-selectors.ts @@ -43,9 +43,18 @@ export abstract class RuntimeWorkspaceSelectors extends RuntimeProjectLaunchCont ...args: Parameters ): ReturnType - protected abstract listResolvedWorktrees( - ...args: Parameters - ): ReturnType + protected abstract listResolvedWorktrees(): Promise + + protected abstract listReadOnlyResolvedWorktrees(worktreeId?: string): Promise + + protected async resolveGitWorktreeReadSelector(selector: string): Promise { + const explicit = this.getValidatedExplicitWorktreeIdSelector(selector) + return this.matchWorktreeSelector( + selector, + await this.listReadOnlyResolvedWorktrees(explicit ?? undefined), + explicit + ) + } /** The repo-backed catalog only: project-group folder workspaces never match. Resolve a workspace with resolveWorkspaceSelector. */ protected async resolveGitWorktreeSelector( diff --git a/src/preload/api/git-bridge.ts b/src/preload/api/git-bridge.ts index 58607ebc9e1..873f1236e50 100644 --- a/src/preload/api/git-bridge.ts +++ b/src/preload/api/git-bridge.ts @@ -190,6 +190,8 @@ export const gitApi = { sourceControlAi?: unknown agentCmdOverrides?: Record }) => ipcRenderer.invoke('git:generateCommitMessage', args), + discoverTerminalModels: (args: { agentId: string; worktree?: string }) => + ipcRenderer.invoke('agent:discoverTerminalModels', args), discoverCommitMessageModels: (args: { agentId: string worktreePath?: string diff --git a/src/preload/api/git-inspection-api.ts b/src/preload/api/git-inspection-api.ts index 7fa8d767a28..fe1de9d60ce 100644 --- a/src/preload/api/git-inspection-api.ts +++ b/src/preload/api/git-inspection-api.ts @@ -124,6 +124,10 @@ export type GitInspectionApi = { connectionId?: string wakeWslDistro?: boolean }) => Promise + discoverTerminalModels: (args: { + agentId: string + worktree?: string + }) => ReturnType discoverCommitMessageModels: (args: { agentId: string worktreePath?: string diff --git a/src/renderer/src/components/agent/AgentLaunchPicker.tsx b/src/renderer/src/components/agent/AgentLaunchPicker.tsx index 4c28231b0b6..facc9855aef 100644 --- a/src/renderer/src/components/agent/AgentLaunchPicker.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPicker.tsx @@ -28,7 +28,10 @@ import { rowLabel } from '../tab-bar/tab-agent-row-presentation' import type { NewTabAgentMenuModel } from '../tab-bar/use-new-tab-agent-menu-rows' import { useAgentPickerDraftScope } from './AgentLaunchSetupButton' import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' -import { useAgentLaunchPickerInventory } from './use-agent-launch-picker-inventory' +import { + useAgentLaunchPickerInventorySource, + useAgentPickerInventoryEntries +} from './use-agent-launch-picker-inventory' import { agentPickerDraft, type AgentPickerDraft, @@ -58,6 +61,7 @@ export const AgentLaunchPicker = memo( onTriggerEnter, onOpenChange, onCatalogOpen, + catalogDemand, onOpenAgentSettings, defaultAgent, onSetDefault, @@ -83,6 +87,7 @@ export const AgentLaunchPicker = memo( onTriggerEnter?: () => void onOpenChange?: (open: boolean) => void /** Supplied entries own their catalogs; this says which agent's menu the user is viewing. */ + catalogDemand?: ComponentProps['catalogDemand'] onCatalogOpen?: (agent: AgentPickerEntry['agent']) => void onOpenAgentSettings?: (invoker: HTMLButtonElement) => void /** The saved default; with onSetDefault, right-clicking an agent row offers "Set as default". */ @@ -131,12 +136,13 @@ export const AgentLaunchPicker = memo( } }, [onOpenAgentSettings, setOpen]) const [selected, setSelected] = useState() - const observedEntries = useAgentLaunchPickerInventory( + const inventory = useAgentLaunchPickerInventorySource( worktreeId, model, open && !setupDisabled && !suppliedEntries, selected ?? agent ?? undefined ) + const observedEntries = useAgentPickerInventoryEntries(inventory) const entries = suppliedEntries ?? observedEntries const ownsCatalog = suppliedEntries !== undefined const selectAgent = useCallback( @@ -249,6 +255,7 @@ export const AgentLaunchPicker = memo( draftScope={draftScope ?? ownDraftScope} model={model} entries={entries} + catalogDemand={suppliedEntries ? catalogDemand : inventory.observeSurface} initialQuery={initialQuery} searchInputRef={setSearchInput} leadingItems={children} diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx index daf9b9dfd7e..bfd1782bbe7 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx @@ -1,11 +1,15 @@ // @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import { useState, type ComponentProps } from 'react' import userEvent from '@testing-library/user-event' import type * as LaunchSetup from './AgentLaunchSetupButton' import type { AgentLaunchSetupButton } from './AgentLaunchSetupButton' -import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' +import { AgentLaunchPickerMenu, SubscribedAgentLaunchPickerMenu } from './AgentLaunchPickerMenu' +import { + createAgentPickerInventorySource, + observeAgentPickerAcquisition +} from './agent-launch-picker-acquisition' import { DropdownMenu, DropdownMenuContent, @@ -138,3 +142,65 @@ it('lists an agent named by the query before other agents’ model setups', () = fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' }) expect(launch).toHaveBeenCalledWith({ agent: 'codex', kind: 'cli' }, undefined) }) + +it('requests the CLI catalog when the subscribed new-tab menu opens on a terminal default', async () => { + const entry: AgentPickerEntry = { + agent: 'antigravity', + label: 'Antigravity', + rows: [{ agent: 'antigravity', kind: 'cli' }], + surfaces: ['chat', 'terminal'], + defaultSurface: 'terminal', + terminal: {}, + structured: {}, + catalog: { origin: 'unknown' }, + catalogRead: 'unsupported', + sourceCatalogs: { + cli: { catalog: { origin: 'unknown' }, catalogRead: 'pending' } + } + } + const inventory = createAgentPickerInventorySource([entry]) + const read = vi.fn(async () => ({ + origin: 'probe' as const, + fetchedAt: 1, + models: [ + { id: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)', isDefault: false, efforts: [] } + ] + })) + const stop = observeAgentPickerAcquisition( + 'subscribed-new-tab-terminal-demand', + [entry], + { catalog: read, support: async () => undefined }, + { + publish: inventory.publish, + selected: () => undefined, + usesSource: inventory.usesSource, + subscribeDemand: inventory.subscribeDemand + } + ) + try { + render( + + Open + + + + + ) + await waitFor(() => + expect(read).toHaveBeenCalledWith( + expect.objectContaining({ agent: 'antigravity' }), + false, + 'cli', + expect.any(AbortSignal) + ) + ) + expect(await screen.findByRole('menuitem', { name: /Gemini 3.8 Flash \(Low\)/ })).toBeTruthy() + } finally { + cleanup() + stop() + } +}) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx index 90bf546b321..2ccaf585edc 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx @@ -1,3 +1,4 @@ +import { AgentPickerCatalogDemand } from './agent-picker-catalog-demand' import { selectWorktreesByRepo, selectFolderWorkspaces @@ -33,6 +34,7 @@ export function AgentLaunchPickerMenu({ mode, value, draftForEntry, + catalogDemand, runLaunch, entries, hideSearch, @@ -52,6 +54,7 @@ export function AgentLaunchPickerMenu({ mode?: 'launch' | 'select' value?: AgentPickerDraft draftForEntry?: (entry: AgentPickerEntry) => AgentPickerDraft + catalogDemand?: AgentPickerInventorySource['observeSurface'] runLaunch: AgentPickerMenuLaunch entries: AgentPickerEntry[] hideSearch?: boolean @@ -94,6 +97,19 @@ export function AgentLaunchPickerMenu({ mode ) }, [entries, draftScope, mode, setupDisabled]) + useEffect(() => { + if (setupDisabled) { + return + } + const stops = entries.map((entry) => + catalogDemand?.( + entry.agent, + (value?.agent === entry.agent ? value.surface : draftForEntry?.(entry)?.surface) ?? + entry.defaultSurface + ) + ) + return () => stops.forEach((stop) => stop?.()) + }, [entries, value, draftForEntry, catalogDemand, setupDisabled]) const terminalBlocked = mode !== 'select' && model?.state === 'settled' && model.terminalPending const [query, setQuery] = useState(initialQuery) const [searchFocused, setSearchFocused] = useState(false) @@ -105,7 +121,16 @@ export function AgentLaunchPickerMenu({ } | null>(null) const openSetup = activeSetup?.id ?? null const root = useRef(null) - const setups = setupDisabled ? [] : searchAgentPickerSetups(entries, query) + const setups = setupDisabled + ? [] + : searchAgentPickerSetups( + entries, + query, + 8, + (entry) => + (value?.agent === entry.agent ? value.surface : draftForEntry?.(entry)?.surface) ?? + entry.defaultSurface + ) const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean) const visible = entries.filter((entry) => words.every((word) => `${entry.agent} ${entry.label}`.toLowerCase().includes(word)) @@ -125,6 +150,9 @@ export function AgentLaunchPickerMenu({ ) { setups.push({ entry, + surface: + (value?.agent === entry.agent ? value.surface : draftForEntry?.(entry)?.surface) ?? + entry.defaultSurface, model: { id: activeSetup.preset.model, label: activeSetup.label, @@ -150,127 +178,133 @@ export function AgentLaunchPickerMenu({ showBlankTerminal || firstEntry ? undefined : setups.find((setup) => enabled(setup.entry)) const showSearchDefault = searchFocused && query.trim().length > 0 return ( -
- {!hideSearch ? ( -
- setSearchFocused(false)} - onFocus={(event) => { - setSearchFocused(true) - // Why: a seeded query must keep the caret after the typed key. - const end = event.currentTarget.value.length - event.currentTarget.setSelectionRange(end, end) - }} - placeholder={ - setupDisabled - ? t('agentPicker.searchAgents', 'Search agents…') - : t('agentPicker.search', 'Search, e.g. Opus 5.5…') - } - onChange={(event) => setQuery(event.target.value)} - onKeyDown={(event) => { - if (event.key === 'Escape') { - return + +
+ {!hideSearch ? ( +
+ setSearchFocused(false)} + onFocus={(event) => { + setSearchFocused(true) + // Why: a seeded query must keep the caret after the typed key. + const end = event.currentTarget.value.length + event.currentTarget.setSelectionRange(end, end) + }} + placeholder={ + setupDisabled + ? t('agentPicker.searchAgents', 'Search agents…') + : t('agentPicker.search', 'Search, e.g. Opus 5.5…') } - event.stopPropagation() - if (event.key === 'Enter' || event.key === 'ArrowDown') { - event.preventDefault() - const results = - event.key === 'Enter' - ? '[data-agent-picker-agent-results]' - : '[data-agent-picker-results]' - const first = root.current?.querySelector( - `${results} [role="menuitem"]:not([data-disabled])` - ) - if (event.key === 'Enter') { - first?.click() - } else { - first?.focus() + onChange={(event) => setQuery(event.target.value)} + onKeyDown={(event) => { + if (event.key === 'Escape') { + return } - } - }} - /> -
- ) : null} -
- {leadingItems} -
- {showBlankTerminal ? ( - onSetDefault('blank') : undefined} - > - ( + `${results} [role="menuitem"]:not([data-disabled])` + ) + if (event.key === 'Enter') { + first?.click() + } else { + first?.focus() + } + } + }} + /> +
+ ) : null} +
+ {leadingItems} +
+ {showBlankTerminal ? ( + onSetDefault('blank') : undefined} > - - {t('auto.components.agent.AgentCombobox.986f946354', 'Blank Terminal')} + + + {t('auto.components.agent.AgentCombobox.986f946354', 'Blank Terminal')} + + + ) : null} + {visible.map((entry) => { + const source = draftForEntry?.(entry) + return ( + + ) + })} + {setups.map((setup) => { + const source = draftForEntry?.(setup.entry) + return ( + + ) + })} + {!showBlankTerminal && !visible.length && !setups.length ? ( + + {t( + 'auto.components.agent.AgentCombobox.579c768bde', + 'No agents match your search.' + )} - - ) : null} - {visible.map((entry) => { - const source = draftForEntry?.(entry) - return ( - - ) - })} - {setups.map((setup) => { - const source = draftForEntry?.(setup.entry) - return ( - - ) - })} - {!showBlankTerminal && !visible.length && !setups.length ? ( - - {t('auto.components.agent.AgentCombobox.579c768bde', 'No agents match your search.')} - - ) : null} + ) : null} +
-
+
) } @@ -282,5 +316,7 @@ export function SubscribedAgentLaunchPickerMenu({ inventory: AgentPickerInventorySource }) { const entries = useAgentPickerInventoryEntries(inventory) - return + return ( + + ) } diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx index ce63771d05c..5ae36a84470 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx @@ -43,6 +43,7 @@ export const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ draftScope, draftId, initialModel, + initialSurface, initialEffort, openSetup, onSetupOpenChange, @@ -63,6 +64,7 @@ export const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ entry: AgentPickerEntry draftScope?: object draftId?: string + initialSurface?: AgentPickerSurface initialModel?: string initialEffort?: string openSetup: string | null @@ -95,13 +97,20 @@ export const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ const setupId = useId() const preset = initialModel ? { model: initialModel, effort: initialEffort } : undefined const initial = preset - ? applyAgentPickerEdit(entry, selected ?? source ?? agentPickerDraft(entry), { - kind: 'choice', - patch: { - model: preset.model, - ...(preset.effort ? { options: { effort: preset.effort } } : {}) + ? applyAgentPickerEdit( + entry, + { + ...(selected ?? source ?? agentPickerDraft(entry)), + ...(initialSurface ? { surface: initialSurface } : {}) + }, + { + kind: 'choice', + patch: { + model: preset.model, + ...(preset.effort ? { options: { effort: preset.effort } } : {}) + } } - }) + ) : undefined const closeMenu = useDropdownMenuClose() const surface = @@ -148,7 +157,7 @@ export const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ entry={entry} initial={source} seed={initial ?? selected ?? source} - surface={selected?.surface} + surface={initialSurface ?? selected?.surface} mode={mode} terminalBlocked={terminalBlocked} open={openSetup === setupId} diff --git a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx index a955acefea8..e2abc455e56 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx @@ -1,3 +1,4 @@ +import { useAgentPickerCatalogDemand } from './agent-picker-catalog-demand' import { useState, type ReactElement } from 'react' import { AgentLaunchSetupSubmenu } from './AgentLaunchSetupSubmenu' import { useTranslate } from '@/i18n/use-translate' @@ -83,6 +84,7 @@ export function AgentLaunchSetupButton({ mode, open }) + useAgentPickerCatalogDemand(entry.agent, setup.draft.surface, open) const changeOpen = (next: boolean) => { if (next) { setup.activate() diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index 0ec1032f1f5..9d1123d51eb 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -1,3 +1,4 @@ +import { agentPickerCatalogView } from '../../../../shared/agent-launch/picker/agent-launch-picker-source' import { AgentLaunchTextModelDefault } from './AgentLaunchTextModelDefault' import { textActionArgumentsOwnModel } from '../../../../shared/agent-launch/picker/agent-launch-picker-text-action' import type { AgentLaunchSetupPanelProps } from './AgentLaunchSetupButton' @@ -40,14 +41,11 @@ import { applyAgentPickerEdit, type AgentPickerEdit } from '../../../../shared/agent-launch/picker/agent-launch-picker-edits' -import { - agentPickerArgumentsKnown, - agentPickerCatalogAuthoritative -} from '../../../../shared/agent-launch/picker/agent-launch-picker-authority' +import { agentPickerArgumentsKnown } from '../../../../shared/agent-launch/picker/agent-launch-picker-authority' import { agentPickerEffectiveChoices } from '../../../../shared/agent-launch/picker/agent-launch-picker' -import type { AgentPickerSurface } from '../../../../shared/agent-launch/picker/agent-launch-picker' import { agentPickerModels, + agentPickerNamesConfiguredModel, agentPickerEntryOptions, agentPickerPermissions } from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' @@ -77,21 +75,26 @@ export function AgentLaunchSetupPanel({ const argumentsKnown = agentPickerArgumentsKnown(entry, draft) const effective = agentPickerEffectiveChoices(entry, draft) const argumentsView = agentPickerPanelArguments(entry, draft) + const view = agentPickerCatalogView(entry, draft.surface) const models = agentPickerModels(entry, draft.surface) const defaultsPending = draft.surface === 'chat' ? entry.structuredDefaultsPending : entry.defaultsPending const seed = getAgentSessionOptionLaunchCatalog(entry.agent) - const listedDefaultKnown = - entry.catalog.origin !== 'unknown' && - (entry.catalog.listingNamesConfiguredModel ?? seed?.hostListingNamesConfiguredModel === true) const currentModel = argumentsView.choices.model ?? effective.model ?? - (!draft.delegated?.includes('model') && !defaultsPending && listedDefaultKnown + (!draft.delegated?.includes('model') && + !defaultsPending && + agentPickerNamesConfiguredModel(entry, draft.surface) ? models.find((model) => model.isDefault)?.id : undefined) // Settled with nothing chosen still lets the user pick; nothing is checked and the agent keeps its own default. - const { hasModels, catalogPending, catalogMessage } = catalogOf(entry, models, currentModel, mode) + const { canSearch, catalogPending, catalogMessage } = catalogOf( + { ...entry, ...view }, + models, + currentModel, + mode + ) const modelInArguments = textActionArgumentsOwnModel(entry, draft) const modelDisabled = disabled || defaultsPending || catalogPending const modelRows = agentLaunchSetupModelRows( @@ -136,11 +139,11 @@ export function AgentLaunchSetupPanel({ onAction={() => {}} /> ) : null - const handleUse = (surface: AgentPickerSurface) => { + const handleUse = (surface: AgentLaunchSetupPanelProps['draft']['surface']) => { const current = getDraft() return current ? onUse({ ...acceptAgentPickerArguments(entry, current), surface }) : false } - const use = (surface: AgentPickerSurface) => + const use = (surface: AgentLaunchSetupPanelProps['draft']['surface']) => mode === 'select' ? handleUse(surface) : footer.current?.launch(surface) const choiceChips = agentModelChoiceChips( entry.agent, @@ -234,7 +237,7 @@ export function AgentLaunchSetupPanel({ {catalogMessage}
) : null} - {hasModels && modelQuery && agentPickerCatalogAuthoritative(entry) ? ( + {canSearch && modelQuery ? ( {t('agentPicker.noModels', 'No models match your search.')} ) : null} diff --git a/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts b/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts index 61dc3cb3aca..5d522d05058 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts @@ -1,5 +1,6 @@ import { expect, it, onTestFinished, vi } from 'vitest' import { + createAgentPickerInventorySource, currentAgentPickerAcquisition, observeAgentPickerAcquisition } from './agent-launch-picker-acquisition' @@ -111,6 +112,50 @@ it('settles closed catalog reads and resumes their refresh when the picker reope expect(currentAgentPickerAcquisition('closed-catalog')).toBeUndefined() }) +it('admits independent protocol jobs into the existing bounded queue and preserves both views', async () => { + const entry: AgentPickerEntry = { + ...codex, + agent: 'antigravity', + surfaces: ['chat', 'terminal'], + defaultSurface: 'chat' + } + const acp = Promise.withResolvers() + const cli = Promise.withResolvers() + const sources: string[] = [] + let entries: AgentPickerEntry[] = [] + const reads = { + catalog: (_entry: AgentPickerEntry, _wait: boolean, source = 'structured') => { + sources.push(source) + return source === 'cli' ? cli.promise : acp.promise + }, + support: async () => undefined + } + const inventory = createAgentPickerInventorySource([entry]) + const observer = { + usesSource: inventory.usesSource, + subscribeDemand: inventory.subscribeDemand, + selected: () => entry.agent, + publish: (next: AgentPickerEntry[]) => { + entries = next + } + } + const stop = observeAgentPickerAcquisition('two-protocols', [entry], reads, observer) + expect(sources).toEqual(['structured']) + stop() + const reopen = observeAgentPickerAcquisition('two-protocols', [entry], reads, observer) + expect(sources).toEqual(['structured']) + const stopTerminal = inventory.observeSurface?.(entry.agent, 'terminal') + expect(sources).toEqual(['structured', 'cli']) + cli.resolve({ origin: 'probe', fetchedAt: 1, models: [model('variant-low')] }) + await expect.poll(() => entries[0].sourceCatalogs?.cli?.catalogRead).toBe('settled') + expect(entries[0].catalogRead).toBe('pending') + acp.resolve({ origin: 'probe', fetchedAt: 1, models: [model('base')] }) + await expect.poll(() => entries[0].catalogRead).toBe('settled') + expect(entries[0].sourceCatalogs?.cli?.catalog).toMatchObject({ models: [{ id: 'variant-low' }] }) + stopTerminal?.() + reopen() +}) + it('waits again only when a wait outlasted its budget, then stops once the listing has ended', async () => { vi.useFakeTimers() onTestFinished(() => { diff --git a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts index 871f38dd813..0607c2b6e7a 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts @@ -2,6 +2,7 @@ import { agentPickerCatalogJobs, agentPickerCatalogFailure, updateAgentPickerCatalog, + agentPickerSourceView, type AgentPickerCatalogJob } from './agent-picker-catalog-jobs' export { @@ -9,6 +10,7 @@ export { useAgentPickerInventoryEntries, type AgentPickerInventorySource } from './agent-picker-inventory-source' +import { AgentPickerSourceDemand, agentPickerCatalogDemanded } from './agent-picker-source-demand' import { shallow } from 'zustand/shallow' import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' import type { @@ -28,7 +30,7 @@ class AgentPickerAcquisition { readonly observers = new Set() entries: AgentPickerEntry[] settingsPending = false - private demand?: AbortController + private demand = new AgentPickerSourceDemand() private outstanding = { catalog: 0, refresh: 0, support: 0 } private queued: Record> private supports = new Map() @@ -63,7 +65,6 @@ class AgentPickerAcquisition { const first = this.observers.size === 0 this.observers.add(observer) if (first) { - this.demand = new AbortController() this.catalogSubscriptions = this.jobs.map( (job, index) => this.reads.observeCatalog?.( @@ -80,11 +81,12 @@ class AgentPickerAcquisition { } this.publish() this.admit('catalog') - } + }, + job.source ) ?? (() => {}) ) for (const [index, job] of this.jobs.entries()) { - const view = this.entries[job.index] + const view = agentPickerSourceView(this.entries[job.index], job.source) if ( view.catalogRead !== 'pending' && (view.catalog.origin === 'unknown' || @@ -109,14 +111,20 @@ class AgentPickerAcquisition { } this.entries = this.project() } + const stopDemand = observer.subscribeDemand?.(() => { + this.demand.reconcile((index) => this.usesSource(index)) + this.admit('catalog') + this.admit('refresh') + }) observer.publish(this.entries) this.admit('catalog') this.admit('refresh') this.admit('support') return () => { + stopDemand?.() this.observers.delete(observer) + this.demand.reconcile((index) => this.usesSource(index)) if (!this.observers.size) { - this.demand?.abort() this.catalogSubscriptions.forEach((stop) => stop()) this.catalogSubscriptions = [] } @@ -140,6 +148,9 @@ class AgentPickerAcquisition { ...entry, catalog: this.entries[i].catalog, catalogRead: this.entries[i].catalogRead, + ...(this.entries[i].sourceCatalogs + ? { sourceCatalogs: this.entries[i].sourceCatalogs } + : {}), ...(read ? { structured: (current && read.value) || entry.structured, @@ -176,8 +187,8 @@ class AgentPickerAcquisition { private async readCatalog(entry: AgentPickerEntry, index: number, waitForListing: boolean) { const job = this.jobs[index] - const signal = this.demand!.signal - const catalog = await this.reads.catalog(entry, waitForListing, signal) + const signal = this.demand.signal(index) + const catalog = await this.reads.catalog(entry, waitForListing, job.source, signal) if (job !== this.jobs[index]) { return } @@ -190,7 +201,7 @@ class AgentPickerAcquisition { // An open picker waits on a running listing, and again when a wait used its whole budget. const refresh = !signal.aborted && - this.observers.size > 0 && + this.usesSource(index) && (waitForListing ? catalog?.waitExpired : catalog?.listingInProgress) === true if (refresh) { this.queued.refresh.add(index) @@ -201,9 +212,22 @@ class AgentPickerAcquisition { }) } + private usesSource(index: number) { + const job = this.jobs[index] + return agentPickerCatalogDemanded(this.entries[job.index], job.source, this.observers) + } + private admit(kind: ReadKind) { while (this.observers.size && this.outstanding[kind] < 2 && this.queued[kind].size) { - const usable = [...this.queued[kind]] + const usable = [...this.queued[kind]].filter((index) => { + if (kind === 'support') { + return true + } + return this.usesSource(index) + }) + if (!usable.length) { + break + } const priorities = [...this.observers].map((o) => o.selected()) const index = usable.find((index) => diff --git a/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts b/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts index a51d5ba93a3..66682985193 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts @@ -1,4 +1,6 @@ -import type { AgentSessionModelCatalogResult } from '../../../../shared/agent-session/agent-session-wire' +import type { ModelCatalogSource } from '../../../../shared/agent-session/options/model-catalog-source' +import type { RuntimeGitContext } from '@/runtime/source-control/git/runtime-git-client-context' +import { cliModelMenuScope } from '@/runtime/native-chat/model-catalogs/model-menu-cli-catalog' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { parseStructuredLaunchSeedOptions } from '../../../../shared/native-chat/input/native-chat-session-option-defaults' import { isAgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' @@ -14,12 +16,15 @@ import { export function agentPickerModelCatalogReads(input: { target: RuntimeClientTarget selector?: string + cliContext?: RuntimeGitContext + cliRuntime?: boolean + invocationKey?: string nativeRuntime: boolean platform?: NodeJS.Platform settings: AgentPickerDefaultSettings | null | undefined serverSettings?: () => Promise }) { - const resolveScope = async (entry: AgentPickerEntry) => { + const resolveScope = async (entry: AgentPickerEntry, source: ModelCatalogSource) => { const server = input.serverSettings ? await input.serverSettings() : input.settings if (input.serverSettings && !server) { return undefined @@ -28,8 +33,8 @@ export function agentPickerModelCatalogReads(input: { input.settings?.agentCmdOverrides?.[entry.agent] ?? server?.agentCmdOverrides?.[entry.agent] if ( !modelMenuUsesHostCatalog({ - nativeRuntime: input.nativeRuntime, - registered: entry.catalogRead !== 'unsupported', + nativeRuntime: source === 'cli' ? input.cliRuntime === true : input.nativeRuntime, + registered: source === 'cli' ? !!input.cliContext : entry.catalogRead !== 'unsupported', commandOverride: command, serverCommandOverride: server?.agentCmdOverrides?.[entry.agent], paired: input.target.kind === 'environment', @@ -38,45 +43,41 @@ export function agentPickerModelCatalogReads(input: { ) { return undefined } - return { - target: input.target, - agent: entry.agent, - ...(input.selector ? { worktree: input.selector } : {}) - } + return source === 'cli' && input.cliContext + ? cliModelMenuScope(input.cliContext, entry.agent, command ?? '', input.invocationKey) + : { + target: input.target, + agent: entry.agent, + ...(input.selector ? { worktree: input.selector } : {}) + } } return { - catalog: async (entry: AgentPickerEntry, waitForListing = false, signal: AbortSignal) => { - if (signal.aborted) { - return undefined - } - if (entry.agent === 'antigravity') { - return callStructuredAgentSession( - input.target, - 'agentSession.modelCatalog', - { - ...(input.selector ? { worktree: input.selector } : {}), - agent: entry.agent, - ...(waitForListing ? { waitForListing } : {}) - } - ) - } - const scope = await resolveScope(entry) - return signal.aborted - ? undefined - : scope - ? hostModelMenuCatalog(scope).read(waitForListing, signal) - : { origin: 'unknown' as const } - }, + catalog: async ( + entry: AgentPickerEntry, + waitForListing = false, + source: ModelCatalogSource = 'structured', + signal: AbortSignal + ) => + signal.aborted + ? Promise.resolve(undefined) + : resolveScope(entry, source).then((scope) => + signal.aborted + ? undefined + : scope + ? hostModelMenuCatalog(scope).read(source === 'cli', waitForListing, signal) + : { origin: 'unknown' as const } + ), observeCatalog: ( entry: AgentPickerEntry, - publish: (snapshot: HostModelMenuSnapshot & { invalidated?: boolean }) => void + publish: (snapshot: HostModelMenuSnapshot & { invalidated?: boolean }) => void, + source: ModelCatalogSource = 'structured' ) => { - if (entry.agent === 'antigravity' || entry.catalogRead === 'unsupported') { + if (source === 'structured' && entry.catalogRead === 'unsupported') { return () => {} } let disposed = false let unsubscribe = () => {} - void resolveScope(entry).then((scope) => { + void resolveScope(entry, source).then((scope) => { if (!scope || disposed) { return } diff --git a/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts b/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts index 94a270f9890..19dc9dfa69a 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts @@ -93,3 +93,52 @@ it('preserves edited presets until a completed catalog confirms their model or e 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([ + [ + '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([]) +}) diff --git a/src/renderer/src/components/agent/agent-launch-picker-retirement.ts b/src/renderer/src/components/agent/agent-launch-picker-retirement.ts index d1020b1bd80..96b95de2dbd 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-retirement.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-retirement.ts @@ -1,3 +1,4 @@ +import { agentPickerCatalogView } from '../../../../shared/agent-launch/picker/agent-launch-picker-source' import { agentPickerCatalogAuthoritative, type AgentPickerRetainedSetup @@ -19,30 +20,31 @@ export function retireAgentPickerSetups( entry.rows[0]?.executionHostId ?? 'local', entry.agent ]) - const membership = new Map( - entries.map((entry) => [ - entryKey(entry), - agentPickerCatalogAuthoritative(entry) - ? new Map( - entry.catalog.models.map((model) => [ - model.id, - model.effortsKnown === false - ? undefined - : new Set(model.efforts.map((effort) => effort.value)) - ]) - ) - : undefined - ]) - ) + const entriesByKey = new Map(entries.map((entry) => [entryKey(entry), entry])) + const memberships = new Map | undefined>>() const retire = ( drafts: Map, currentKey?: string, currentOwner?: { workspaceId: string; executionHostId: string } ) => { for (const [key, retained] of drafts) { - const models = membership.get( + const entry = entriesByKey.get( currentKey ?? JSON.stringify([retained.target?.key, retained.agent]) ) + 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) { + models = new Map( + catalog.models.map((model) => [ + model.id, + model.effortsKnown === false + ? undefined + : new Set(model.efforts.map((effort) => effort.value)) + ]) + ) + memberships.set(catalog, models) + } // Accepted relocation owns the slot now; an obsolete address cannot retire its options. const target = retained.target && currentOwner diff --git a/src/renderer/src/components/agent/agent-launch-picker-runtime.ts b/src/renderer/src/components/agent/agent-launch-picker-runtime.ts index a2c618a57e8..4cc1e77f437 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-runtime.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-runtime.ts @@ -29,6 +29,24 @@ export function agentPickerUsesNativeRuntime( ) } +export function agentPickerCliReadOptions( + target: RuntimeClientTarget, + worktreeId: string | undefined, + worktreePath: string, + route: AgentLaunchRoutingInput, + generation: readonly unknown[] +) { + return { + cliRuntime: + route.projectExecutionKind !== 'ssh' && route.projectRuntime?.status !== 'repair-required', + invocationKey: + target.kind === 'local' && !worktreeId && !worktreePath + ? undefined + : JSON.stringify([...generation, route.projectRuntime, worktreePath]), + cliContext: { target, worktreeId, worktreePath } + } +} + export function agentPickerHostPlatform( target: RuntimeClientTarget | null | undefined, statuses: AppState['runtimeStatusByEnvironmentId'] @@ -37,3 +55,19 @@ export function agentPickerHostPlatform( ? lastVerifiedRuntimeStatus(statuses.get(target.environmentId))?.hostPlatform : getRendererAppPlatform() } + +export function agentPickerCatalogAvailability( + target: RuntimeClientTarget | null | undefined, + route: AgentLaunchRoutingInput, + workspaceId: string | undefined, + nativeRuntime: boolean +) { + return { + structured: !!target && nativeRuntime, + cli: + !!target && + route.projectExecutionKind !== 'ssh' && + route.projectRuntime?.status !== 'repair-required' && + (target.kind === 'local' || !!workspaceId) + } +} diff --git a/src/renderer/src/components/agent/agent-launch-picker-source-routing.test.ts b/src/renderer/src/components/agent/agent-launch-picker-source-routing.test.ts new file mode 100644 index 00000000000..3088b6464dd --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-source-routing.test.ts @@ -0,0 +1,169 @@ +import { agentPickerCatalogAvailability } from './agent-launch-picker-runtime' +import { + withAgentPickerCatalogAvailability, + agentPickerCatalogJobs +} from './agent-picker-catalog-jobs' +import { + agentPickerModelMenu, + agentPickerModels +} from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' +import { beforeEach, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ discover: vi.fn(), structured: vi.fn() })) +vi.mock('@/runtime/native-chat/model-catalogs/terminal-model-discovery-client', () => ({ + discoverRuntimeTerminalModels: mocks.discover +})) +vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: mocks.structured +})) +import { agentPickerModelCatalogReads } from './agent-launch-picker-host-reads' +import { cliModelCatalogAnswer } from '@/runtime/native-chat/model-catalogs/model-menu-cli-catalog' +import { resetHostModelCatalogSnapshotsForTests } from '@/runtime/native-chat/model-catalogs/host-model-catalog-snapshots' +import { projectAgentLaunchProfile } from '../../../../shared/agent-launch/choices/agent-launch-profile' +import { cliResult, sourceEntry } from './agent-launch-picker-sources.test-fixture' + +beforeEach(() => { + mocks.discover.mockReset().mockResolvedValue(cliResult) + mocks.structured.mockReset() + resetHostModelCatalogSnapshotsForTests() +}) + +it('consumes legacy rows without claiming a configured default and separates fallback from verified empty', () => { + expect( + cliModelCatalogAnswer('antigravity', { ...cliResult, catalogOrigin: undefined }) + ).toMatchObject({ + origin: 'probe', + listingNamesConfiguredModel: false, + models: [ + { id: 'gemini-3.8-flash-high', isDefault: false, efforts: [] }, + { id: 'gemini-3.8-flash-medium' }, + { id: 'gemini-3.8-flash-low' }, + { id: 'claude-sonnet-4-6' } + ] + }) + expect( + cliModelCatalogAnswer('antigravity', { ...cliResult, catalogOrigin: 'spec' }) + ).toBeUndefined() + expect( + cliModelCatalogAnswer('antigravity', { success: false, error: 'unsupported' }) + ).toBeUndefined() + expect(cliModelCatalogAnswer('antigravity', { ...cliResult, models: [] })).toMatchObject({ + origin: 'probe', + models: [] + }) + expect( + cliModelCatalogAnswer('antigravity', { ...cliResult, catalogOrigin: undefined, models: [] }) + ).toBeUndefined() +}) + +it('uses the guest CLI route, retains its last good list on failure, and never falls through remote global discovery to this Mac', async () => { + const target = { kind: 'local' } as const + const cliContext = { + target, + worktreeId: 'folder:guest', + worktreePath: '\\\\wsl.localhost\\Ubuntu\\work' + } + const reads = agentPickerModelCatalogReads({ + target, + cliContext, + cliRuntime: true, + nativeRuntime: false, + settings: {} + }) + const entry = { ...sourceEntry(), catalogRead: 'unsupported' as const } + const answer = await reads.catalog(entry, false, 'cli', new AbortController().signal) + expect(answer).toMatchObject({ + models: [ + { id: 'gemini-3.8-flash-high' }, + { id: 'gemini-3.8-flash-medium' }, + { id: 'gemini-3.8-flash-low' }, + { id: 'claude-sonnet-4-6' } + ] + }) + expect(mocks.discover).toHaveBeenCalledWith({ ...cliContext, prefs: undefined }, 'antigravity') + mocks.discover.mockResolvedValueOnce({ success: false, error: 'offline' }) + expect(await reads.catalog(entry, false, 'cli', new AbortController().signal)).toEqual(answer) + mocks.discover.mockClear() + const remote = { kind: 'environment', environmentId: 'remote-global' } as const + const global = agentPickerModelCatalogReads({ + target: remote, + cliContext: { target: remote, worktreeId: undefined, worktreePath: '' }, + cliRuntime: true, + nativeRuntime: true, + settings: {}, + serverSettings: async () => ({}) + }) + expect(await global.catalog(entry, false, 'cli', new AbortController().signal)).toBeUndefined() + expect(mocks.discover).not.toHaveBeenCalled() + const overridden = agentPickerModelCatalogReads({ + target, + cliContext, + cliRuntime: true, + nativeRuntime: false, + settings: { agentCmdOverrides: { antigravity: 'MODE=x agy' } } + }) + expect(await overridden.catalog(entry, false, 'cli', new AbortController().signal)).toEqual({ + origin: 'unknown' + }) + expect(mocks.discover).not.toHaveBeenCalled() +}) + +it('settles unsupported terminal source routes without leaving a listing placeholder', () => { + const route = { + agent: 'antigravity' as const, + settings: {}, + executionHostId: 'ssh:host', + hostCapabilities: null, + projectExecutionKind: 'ssh' as const + } + const entry = withAgentPickerCatalogAvailability( + { ...sourceEntry(), catalog: { origin: 'unknown' }, sourceCatalogs: undefined }, + agentPickerCatalogAvailability(null, route, 'folder:f', false) + ) + expect(agentPickerCatalogJobs([entry])).toEqual([]) + expect(agentPickerModelMenu(entry, 'terminal')).toMatchObject({ status: 'builtin', rows: [] }) + const remote = { kind: 'environment', environmentId: 'host-global' } as const + const global = withAgentPickerCatalogAvailability( + { ...sourceEntry(), sourceCatalogs: undefined }, + agentPickerCatalogAvailability( + remote, + { ...route, projectExecutionKind: 'host' }, + undefined, + true + ) + ) + expect(agentPickerCatalogJobs([global])).toEqual([{ index: 0, source: 'structured' }]) + expect(agentPickerModelMenu(global, 'terminal')).toMatchObject({ status: 'builtin', rows: [] }) +}) + +it('does not promote the legacy Config default fallback into a terminal operand', () => { + const answer = cliModelCatalogAnswer('antigravity', { + ...cliResult, + catalogOrigin: undefined, + models: [{ id: 'default', label: 'Changed or translated label' }], + defaultModelId: 'default' + }) + expect(answer).toBeUndefined() + const entry = sourceEntry('terminal') + entry.sourceCatalogs = { + cli: { catalog: answer ?? { origin: 'unknown' }, catalogRead: 'settled', coherentCatalog: true } + } + expect(agentPickerModels(entry, 'terminal')).toEqual([]) + expect( + projectAgentLaunchProfile('antigravity', {}, { target: 'terminal', choices: {}, userArgs: '' }) + .args + ).toBe('') +}) + +it('consumes explicit probe provenance even for empty lists and the literal default ID', () => { + expect( + cliModelCatalogAnswer('antigravity', { ...cliResult, models: [], catalogOrigin: 'probe' }) + ).toMatchObject({ origin: 'probe', models: [] }) + expect( + cliModelCatalogAnswer('antigravity', { + ...cliResult, + catalogOrigin: 'probe', + defaultModelId: 'default', + models: [{ id: 'default', label: 'Config default' }] + }) + ).toMatchObject({ origin: 'probe', models: [{ id: 'default' }] }) +}) diff --git a/src/renderer/src/components/agent/agent-launch-picker-sources.test-fixture.ts b/src/renderer/src/components/agent/agent-launch-picker-sources.test-fixture.ts new file mode 100644 index 00000000000..473358e4668 --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-sources.test-fixture.ts @@ -0,0 +1,66 @@ +import { parseAntigravityModels } from '../../../../shared/source-control/ai/generation/commit-message-model-parsers' +import { getCommitMessageAgentCapability } from '../../../../shared/source-control/ai/generation/commit-message-agent-spec' +import { cliModelCatalogAnswer } from '@/runtime/native-chat/model-catalogs/model-menu-cli-catalog' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' + +// Recorded agy 1.4.11 models rows; IDs are protocol operands, including the non-suffix ID. +export const cliOutput = + 'gemini-3.8-flash-high\tGemini 3.8 Flash (High)\ngemini-3.8-flash-medium\tGemini 3.8 Flash (Medium)\ngemini-3.8-flash-low\tGemini 3.8 Flash (Low)\nclaude-sonnet-4-6\tClaude Sonnet 4.6\n' +export const cliResult = { + success: true as const, + catalogOrigin: 'probe' as const, + capability: getCommitMessageAgentCapability('antigravity')!, + models: parseAntigravityModels(cliOutput).map((row) => ({ ...row, thinkingLevels: [] })), + defaultModelId: '__text_action_default__' +} + +export function sourceEntry( + defaultSurface: AgentPickerEntry['defaultSurface'] = 'chat' +): AgentPickerEntry { + return { + agent: 'antigravity', + label: 'Antigravity', + rows: [{ agent: 'antigravity', kind: 'chat' }], + surfaces: ['chat', 'terminal'], + defaultSurface, + terminal: {}, + structured: {}, + catalog: { + origin: 'probe', + fetchedAt: 1, + // Host answer for the recorded ACP session; protocol adaptation is tested in main. + models: [ + { + id: 'gemini-3.8-flash', + label: 'Gemini 3.8 Flash', + isDefault: false, + efforts: [ + { value: 'low', label: 'Low' }, + { value: 'medium', label: 'Medium' }, + { value: 'high', label: 'High' } + ] + }, + ...[ + { id: 'gemini-3.7-flash', label: 'Gemini 3.7 Flash' }, + { id: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' }, + { id: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash' }, + { id: 'gemini-3.1-pro', label: 'Gemini 3.1 Pro' } + ].map((model) => ({ + ...model, + isDefault: false, + efforts: [], + effortsKnown: false as const + })) + ] + }, + coherentCatalog: true, + catalogRead: 'settled', + sourceCatalogs: { + cli: { + catalog: cliModelCatalogAnswer('antigravity', cliResult)!, + coherentCatalog: true, + catalogRead: 'settled' + } + } + } +} diff --git a/src/renderer/src/components/agent/agent-launch-picker-sources.test.ts b/src/renderer/src/components/agent/agent-launch-picker-sources.test.ts new file mode 100644 index 00000000000..2dfe6915725 --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-sources.test.ts @@ -0,0 +1,101 @@ +import { expect, it } from 'vitest' +import { sourceEntry } from './agent-launch-picker-sources.test-fixture' +import { + agentPickerEntryOptions, + agentPickerModelMenu, + agentPickerModels +} from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' +import { + agentPickerDraft, + agentPickerEffectiveChoices, + agentPickerFreshLaunchInputs +} from '../../../../shared/agent-launch/picker/agent-launch-picker' +import { applyAgentPickerEdit } from '../../../../shared/agent-launch/picker/agent-launch-picker-edits' +import { searchAgentPickerSetups } from '../../../../shared/agent-launch/picker/agent-launch-picker-search' +import { projectAgentLaunchProfile } from '../../../../shared/agent-launch/choices/agent-launch-profile' +import { toAgentLaunchPreferences } from '../../../../shared/agent-launch/choices/agent-launch-preferences' + +import type { AgentDedicatedChoices } from '../../../../shared/agent-launch/choices/agent-launch-choices' + +it('selects protocol rows, efforts, defaults and search by the actual draft surface', () => { + for (const defaultSurface of ['chat', 'terminal'] as const) { + const entry = sourceEntry(defaultSurface) + expect(agentPickerModels(entry, 'terminal').map(({ id }) => id)).toEqual([ + 'gemini-3.8-flash-high', + 'gemini-3.8-flash-medium', + 'gemini-3.8-flash-low', + 'claude-sonnet-4-6' + ]) + expect(agentPickerModels(entry, 'chat')[0].id).toBe('gemini-3.8-flash') + expect( + agentPickerEntryOptions(entry, 'gemini-3.8-flash', 'chat').find(({ id }) => id === 'effort') + ?.kind + ).toMatchObject({ choices: [{ value: 'low' }, { value: 'medium' }, { value: 'high' }] }) + expect(agentPickerEntryOptions(entry, 'gemini-3.8-flash-low', 'terminal')).toEqual([]) + expect(agentPickerModels(entry, 'terminal').some(({ isDefault }) => isDefault)).toBe(false) + const setup = searchAgentPickerSetups([entry], 'Flash Low', 8, () => 'terminal')[0] + expect(setup).toMatchObject({ surface: 'terminal', choices: { model: 'gemini-3.8-flash-low' } }) + expect(setup.choices.options?.effort).toBeUndefined() + expect(searchAgentPickerSetups([entry], 'Flash Low', 8, () => 'chat')[0]).toMatchObject({ + surface: 'chat', + choices: { model: 'gemini-3.8-flash', options: { effort: 'low' } } + }) + const pending = { + ...entry, + sourceCatalogs: { + cli: { + catalog: { origin: 'unknown' as const }, + catalogRead: 'pending' as const, + coherentCatalog: true + } + } + } + expect(agentPickerModelMenu(pending, 'terminal').status).toBe('listing') + expect(agentPickerModelMenu(pending, 'chat').status).toBe('listed') + } +}) + +it.each([ + {}, + { model: 'gemini-3.8-flash', options: { effort: 'high' } }, + { options: { effort: 'high' } } +] satisfies AgentDedicatedChoices[])( + 'replaces model-dependent menu effort only on an explicit CLI model pick: %j', + (terminal) => { + const entry = { ...sourceEntry(), terminal } + const untouched = agentPickerEffectiveChoices(entry, agentPickerDraft(entry, 'terminal')) + expect(untouched.options?.effort).toBe(terminal.options?.effort) + const draft = applyAgentPickerEdit(entry, agentPickerDraft(entry, 'terminal'), { + kind: 'choice', + patch: { model: 'gemini-3.8-flash-low' } + }) + expect(draft.acceptedEdits?.choices).toMatchObject({ + model: 'gemini-3.8-flash-low', + options: { effort: null } + }) + const input = agentPickerFreshLaunchInputs( + draft, + { surface: 'terminal', executionHostId: 'runtime:paired' }, + entry + ) + expect(input.sessionOptions).toEqual({ model: 'gemini-3.8-flash-low' }) + expect(toAgentLaunchPreferences(input.sessionOptions, 'antigravity')).toEqual({ + model: 'gemini-3.8-flash-low' + }) + expect( + projectAgentLaunchProfile( + 'antigravity', + { agentLaunchChoices: { antigravity: terminal } }, + { target: 'terminal', choices: draft.choices, userArgs: '' } + ).args + ).toBe('--model gemini-3.8-flash-low') + // Alternate launch sends the same explicit choice; it does not translate protocols. + expect( + agentPickerFreshLaunchInputs( + { ...draft, surface: 'chat' }, + { surface: 'chat', executionHostId: 'local' }, + entry + ).sessionOptions + ).toEqual({ model: 'gemini-3.8-flash-low' }) + } +) diff --git a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts index ced76c6ecfa..dc3f31dd055 100644 --- a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts +++ b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts @@ -1,7 +1,6 @@ -import { - agentPickerModelMenu, - agentPickerUsesComposerModelMenu -} from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' +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 { TEXT_ACTION_DEFAULT_MODEL, textActionArgumentsOwnEffort @@ -94,11 +93,12 @@ export function agentLaunchSetupOptionRows( argumentsOwnedRow('effort', options[0]?.label ?? 'Reasoning effort', 'thought_level', t) ] } + const view = agentPickerCatalogView(entry, draft.surface) const effort = agentPickerModelMenu(entry, draft.surface, { ...(currentModel ? { model: currentModel } : {}), ...argumentsView.choices.options }).descriptors.find((row) => row.id === 'effort') - const sharedEffort = agentPickerUsesComposerModelMenu(entry, draft.surface) ? effort : undefined + const sharedEffort = !entry.textGeneration ? effort : undefined const rows: SessionOptionDescriptor[] = options .filter((option) => !sharedEffort || option.id !== 'effort') .map((option) => { @@ -123,7 +123,7 @@ export function agentLaunchSetupOptionRows( const valueKnown = current !== undefined || (option.id === 'serviceTier' && - entry.catalog.origin !== 'unknown' && + view.catalog.origin !== 'unknown' && Boolean(liveModel?.serviceTiers?.length)) return { id: option.id, @@ -265,7 +265,8 @@ export function agentLaunchSetupCatalogState( agent: entry.label }) : null - return { hasModels, catalogPending, catalogMessage } + const canSearch = hasModels && agentPickerCatalogAuthoritative(entry) + return { hasModels, catalogPending, catalogMessage, canSearch } } /** Visible model rows, plus the model the list starts on. */ diff --git a/src/renderer/src/components/agent/agent-picker-catalog-demand.ts b/src/renderer/src/components/agent/agent-picker-catalog-demand.ts new file mode 100644 index 00000000000..fb1cad516dd --- /dev/null +++ b/src/renderer/src/components/agent/agent-picker-catalog-demand.ts @@ -0,0 +1,15 @@ +import { createContext, useContext, useEffect } from 'react' +import type { AgentPickerInventorySource } from './agent-picker-inventory-source' +import type { AgentPickerSurface } from '../../../../shared/agent-launch/picker/agent-launch-picker' + +export const AgentPickerCatalogDemand = + createContext(undefined) + +export function useAgentPickerCatalogDemand( + agent: string, + surface: AgentPickerSurface, + open: boolean +) { + const observe = useContext(AgentPickerCatalogDemand) + useEffect(() => (open ? observe?.(agent, surface) : undefined), [observe, agent, surface, open]) +} diff --git a/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts b/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts index 39ac2a7614b..9852acf54b8 100644 --- a/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts +++ b/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts @@ -1,10 +1,21 @@ import { shallow } from 'zustand/shallow' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' +import type { ModelCatalogSource } from '../../../../shared/agent-session/options/model-catalog-source' +import type { + AgentPickerEntry, + AgentPickerCatalogView +} from '../../../../shared/agent-launch/picker/agent-launch-picker' +import { + agentPickerCatalogSources, + agentPickerSourceView, + withAgentPickerSourceView +} from '../../../../shared/agent-launch/picker/agent-launch-picker-source' -export type AgentPickerCatalogJob = { index: number } +export type AgentPickerCatalogJob = { index: number; source: ModelCatalogSource } export function agentPickerCatalogJobs(entries: AgentPickerEntry[]): AgentPickerCatalogJob[] { return entries.flatMap((entry, index) => - entry.surfaces.length && entry.catalogRead !== 'unsupported' ? [{ index }] : [] + agentPickerCatalogSources(entry).flatMap((source) => + agentPickerSourceView(entry, source).catalogRead === 'unsupported' ? [] : [{ index, source }] + ) ) } export function agentPickerCatalogFailure(error: unknown): 'unsupported' | 'failed' { @@ -20,11 +31,35 @@ export function agentPickerCatalogFailure(error: unknown): 'unsupported' | 'fail export function updateAgentPickerCatalog( entries: AgentPickerEntry[], job: AgentPickerCatalogJob, - patch: Partial> + patch: Partial ) { - const before = entries[job.index] + const entry = entries[job.index] + const before = agentPickerSourceView(entry, job.source) const next = { ...before, ...patch } return shallow(before, next) ? entries - : entries.map((row, index) => (index === job.index ? next : row)) + : entries.map((row, index) => + index === job.index ? withAgentPickerSourceView(row, job.source, next) : row + ) +} +export { agentPickerSourceView } + +export function withAgentPickerCatalogAvailability( + entry: AgentPickerEntry, + available: Record, + registeredAgents?: readonly { agent: string }[] | null +) { + for (const source of agentPickerCatalogSources(entry)) { + entry = withAgentPickerSourceView(entry, source, { + ...agentPickerSourceView(entry, source), + catalogRead: + available[source] && + (source !== 'structured' || + !registeredAgents || + registeredAgents.some(({ agent }) => agent === entry.agent)) + ? 'pending' + : 'unsupported' + }) + } + return entry } diff --git a/src/renderer/src/components/agent/agent-picker-inventory-source.ts b/src/renderer/src/components/agent/agent-picker-inventory-source.ts index 92f24705816..8da8334588b 100644 --- a/src/renderer/src/components/agent/agent-picker-inventory-source.ts +++ b/src/renderer/src/components/agent/agent-picker-inventory-source.ts @@ -1,3 +1,8 @@ +import { + modelCatalogSource, + type ModelCatalogSurface, + type ModelCatalogSource +} from '../../../../shared/agent-session/options/model-catalog-source' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import { useAppViewExternalStore } from '@/store/retained-views/app-state-view' import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' @@ -10,19 +15,47 @@ import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/ag export type AgentPickerInventorySource = { getSnapshot: () => AgentPickerEntry[] subscribe: (listener: () => void) => () => void + observeSurface?: (agent: string, surface: ModelCatalogSurface) => () => void } -type WritableAgentPickerInventorySource = AgentPickerInventorySource & { - publish: (entries: readonly AgentPickerEntry[]) => void -} +type WritableAgentPickerInventorySource = AgentPickerInventorySource & + Pick & { + publish: (entries: readonly AgentPickerEntry[]) => void + } export function createAgentPickerInventorySource( initial: AgentPickerEntry[] ): WritableAgentPickerInventorySource { let entries = initial const listeners = new Set<() => void>() + const demand = new Map() + const demandListeners = new Set<() => void>() return { getSnapshot: () => entries, + usesSource: (entry: AgentPickerEntry, source: ModelCatalogSource) => + source !== 'cli' || (demand.get(entry.agent) ?? 0) > 0, + subscribeDemand: (listener: () => void) => { + demandListeners.add(listener) + return () => { + demandListeners.delete(listener) + } + }, + observeSurface: (agent: string, surface: ModelCatalogSurface) => { + if (modelCatalogSource(agent, surface) !== 'cli') { + return () => {} + } + demand.set(agent, (demand.get(agent) ?? 0) + 1) + demandListeners.forEach((listener) => listener()) + return () => { + const next = (demand.get(agent) ?? 1) - 1 + if (next) { + demand.set(agent, next) + } else { + demand.delete(agent) + } + demandListeners.forEach((listener) => listener()) + } + }, subscribe: (listener) => { listeners.add(listener) return () => listeners.delete(listener) @@ -49,12 +82,15 @@ export function useAgentPickerInventoryEntries( export type AgentPickerAcquisitionObserver = { publish: (entries: AgentPickerEntry[]) => void selected: () => TuiAgent | undefined + usesSource?: (entry: AgentPickerEntry, source: ModelCatalogSource) => boolean + subscribeDemand?: (listener: () => void) => () => void } export type AgentPickerAcquisitionReads = { settings?: () => Promise catalog: ( entry: AgentPickerEntry, waitForListing: boolean, + source: ModelCatalogSource | undefined, signal: AbortSignal ) => Promise observeCatalog?: ( @@ -63,7 +99,8 @@ export type AgentPickerAcquisitionReads = { answer?: AgentPickerEntry['catalog'] pending: boolean invalidated?: boolean - }) => void + }) => void, + source?: ModelCatalogSource ) => () => void support: (entry: AgentPickerEntry) => Promise } diff --git a/src/renderer/src/components/agent/agent-picker-source-demand.ts b/src/renderer/src/components/agent/agent-picker-source-demand.ts new file mode 100644 index 00000000000..ebaa7e437de --- /dev/null +++ b/src/renderer/src/components/agent/agent-picker-source-demand.ts @@ -0,0 +1,38 @@ +import { + modelCatalogSource, + type ModelCatalogSource +} from '../../../../shared/agent-session/options/model-catalog-source' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' +import type { AgentPickerAcquisitionObserver } from './agent-picker-inventory-source' + +export function agentPickerCatalogDemanded( + entry: AgentPickerEntry, + source: ModelCatalogSource, + observers: Iterable +) { + return [...observers].some( + (observer) => + observer.usesSource?.(entry, source) ?? + (source !== 'cli' || modelCatalogSource(entry.agent, entry.defaultSurface) === source) + ) +} + +export class AgentPickerSourceDemand { + private controllers = new Map() + signal(index: number) { + let controller = this.controllers.get(index) + if (!controller) { + controller = new AbortController() + this.controllers.set(index, controller) + } + return controller.signal + } + reconcile(uses: (index: number) => boolean) { + for (const [index, controller] of this.controllers) { + if (!uses(index)) { + this.controllers.delete(index) + controller.abort() + } + } + } +} diff --git a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx index 605071951e7..6b70c4a0da6 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx @@ -1,3 +1,7 @@ +import { + modelCatalogChoiceEdit, + type ModelCatalogSource +} from '../../../../../shared/agent-session/options/model-catalog-source' import type { modelMenuOptions } from '../../../../../shared/agent-session/options/model-menu-options' import type { AgentChoicePatch, @@ -25,6 +29,7 @@ export type AgentChoiceControlsProps = { value: AgentDedicatedChoices | undefined modelMenu?: ReturnType & { fallbackAfterFailure?: boolean + source?: ModelCatalogSource } disabled?: boolean onOpenChange?: (open: boolean) => void @@ -134,7 +139,17 @@ export function AgentChoiceFields({ })), ...(unlistedModel ? [{ value: unlistedModel, label: unlistedModel }] : []) ]} - onChange={(model) => onSelect({ model: model === AGENT_DEFAULT_VALUE ? null : model })} + onChange={(model) => { + const patch = { model: model === AGENT_DEFAULT_VALUE ? null : model } + onSelect( + modelCatalogChoiceEdit( + modelMenu?.source ?? 'structured', + modelMenu?.rows ?? [], + selected?.model, + patch + ) + ) + }} /> ) : null} {modelMenu?.fallbackAfterFailure ? ( diff --git a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.sources.test.tsx b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.sources.test.tsx new file mode 100644 index 00000000000..ec4549c6b6d --- /dev/null +++ b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.sources.test.tsx @@ -0,0 +1,94 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { AgentLaunchChoiceEditor } from './AgentLaunchChoiceEditor' +import { cliModelMenuScope } from '@/runtime/native-chat/model-catalogs/model-menu-cli-catalog' +import { resetHostModelCatalogSnapshotsForTests } from '@/runtime/native-chat/model-catalogs/host-model-catalog-snapshots' +import { cliResult } from '../agent-launch-picker-sources.test-fixture' +const mocks = vi.hoisted(() => ({ discover: vi.fn() })) +vi.mock('@/runtime/native-chat/model-catalogs/terminal-model-discovery-client', () => ({ + discoverRuntimeTerminalModels: mocks.discover +})) +vi.mock('./AgentChoiceMenu', () => ({ + AgentChoiceMenu: (props: { + label: string + value: string + choices: { value: string; label: string }[] + onChange: (value: string) => void + onOpenChange?: (open: boolean) => void + }) => ( + + ) +})) +afterEach(() => { + cleanup() + resetHostModelCatalogSnapshotsForTests() + mocks.discover.mockReset() +}) +it('saves a model-only terminal edit with an explicit effort clear through the Settings writer', async () => { + mocks.discover.mockResolvedValue(cliResult) + const save = vi.fn().mockResolvedValue(undefined) + const source = { + source: 'cli' as const, + coherentCatalog: true, + scope: cliModelMenuScope( + { target: { kind: 'local' }, worktreeId: undefined, worktreePath: '' }, + 'antigravity', + 'agy' + ) + } + const choices = { options: { effort: 'high' } } + const editor = render( + + ) + expect(mocks.discover).not.toHaveBeenCalled() + fireEvent.focus(screen.getByRole('combobox', { name: 'Model' })) + await screen.findByRole('option', { name: 'Gemini 3.8 Flash (Low)' }) + fireEvent.change(screen.getByRole('combobox', { name: 'Model' }), { + target: { value: 'gemini-3.8-flash-low' } + }) + await waitFor(() => + expect(save).toHaveBeenCalledWith( + { model: 'gemini-3.8-flash-low', options: { effort: null } }, + '' + ) + ) + expect(choices).toEqual({ options: { effort: 'high' } }) + editor.rerender( + + ) + await waitFor(() => expect(screen.queryByRole('combobox', { name: 'Thinking' })).toBeNull()) + fireEvent.change(screen.getByRole('combobox', { name: 'Model' }), { + target: { value: '__agent_default__' } + }) + await waitFor(() => expect(save).toHaveBeenLastCalledWith({ model: null }, '')) +}) diff --git a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx index 4476d877025..2d25ed24105 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.tsx @@ -104,7 +104,7 @@ export function AgentLaunchChoiceEditor({
() => {} @@ -37,11 +39,11 @@ export function useAgentModelMenu( useEffect(() => { if (catalog && open && active) { const controller = new AbortController() - void catalog.read(undefined, controller.signal) + void catalog.read(source?.source === 'cli', undefined, controller.signal) return () => controller.abort() } return undefined - }, [catalog, open, active, snapshot.generation]) + }, [catalog, open, active, snapshot.generation, source?.source]) const menu = modelMenuOptions(snapshot.answer, { agent, surface: 'terminal', @@ -56,6 +58,7 @@ export function useAgentModelMenu( }) return { ...menu, + source: source?.source ?? 'structured', fallbackAfterFailure: !!source && snapshot.attempted === true && !snapshot.pending && menu.status === 'builtin' } diff --git a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts index 349f06f048a..800d064a1b0 100644 --- a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts +++ b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts @@ -1,4 +1,4 @@ -import { getAgentSessionOptionLaunchCatalog } from '../../../../shared/agent-session/options/agent-session-option-catalog' +import { withAgentPickerCatalogAvailability } from './agent-picker-catalog-jobs' import { recomputeOn } from '@/lib/recompute-on' import { useHostStructuredAgentsVersion } from '@/runtime/native-chat/agent-catalogs/chat-provider-agents' import { @@ -27,7 +27,9 @@ import { } from './agent-launch-picker-host-reads' import { agentPickerUsesNativeRuntime, - agentPickerHostPlatform + agentPickerCatalogAvailability, + agentPickerHostPlatform, + agentPickerCliReadOptions } from './agent-launch-picker-runtime' import { AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' @@ -196,20 +198,13 @@ export function useAgentLaunchPickerInventorySource( (agent) => agentPickerChoiceSeeds(agent, defaults), formatAgentTypeLabel, model.defaultTuiAgent - ).map((entry) => ({ - ...entry, - coherentCatalog, - ...(!target || - !entry.surfaces.length || - (entry.agent === 'antigravity' - ? registeredAgents && - !registeredAgents.some(({ agent }) => agent === entry.agent) && - !getAgentSessionOptionLaunchCatalog(entry.agent) - : !nativeRuntime || - (registeredAgents && !registeredAgents.some(({ agent }) => agent === entry.agent))) - ? { catalogRead: 'unsupported' as const } - : {}) - })) + ).map((entry) => + withAgentPickerCatalogAvailability( + { ...entry, coherentCatalog }, + agentPickerCatalogAvailability(target, route, workspaceId, nativeRuntime), + registeredAgents + ) + ) : [] const fallback = useMemo( () => @@ -277,6 +272,13 @@ export function useAgentLaunchPickerInventorySource( target, selector, nativeRuntime, + ...agentPickerCliReadOptions( + target, + workspaceId, + context?.launchCwd ?? (selectedWorkspace ? selectedWorkspace.path : repo?.path) ?? '', + route, + [context?.runtimeId, context?.pairingRevision] + ), platform, settings, serverSettings: @@ -286,6 +288,8 @@ export function useAgentLaunchPickerInventorySource( }, { selected: () => selectedRef.current, + usesSource: source.usesSource, + subscribeDemand: source.subscribeDemand, publish: source.publish } ) diff --git a/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx b/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx index 7d41df74e03..5549058efb2 100644 --- a/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx @@ -2,7 +2,10 @@ import { useCallback, useMemo, useState, type ComponentProps } from 'react' import { useAppStore } from '@/store/index' import { AgentLaunchPicker } from '@/components/agent/AgentLaunchPicker' import { useAgentPickerDraftScope } from '@/components/agent/agent-launch-picker-drafts' -import { useAgentLaunchPickerInventory } from '@/components/agent/use-agent-launch-picker-inventory' +import { + useAgentLaunchPickerInventorySource, + useAgentPickerInventoryEntries +} from '@/components/agent/use-agent-launch-picker-inventory' import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' import { buildAgentLaunchRouteInput, @@ -130,12 +133,13 @@ export function AutomationAgentLaunchPicker({ ] ) - const observed = useAgentLaunchPickerInventory( + const inventory = useAgentLaunchPickerInventorySource( workspace.worktreeId, model, modern && menuOpen, catalogAgent ?? draft.agentId ) + const observed = useAgentPickerInventoryEntries(inventory) const { entries, draftForEntry } = useAutomationAgentPickerEntries( observed, state, @@ -157,6 +161,7 @@ export function AutomationAgentLaunchPicker({ agent === props.agent) : true const capabilities = detectionTarget.kind === 'runtime' ? lastVerifiedRuntimeStatus(status)?.capabilities : readLocalRuntimeCapabilitiesOrUnknown() const eligible = modelMenuUsesHostCatalog({ - nativeRuntime: detectionTarget.kind !== 'ssh', - registered, + nativeRuntime: + detectionTarget.kind !== 'ssh' && !(source === 'cli' && detectionTarget.kind === 'runtime'), + registered: source === 'cli' || registered, commandOverride, serverCommandOverride: commandOverride, paired: detectionTarget.kind === 'runtime', @@ -63,10 +67,19 @@ export function HostAgentLaunchChoiceEditor({ SSH.", "failed": "Couldn’t stop {{host}}. Turn off its browser control in Settings > SSH." }, + "agents": { + "terminalModels": { + "connectionUnavailable": "Terminal model discovery is unavailable on this connection.", + "workspaceRequired": "Terminal model discovery requires a workspace on this host.", + "hostRequired": "Terminal model discovery requires a connected host." + } + }, "speechModelUpdate": { "update": "Update", "cancel": "Cancel", diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots.ts index 9e7b773e6fd..02159ad9aaa 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-catalog-snapshots.ts @@ -10,7 +10,11 @@ import { callStructuredAgentSession } from '../requests/structured-agent-session import { structuredAgentSessionHostKey } from '../host-capabilities/structured-agent-session-host-capability' // Per host and agent; absence or an account-setting change drops them. -const snapshots = new Map() +type SnapshotEntry = { + catalog?: HostModelCatalogSnapshot + completedAttempts: Map +} +const snapshots = new Map() // Bumped when a host's answers are dropped, so a preload sent before then records nothing. const generations = new Map() const catalogGenerations = new Map() @@ -26,9 +30,10 @@ const listeners = new Map>() export function subscribeHostModelCatalogSnapshot( target: RuntimeClientTarget, agent: string, - listener: CatalogListener + listener: CatalogListener, + sourceKey = 'structured' ): () => void { - const key = snapshotKey(structuredAgentSessionHostKey(target), agent) + const key = snapshotKey(structuredAgentSessionHostKey(target), agent, sourceKey) const scoped = listeners.get(key) ?? new Set() listeners.set(key, scoped) scoped.add(listener) @@ -40,8 +45,12 @@ export function subscribeHostModelCatalogSnapshot( } } -export function hostModelCatalogGeneration(target: RuntimeClientTarget, agent: string): number { - // Invalidation is per host/agent. +export function hostModelCatalogGeneration( + target: RuntimeClientTarget, + agent: string, + _sourceKey = 'structured' +): number { + // Invalidation is per host/agent, independent of retired invocation identities. const key = `${structuredAgentSessionHostKey(target)}\u0000${agent}` if (!catalogGenerations.has(key)) { catalogGenerations.set(key, 0) @@ -49,18 +58,19 @@ export function hostModelCatalogGeneration(target: RuntimeClientTarget, agent: s return catalogGenerations.get(key)! } -function snapshotKey(hostKey: string, agent: string): string { - return `${hostKey}\u0000${agent}` +function snapshotKey(hostKey: string, agent: string, sourceKey = 'structured'): string { + return `${hostKey}\u0000${agent}\u0000${sourceKey}` } /** Undefined until host answers for this frame. */ export function readHostModelCatalogSnapshot( target: RuntimeClientTarget, agent: string, - launch: HostModelCatalogLaunch + launch: HostModelCatalogLaunch, + sourceKey = 'structured' ): AgentSessionModelCatalogResult | undefined { return selectHostModelCatalogSnapshot( - snapshots.get(snapshotKey(structuredAgentSessionHostKey(target), agent)), + snapshots.get(snapshotKey(structuredAgentSessionHostKey(target), agent, sourceKey))?.catalog, launch ) } @@ -70,12 +80,19 @@ export function recordHostModelCatalogSnapshot( target: RuntimeClientTarget, agent: string, worktree: string | null, - catalog: AgentSessionModelCatalogResult + catalog: AgentSessionModelCatalogResult, + sourceKey = 'structured' ): void { - const key = snapshotKey(structuredAgentSessionHostKey(target), agent) - const previous = snapshots.get(key) + const key = snapshotKey(structuredAgentSessionHostKey(target), agent, sourceKey) + const entry = snapshots.get(key) + const previous = entry?.catalog const next = withHostModelCatalogAnswer(previous, worktree, catalog) - if (worktree !== null && next !== previous && next?.byWorktree.has(worktree)) { + if ( + sourceKey === 'structured' && + worktree !== null && + next !== previous && + next?.byWorktree.has(worktree) + ) { chatAnswers.set(key, (chatAnswers.get(key) ?? 0) + 1) } const same = (a: unknown, b: unknown) => a === b || JSON.stringify(a) === JSON.stringify(b) @@ -89,13 +106,33 @@ export function recordHostModelCatalogSnapshot( return } if (next) { - snapshots.set(key, next) + snapshots.set(key, { catalog: next, completedAttempts: entry?.completedAttempts ?? new Map() }) } else { snapshots.delete(key) } listeners.get(key)?.forEach((listener) => listener({ forgotten: false, worktree, catalog })) } +/** Acquisition metadata shares the answer lifetime; it is never catalog equality or persisted data. */ +export function hostModelCatalogCompletedAttempt( + target: RuntimeClientTarget, + agent: string, + worktree: string | null, + sourceKey: string, + completedAt?: number +): number | undefined { + const key = snapshotKey(structuredAgentSessionHostKey(target), agent, sourceKey) + let entry = snapshots.get(key) + if (completedAt !== undefined) { + if (!entry) { + entry = { completedAttempts: new Map() } + snapshots.set(key, entry) + } + entry.completedAttempts.set(worktree, completedAt) + } + return entry?.completedAttempts.get(worktree) +} + /** Drop all or selected agents’ host answers when the account a new chat pins may change. */ export function forgetHostModelCatalogSnapshots( target: RuntimeClientTarget, @@ -133,7 +170,7 @@ export function forgetHostModelCatalogSnapshots( export function hostModelCatalogSnapshotAgents(target: RuntimeClientTarget): string[] { const prefix = `${structuredAgentSessionHostKey(target)}\u0000` return [...snapshots.keys()] - .filter((key) => key.startsWith(prefix)) + .filter((key) => key.startsWith(prefix) && key.split('\u0000')[2] === 'structured') .map((key) => key.split('\u0000')[1]!) } @@ -173,3 +210,11 @@ export function resetHostModelCatalogSnapshotsForTests(): void { catalogGenerations.clear() chatAnswers.clear() } + +export function hostModelCatalogSnapshotDiagnostics() { + return { + epochs: catalogGenerations.size, + chatAnswers: chatAnswers.size, + snapshots: snapshots.size + } +} diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-lifecycle.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-lifecycle.test.ts index c1416799aa8..3b00db7451c 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-lifecycle.test.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-lifecycle.test.ts @@ -79,7 +79,7 @@ it('preserves scoped retirement across owner handoff and rejected reopen without expect(successor).not.toBe(a) expect(successor.snapshot.answer).toEqual(retired) mocks.call.mockRejectedValueOnce(new Error('reopen offline')) - await successor.read(undefined, new AbortController().signal) + await successor.read(false, undefined, new AbortController().signal) expect(successor.snapshot.answer).toEqual(retired) recordHostModelCatalogSnapshot(target, 'codex', 'id:b', catalog('other-new')) expect(successor.snapshot.answer).toEqual(retired) @@ -114,7 +114,7 @@ it.each([ const owner = hostModelMenuCatalog(scope) const stop = owner.subscribe(() => {}) mocks.call.mockResolvedValueOnce(answer) - expect(await owner.read(undefined, new AbortController().signal)).toEqual(answer) + expect(await owner.read(false, undefined, new AbortController().signal)).toEqual(answer) expect(owner.snapshot.answer).toEqual(answer) const read = () => readHostModelCatalogSnapshot(target, 'codex', { @@ -132,7 +132,7 @@ it.each([ const detach = successor.subscribe(() => {}) expect(successor).not.toBe(owner) mocks.call.mockRejectedValueOnce(new Error('reopen offline')) - expect(await successor.read(undefined, new AbortController().signal)).toEqual(answer) + expect(await successor.read(false, undefined, new AbortController().signal)).toEqual(answer) recordHostModelCatalogSnapshot(target, 'codex', 'id:sibling', catalog('sibling')) expect(successor.snapshot.answer).toEqual(answer) expect( @@ -145,10 +145,10 @@ it.each([ mocks.call .mockResolvedValueOnce({ origin: 'unknown', listingInProgress: true }) .mockRejectedValueOnce(new Error('refresh offline')) - expect(await successor.read(undefined, new AbortController().signal)).toEqual(answer) + expect(await successor.read(false, undefined, new AbortController().signal)).toEqual(answer) expect(read()).toEqual(answer) mocks.call.mockResolvedValueOnce(catalog('replacement')) - await successor.read(undefined, new AbortController().signal) + await successor.read(false, undefined, new AbortController().signal) expect(successor.snapshot.answer).toMatchObject({ models: [{ id: 'replacement' }] }) forgetHostModelCatalogSnapshots(target) expect(successor.snapshot.answer).toBeUndefined() diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-phases.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-phases.test.ts index 3a958fcb760..9e9c5146f81 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-phases.test.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog-phases.test.ts @@ -1,7 +1,3 @@ -const transport = vi.hoisted(() => ({ call: vi.fn() })) -vi.mock('../requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: transport.call -})) import { beforeEach, expect, it, vi } from 'vitest' import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire' import { hostModelMenuCatalog } from './host-model-menu-catalog' @@ -28,10 +24,7 @@ function transportReply() { } } } -beforeEach(() => { - resetHostModelCatalogSnapshotsForTests() - transport.call.mockReset() -}) +beforeEach(() => resetHostModelCatalogSnapshotsForTests()) it('withdraws abandoned queued upgrades and shares the surviving upgrade across reopen without listeners', async () => { const first = transportReply(), @@ -47,10 +40,7 @@ it('withdraws abandoned queued upgrades and shares the surviving upgrade across ? Promise.resolve(models('unwanted-orphan')) : first.request() ) - transport.call.mockImplementation((_target, _method, params) => - request(params.waitForListing === true) - ) - const scope = { target, agent: 'codex', worktree: 'id:queued-lifetime' } + const scope = { target, agent: 'codex', worktree: 'id:queued-lifetime', request } const owner = hostModelMenuCatalog(scope) const a = new AbortController(), b = new AbortController() @@ -61,10 +51,10 @@ it('withdraws abandoned queued upgrades and shares the surviving upgrade across const display = vi.fn() stops.push(owner.subscribe(display)) try { - const plain = owner.read(false, a.signal) + const plain = owner.read(false, false, a.signal) reads.push(plain) await first.started - const queued = owner.read(true, b.signal) + const queued = owner.read(false, true, b.signal) reads.push(queued) expect(request.mock.calls).toEqual([[false]]) // The mounted display subscription owns no permission to continue either ended request. @@ -79,13 +69,13 @@ it('withdraws abandoned queued upgrades and shares the surviving upgrade across reopening = true const successor = hostModelMenuCatalog(scope) stops.push(successor.subscribe(display)) - const plainA = successor.read(false, nextA.signal) - const plainB = successor.read(false, nextB.signal) + const plainA = successor.read(false, false, nextA.signal) + const plainB = successor.read(false, false, nextB.signal) reads.push(plainA, plainB) await reopened.started expect(request.mock.calls).toEqual([[false], [false]]) - const waitA = successor.read(true, nextA.signal) - const waitB = successor.read(true, nextB.signal) + const waitA = successor.read(false, true, nextA.signal) + const waitB = successor.read(false, true, nextB.signal) reads.push(waitA, waitB) nextA.abort() stops[1]() @@ -95,7 +85,7 @@ it('withdraws abandoned queued upgrades and shares the surviving upgrade across expect(request.mock.calls).toEqual([[false], [false], [true]]) // The remaining request signal alone retains the registered owner and physical wait. expect(hostModelMenuCatalog(scope)).toBe(successor) - expect(await successor.read(false, nextB.signal)).toEqual(listing) + expect(await successor.read(false, false, nextB.signal)).toEqual(listing) expect(request.mock.calls).toEqual([[false], [false], [true]]) stops.push(successor.subscribe(display)) wait.resolve(models('fresh-after-reopen')) @@ -139,10 +129,7 @@ it('shares actual waits, stops after failure, follows open Settings to completio for (const port of ports) { request.mockImplementationOnce(port.request) } - transport.call.mockImplementation((_target, _method, params) => - request(params.waitForListing === true) - ) - const scope = { target, agent: 'codex', worktree: 'id:phase-outcomes' } + const scope = { target, agent: 'codex', worktree: 'id:phase-outcomes', request } const owner = hostModelMenuCatalog(scope) const settings = new AbortController(), picker = new AbortController() @@ -154,21 +141,21 @@ it('shares actual waits, stops after failure, follows open Settings to completio const reads: Promise[] = [] const stop = owner.subscribe(() => {}) try { - const automatic = owner.read(undefined, settings.signal) - const pickerPlain = owner.read(false, picker.signal) - const pickerWait = owner.read(true, picker.signal) + const automatic = owner.read(false, undefined, settings.signal) + const pickerPlain = owner.read(false, false, picker.signal) + const pickerWait = owner.read(false, true, picker.signal) reads.push(automatic, pickerPlain, pickerWait) await plain.started plain.resolve(listing) expect(await pickerPlain).toEqual(listing) await firstWait.started - const provisional = owner.read(false, picker.signal) + const provisional = owner.read(false, false, picker.signal) reads.push(provisional) firstWait.resolve({ ...models('gpt-6.1-sol'), listingInProgress: true, waitExpired: true }) expect(await provisional).toEqual(listing) expect(await pickerWait).toMatchObject({ models: [{ id: 'gpt-6.1-sol' }], waitExpired: true }) await failure.started - const failedPicker = owner.read(true, picker.signal) + const failedPicker = owner.read(false, true, picker.signal) reads.push(failedPicker) failure.reject(new Error('host offline')) for (const answer of await Promise.all([automatic, failedPicker])) { @@ -180,8 +167,8 @@ it('shares actual waits, stops after failure, follows open Settings to completio settings.abort() picker.abort() - const follow = owner.read(undefined, reopened.signal) - const sharedWait = owner.read(true, explicit.signal) + const follow = owner.read(false, undefined, reopened.signal) + const sharedWait = owner.read(false, true, explicit.signal) reads.push(follow, sharedWait) await reopenPlain.started reopenPlain.resolve(listing) @@ -196,7 +183,7 @@ it('shares actual waits, stops after failure, follows open Settings to completio reopened.abort() explicit.abort() - const ended = owner.read(undefined, closing.signal) + const ended = owner.read(false, undefined, closing.signal) reads.push(ended) await closingPlain.started closingPlain.resolve(listing) @@ -204,7 +191,7 @@ it('shares actual waits, stops after failure, follows open Settings to completio closing.abort() stop() expect(hostModelMenuCatalog(scope)).toBe(owner) - const stillShared = hostModelMenuCatalog(scope).read(true, survivor.signal) + const stillShared = hostModelMenuCatalog(scope).read(false, true, survivor.signal) reads.push(stillShared) closingWait.resolve(expired) await Promise.all([ended, stillShared]) diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.test.ts index 985e48e383f..f80a3056afe 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.test.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.test.ts @@ -37,8 +37,8 @@ it('never restores a catalog retired or invalidated during a failed refresh', as const worktree = `id:${invalidate}` const owner = hostModelMenuCatalog({ target, agent: 'codex', worktree }) const stop = owner.subscribe(() => {}) - await owner.read(undefined, new AbortController().signal) - const refresh = owner.read(undefined, new AbortController().signal) + await owner.read(false, undefined, new AbortController().signal) + const refresh = owner.read(false, undefined, new AbortController().signal) await vi.waitFor(() => expect(mocks.call.mock.calls.at(-1)?.[2].waitForListing).toBe(true)) if (invalidate !== 'account') { recordHostModelCatalogSnapshot( @@ -65,7 +65,7 @@ it('never restores a catalog retired or invalidated during a failed refresh', as mocks.call .mockResolvedValueOnce({ origin: 'unknown', listingInProgress: true }) .mockRejectedValueOnce(new Error('still offline')) - await owner.read(undefined, new AbortController().signal) + await owner.read(false, undefined, new AbortController().signal) recordHostModelCatalogSnapshot(target, 'codex', 'id:unrelated', catalog('other')) expect(owner.snapshot.answer).toEqual({ origin: 'unknown' }) } @@ -108,6 +108,7 @@ it('keeps native-only answers out of guest and differing paired-command routes', const answer = await agentPickerModelCatalogReads(input).catalog( entry, false, + undefined, new AbortController().signal ) const menu = modelMenuOptions(answer, { diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.ts index 437a18a6ebb..b82fdd5dd07 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-catalog.ts @@ -5,6 +5,7 @@ import { structuredAgentSessionHostKey } from '../host-capabilities/structured-a import { callStructuredAgentSession } from '../requests/structured-agent-session-call' import { hostModelCatalogGeneration, + hostModelCatalogCompletedAttempt, readHostModelCatalogSnapshot, recordHostModelCatalogSnapshot, subscribeHostModelCatalogSnapshot @@ -14,6 +15,8 @@ export type HostModelMenuScope = { target: RuntimeClientTarget agent: string worktree?: string + sourceKey?: string + request?: Reader } export type HostModelMenuSnapshot = { answer?: AgentSessionModelCatalogResult @@ -21,6 +24,7 @@ export type HostModelMenuSnapshot = { attempted?: boolean generation: number } +type Reader = (waitForListing: boolean) => Promise const owners = new Map() function withoutWaitExpiry(answer: AgentSessionModelCatalogResult) { if (!answer.waitExpired) { @@ -47,9 +51,17 @@ function withListingStatus( } function keyOf(scope: HostModelMenuScope) { - return JSON.stringify([structuredAgentSessionHostKey(scope.target), scope.agent, scope.worktree]) + return JSON.stringify([ + structuredAgentSessionHostKey(scope.target), + scope.agent, + scope.worktree, + scope.sourceKey ?? 'structured' + ]) } +export class ModelMenuContextUnresolvedError extends Error {} +const CLI_REUSE_INTERVAL_MS = 10 * 60 * 1000 + class HostModelMenuCatalog { listeners = new Set<() => void>() snapshot: HostModelMenuSnapshot @@ -59,6 +71,7 @@ class HostModelMenuCatalog { ...withoutWaitExpiry(this.snapshot.answer ?? { origin: 'unknown' }), listingInProgress: true }), + () => this.reuseHeld(), () => this.syncPhases() ) private unsubscribe?: () => void @@ -66,20 +79,29 @@ class HostModelMenuCatalog { this.snapshot = { answer: this.held(), pending: false, - generation: hostModelCatalogGeneration(scope.target, scope.agent) + generation: hostModelCatalogGeneration(scope.target, scope.agent, scope.sourceKey) } } private held() { - return readHostModelCatalogSnapshot(this.scope.target, this.scope.agent, { - newLaunch: true, - seedsModel: true, - worktree: this.scope.worktree ?? null - }) + return readHostModelCatalogSnapshot( + this.scope.target, + this.scope.agent, + { + newLaunch: true, + seedsModel: true, + worktree: this.scope.worktree ?? null + }, + this.scope.sourceKey + ) } publish(value: Omit) { const next = { ...value, - generation: hostModelCatalogGeneration(this.scope.target, this.scope.agent) + generation: hostModelCatalogGeneration( + this.scope.target, + this.scope.agent, + this.scope.sourceKey + ) } if ( this.snapshot.generation === next.generation && @@ -112,39 +134,81 @@ class HostModelMenuCatalog { } else { this.publish({ ...this.snapshot, answer: this.held() }) } - } + }, + this.scope.sourceKey ) } private syncPhases() { - const generation = hostModelCatalogGeneration(this.scope.target, this.scope.agent) + const generation = hostModelCatalogGeneration( + this.scope.target, + this.scope.agent, + this.scope.sourceKey + ) this.publish({ ...(this.snapshot.generation === generation ? this.snapshot : {}), pending: this.phases.pending }) this.retire() } - read(waitForListing: boolean | undefined, signal: AbortSignal) { + read(reuseHeld: boolean, waitForListing: boolean | undefined, signal: AbortSignal) { if (signal.aborted) { return Promise.resolve(undefined) } this.watch() - return this.phases.read(waitForListing, signal) + return this.phases.read(reuseHeld, waitForListing, signal) + } + private reuseHeld() { + const completedAt = this.scope.sourceKey + ? hostModelCatalogCompletedAttempt( + this.scope.target, + this.scope.agent, + this.scope.worktree ?? null, + this.scope.sourceKey + ) + : undefined + if (completedAt !== undefined && Date.now() - completedAt < CLI_REUSE_INTERVAL_MS) { + this.publish({ ...this.snapshot, pending: false, attempted: true }) + return { answer: retained(this.held() ?? this.snapshot.answer) } + } + return undefined } private async requestPhase(waitForListing: boolean, current: () => boolean) { const { target, agent, worktree } = this.scope + const request: Reader = + this.scope.request ?? + ((waitForListing) => + callStructuredAgentSession(target, 'agentSession.modelCatalog', { + agent, + ...(worktree ? { worktree } : {}), + ...(waitForListing ? { waitForListing: true } : {}) + })) + let contextUnresolved = false let answer: AgentSessionModelCatalogResult | undefined try { - answer = await callStructuredAgentSession(target, 'agentSession.modelCatalog', { - agent, - ...(worktree ? { worktree } : {}), - ...(waitForListing ? { waitForListing: true } : {}) - }) - } catch {} + answer = await request(waitForListing) + } catch (error) { + contextUnresolved = error instanceof ModelMenuContextUnresolvedError + } if (!current()) { return {} } + if (this.scope.sourceKey && !contextUnresolved && !answer?.listingInProgress) { + hostModelCatalogCompletedAttempt( + target, + agent, + worktree ?? null, + this.scope.sourceKey, + Date.now() + ) + } if (answer) { - recordHostModelCatalogSnapshot(target, agent, worktree ?? null, withoutWaitExpiry(answer)) + recordHostModelCatalogSnapshot( + target, + agent, + worktree ?? null, + withoutWaitExpiry(answer), + this.scope.sourceKey + ) } const shown = answer?.listingInProgress ? withListingStatus(this.held() ?? answer, { diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-freshness.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-freshness.test.ts new file mode 100644 index 00000000000..2b742f20bde --- /dev/null +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-freshness.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import { hostModelMenuCatalog, ModelMenuContextUnresolvedError } from './host-model-menu-catalog' +import { resetHostModelCatalogSnapshotsForTests } from './host-model-catalog-snapshots' +import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire' + +const target = { kind: 'local' } as const +const answer = (id: string): AgentSessionModelCatalogResult => ({ + origin: 'probe', + fetchedAt: 0, + modelsDifferByWorkspace: true, + listingNamesConfiguredModel: false, + models: [{ id, label: id, isDefault: false, efforts: [] }] +}) +beforeEach(() => { + resetHostModelCatalogSnapshotsForTests() +}) + +it('does not suppress a prompt retry after an unresolved WSL context', async () => { + const request = vi + .fn() + .mockRejectedValueOnce(new ModelMenuContextUnresolvedError()) + .mockResolvedValueOnce(answer('ubuntu-model')) + const scope = { target, agent: 'antigravity', sourceKey: 'cli-unresolved', request } + const owner = hostModelMenuCatalog(scope) + const stop = owner.subscribe(() => {}) + await owner.read(true, undefined, new AbortController().signal) + expect(await owner.read(true, undefined, new AbortController().signal)).toEqual( + answer('ubuntu-model') + ) + expect(request).toHaveBeenCalledTimes(2) + stop() +}) diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-phases.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-phases.ts index dd96d3cbb3e..b14b7842d8b 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-phases.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-phases.ts @@ -29,6 +29,7 @@ export class HostModelMenuPhases { constructor( private readonly perform: (waited: boolean, current: () => boolean) => Promise, private readonly provisional: () => AgentSessionModelCatalogResult, + private readonly reuse: () => PhaseResult | undefined, private readonly changed: () => void ) {} get pending() { @@ -50,7 +51,7 @@ export class HostModelMenuPhases { claim.end() } } - async read(waitForListing: boolean | undefined, signal: AbortSignal) { + async read(reuseHeld: boolean, waitForListing: boolean | undefined, signal: AbortSignal) { if (signal.aborted) { return undefined } @@ -69,7 +70,7 @@ export class HostModelMenuPhases { this.claims.add(claim) signal.addEventListener('abort', claim.end, { once: true }) try { - const initial = this.phase(claim, waitForListing ?? false) + const initial = this.phase(claim, waitForListing ?? false, reuseHeld) let result = await (waitForListing === undefined && 'waiting' in initial && initial.waiting ? this.join(initial.waiting, claim) : initial) @@ -79,7 +80,7 @@ export class HostModelMenuPhases { result.reply?.listingInProgress && (!result.waited || result.reply.waitExpired) ) { - result = await this.phase(claim, true) + result = await this.phase(claim, true, false) } return this.live(claim) ? result.answer : undefined } finally { @@ -89,7 +90,11 @@ export class HostModelMenuPhases { private live(claim: Claim) { return !claim.signal.aborted && claim.generation === this.generation && this.claims.has(claim) } - private phase(claim: Claim, waited: boolean): PhaseResult | Promise { + private phase( + claim: Claim, + waited: boolean, + reuseHeld: boolean + ): PhaseResult | Promise { if (!this.live(claim)) { return {} } @@ -103,6 +108,10 @@ export class HostModelMenuPhases { } return this.join(this.active, claim) } + const held = reuseHeld && !waited ? this.reuse() : undefined + if (held) { + return held + } const phase = this.create(waited) const result = this.join(phase, claim) this.start(phase) diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-sources.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-sources.test.ts new file mode 100644 index 00000000000..1408d88851e --- /dev/null +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-menu-sources.test.ts @@ -0,0 +1,125 @@ +import { beforeEach, expect, it, vi } from 'vitest' +const calls = vi.hoisted(() => ({ structured: vi.fn() })) +vi.mock('../requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: calls.structured +})) +vi.mock('../host-capabilities/structured-agent-session-host-capability', () => ({ + structuredAgentSessionHostKey: () => 'local' +})) +import { hostModelMenuCatalog } from './host-model-menu-catalog' +import { + forgetHostModelCatalogSnapshots, + hostModelCatalogSnapshotAgents, + readHostModelCatalogSnapshot, + recordHostModelCatalogSnapshot, + resetHostModelCatalogSnapshotsForTests +} from './host-model-catalog-snapshots' +import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire' + +const target = { kind: 'local' } as const +const positive = (id: string): AgentSessionModelCatalogResult => ({ + origin: 'probe', + fetchedAt: 1, + modelsDifferByWorkspace: true, + models: [{ id, label: id, isDefault: true, efforts: [] }] +}) +beforeEach(() => { + resetHostModelCatalogSnapshotsForTests() + calls.structured.mockReset() +}) + +it.each(['structured-first', 'cli-first'])( + 'retains source-scoped negative evidence through handoff and failed refresh: %s', + async (order) => { + const acp = Promise.withResolvers() + const cli = Promise.withResolvers() + calls.structured.mockReturnValueOnce(acp.promise) + const request = vi + .fn<() => Promise>() + .mockReturnValueOnce(cli.promise) + const base = { target, agent: 'antigravity' } + const chat = hostModelMenuCatalog(base), + terminal = hostModelMenuCatalog({ ...base, sourceKey: 'cli', request }) + const stopChat = chat.subscribe(() => {}), + stopCli = terminal.subscribe(() => {}) + const chatRead = chat.read(false, undefined, new AbortController().signal), + cliRead = terminal.read(false, undefined, new AbortController().signal) + if (order === 'structured-first') { + acp.resolve(positive('base')) + await chatRead + expect(terminal.snapshot.pending).toBe(true) + cli.resolve(positive('variant')) + await cliRead + } else { + cli.resolve(positive('variant')) + await cliRead + expect(hostModelCatalogSnapshotAgents(target)).toEqual([]) + expect(chat.snapshot.pending).toBe(true) + acp.resolve(positive('base')) + await chatRead + } + expect(chat.snapshot.answer).toMatchObject({ models: [{ id: 'base' }] }) + expect(terminal.snapshot.answer).toMatchObject({ models: [{ id: 'variant' }] }) + stopCli() + for (const negative of [ + { origin: 'unknown' }, + { origin: 'probe', fetchedAt: 2, models: [] } + ] satisfies AgentSessionModelCatalogResult[]) { + recordHostModelCatalogSnapshot(target, 'antigravity', null, negative, 'cli') + recordHostModelCatalogSnapshot(target, 'antigravity', 'id:y', positive('sibling'), 'cli') + const successor = hostModelMenuCatalog({ ...base, sourceKey: 'cli', request }) + const detach = successor.subscribe(() => {}) + request.mockRejectedValueOnce(new Error('offline')) + expect(await successor.read(false, undefined, new AbortController().signal)).toEqual(negative) + expect( + readHostModelCatalogSnapshot( + target, + 'antigravity', + { newLaunch: true, seedsModel: true, worktree: 'id:x' }, + 'cli' + ) + ).toBeUndefined() + recordHostModelCatalogSnapshot(target, 'antigravity', null, positive('base-new')) + expect(successor.snapshot.answer).toEqual(negative) + expect( + readHostModelCatalogSnapshot(target, 'antigravity', { + newLaunch: true, + seedsModel: true, + worktree: null + }) + ).toMatchObject({ models: [{ id: 'base-new' }] }) + recordHostModelCatalogSnapshot(target, 'antigravity', 'id:x', negative, 'cli') + const scoped = hostModelMenuCatalog({ ...base, worktree: 'id:x', sourceKey: 'cli', request }) + const closeScoped = scoped.subscribe(() => {}) + closeScoped() + const reopened = hostModelMenuCatalog({ + ...base, + worktree: 'id:x', + sourceKey: 'cli', + request + }) + const closeReopened = reopened.subscribe(() => {}) + request.mockRejectedValueOnce(new Error('reopen offline')) + expect(await reopened.read(false, undefined, new AbortController().signal)).toEqual(negative) + closeReopened() + detach() + } + const late = Promise.withResolvers() + request.mockReturnValueOnce(late.promise) + const owner = hostModelMenuCatalog({ ...base, sourceKey: 'cli', request }) + const detach = owner.subscribe(() => {}) + const reading = owner.read(false, undefined, new AbortController().signal) + await Promise.resolve() + forgetHostModelCatalogSnapshots(target) + late.resolve(positive('stale')) + await reading + expect(owner.snapshot.answer).toBeUndefined() + expect(chat.snapshot.answer).toBeUndefined() + request.mockResolvedValueOnce(positive('replacement')) + expect(await owner.read(false, undefined, new AbortController().signal)).toMatchObject({ + models: [{ id: 'replacement' }] + }) + detach() + stopChat() + } +) diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-runtime-invalidation.test.ts b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-runtime-invalidation.test.ts index 0a697e79b2f..de0a2ec9519 100644 --- a/src/renderer/src/runtime/native-chat/model-catalogs/host-model-runtime-invalidation.test.ts +++ b/src/renderer/src/runtime/native-chat/model-catalogs/host-model-runtime-invalidation.test.ts @@ -4,11 +4,8 @@ import { act, cleanup, render, screen, waitFor } from '@testing-library/react' import { createElement } from 'react' import { useAgentModelMenu } from '@/components/agent/launch-settings/use-agent-model-menu' import { AgentChoiceControls } from '@/components/agent/launch-settings/AgentChoiceControls' +import type { AppState } from '@/store/types' import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire' -const transport = vi.hoisted(() => ({ call: vi.fn() })) -vi.mock('../requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: transport.call -})) const store = vi.hoisted(() => ({ subscribe: vi.fn().mockReturnValue(() => {}), getState: vi.fn() @@ -24,11 +21,66 @@ vi.mock('../../hosts/capabilities/local-runtime-capabilities', () => ({ subscribeLocalRuntimeCapabilitiesKnown: () => () => {} })) import { installHostModelCatalogSnapshotsSync } from './host-model-catalog-snapshots-sync' +import { hostModelMenuCatalog } from './host-model-menu-catalog' import { recordHostModelCatalogSnapshot, resetHostModelCatalogSnapshotsForTests } from './host-model-catalog-snapshots' +it('switching PowerShell to WSL invalidates a fresh native list and its in-flight request', async () => { + resetHostModelCatalogSnapshotsForTests() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the subscription only reads these fields; state transport is the external port. + const previous = { + settings: { terminalWindowsShell: 'powershell.exe', terminalWindowsWslDistro: 'Ubuntu' }, + runtimeStatusByEnvironmentId: new Map(), + removedRuntimeEnvironmentIds: new Set() + } as unknown as AppState + store.getState.mockReturnValue(previous) + const cleanup = installHostModelCatalogSnapshotsSync() + const change = store.subscribe.mock.calls[0][0] + const native = { + origin: 'probe', + fetchedAt: 0, + models: [{ id: 'native-model', label: 'Native', isDefault: false, efforts: [] }] + } as const + const guest = { + ...native, + models: [{ id: 'ubuntu-model', label: 'Ubuntu', isDefault: false, efforts: [] }] + } + const late = Promise.withResolvers() + const request = vi + .fn() + .mockResolvedValueOnce(native) + .mockReturnValueOnce(late.promise) + .mockResolvedValueOnce(guest) + const scope = { + target: { kind: 'local' } as const, + agent: 'antigravity', + sourceKey: 'cli-shell', + request + } + const owner = hostModelMenuCatalog(scope) + const stop = owner.subscribe(() => {}) + await owner.read(true, undefined, new AbortController().signal) + const pending = owner.read(false, undefined, new AbortController().signal) + await Promise.resolve() + const successor = { + ...previous, + settings: { ...previous.settings, terminalWindowsShell: 'wsl.exe' } + } + store.getState.mockReturnValue(successor) + change(successor, previous) + expect(await owner.read(true, undefined, new AbortController().signal)).toMatchObject({ + models: [{ id: 'ubuntu-model' }] + }) + late.resolve(native) + await pending + expect(owner.snapshot.answer).toMatchObject({ models: [{ id: 'ubuntu-model' }] }) + expect(request).toHaveBeenCalledTimes(3) + stop() + cleanup() +}) + it('keeps closed Settings labels through a full settings fetch and a saved model choice', async () => { resetHostModelCatalogSnapshotsForTests() store.subscribe.mockClear() @@ -47,7 +99,7 @@ it('keeps closed Settings labels through a full settings fetch and a saved model const changed = store.subscribe.mock.calls[0][0] const request = vi.fn() const source = { - scope: { target: { kind: 'local' as const }, agent: 'codex' }, + scope: { target: { kind: 'local' as const }, agent: 'codex', request }, coherentCatalog: true } function Editor({ model }: { model?: string }) { @@ -66,7 +118,8 @@ it('keeps closed Settings labels through a full settings fetch and a saved model const coldSource = { scope: { target: { kind: 'environment' as const, environmentId: 'without-preload' }, - agent: 'codex' + agent: 'codex', + request: coldRequest }, coherentCatalog: true } @@ -81,9 +134,6 @@ it('keeps closed Settings labels through a full settings fetch and a saved model onChange: () => {} }) } - transport.call.mockImplementation((target) => - target.kind === 'environment' ? coldRequest() : request() - ) const cold = render(createElement(Unpreloaded, { open: false })) try { expect( diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/model-menu-cli-catalog.ts b/src/renderer/src/runtime/native-chat/model-catalogs/model-menu-cli-catalog.ts new file mode 100644 index 00000000000..ea118ed2da2 --- /dev/null +++ b/src/renderer/src/runtime/native-chat/model-catalogs/model-menu-cli-catalog.ts @@ -0,0 +1,69 @@ +import { getAgentModelProbeSpec } from '../../../../../shared/agent-model-probe-spec' +import { isTuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent-config' +import { TERMINAL_EXECUTION_CONTEXT_UNRESOLVED } from '../../../../../shared/terminal/effective-terminal-execution-context' +import { ModelMenuContextUnresolvedError } from './host-model-menu-catalog' +import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire' +import type { + RuntimeDiscoverCommitMessageModelsResult, + RuntimeGitContext +} from '@/runtime/source-control/git/runtime-git-client-context' +import { discoverRuntimeTerminalModels } from './terminal-model-discovery-client' +import type { HostModelMenuScope } from './host-model-menu-catalog' + +export function cliModelCatalogAnswer( + agent: string, + result: RuntimeDiscoverCommitMessageModelsResult +): AgentSessionModelCatalogResult | undefined { + if ( + !result.success || + result.catalogOrigin === 'spec' || + (!result.catalogOrigin && !result.models.length) + ) { + return undefined + } + const fallback = isTuiAgent(agent) ? getAgentModelProbeSpec(agent) : undefined + if ( + !result.catalogOrigin && + fallback && + result.defaultModelId === fallback.defaultModelId && + result.models.length === fallback.models.length + ) { + const fallbackIds = new Set(fallback.models.map(({ id }) => id)) + if (result.models.every(({ id }) => fallbackIds.has(id))) { + return undefined + } + } + return { + origin: 'probe', + // This transport has no catalog timestamp; identical listings retain identical values. + fetchedAt: 0, + listingNamesConfiguredModel: false, + modelsDifferByWorkspace: true, + models: result.models.map(({ id, label }) => ({ id, label, isDefault: false, efforts: [] })) + } +} + +export function cliModelMenuScope( + context: RuntimeGitContext, + agent: string, + invocation: string, + runtime?: string +): HostModelMenuScope { + return { + target: context.target, + agent, + ...(context.worktreeId ? { worktree: `id:${context.worktreeId}` } : {}), + sourceKey: JSON.stringify(['cli', invocation.trim(), runtime]), + request: async () => { + // The existing remote operation requires a workspace; its helper otherwise falls through to local IPC. + if (context.target.kind === 'environment' && !context.worktreeId) { + return undefined + } + const result = await discoverRuntimeTerminalModels({ ...context, prefs: undefined }, agent) + if (!result.success && result.error === TERMINAL_EXECUTION_CONTEXT_UNRESOLVED) { + throw new ModelMenuContextUnresolvedError(result.error) + } + return cliModelCatalogAnswer(agent, result) + } + } +} diff --git a/src/renderer/src/runtime/native-chat/model-catalogs/terminal-model-discovery-client.ts b/src/renderer/src/runtime/native-chat/model-catalogs/terminal-model-discovery-client.ts new file mode 100644 index 00000000000..de128049724 --- /dev/null +++ b/src/renderer/src/runtime/native-chat/model-catalogs/terminal-model-discovery-client.ts @@ -0,0 +1,48 @@ +import { translate } from '@/i18n/i18n' +import type { + RuntimeGitContext, + RuntimeDiscoverCommitMessageModelsResult +} from '@/runtime/source-control/git/runtime-git-client-context' +import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' +import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector' +import { TEXT_GENERATION_CLIENT_TIMEOUT_MS } from '../../../../../shared/text-generation-client-timeout' + +export async function discoverRuntimeTerminalModels( + context: RuntimeGitContext, + agentId: string +): Promise { + const worktree = context.worktreeId + ? toRuntimeWorktreeSelector(context.worktreeId) + : context.worktreePath + ? `path:${context.worktreePath}` + : undefined + if (context.target.kind === 'local') { + if (context.connectionId) { + return { + success: false, + error: translate( + 'agents.terminalModels.connectionUnavailable', + 'Terminal model discovery is unavailable on this connection.' + ) + } + } + return window.api.git.discoverTerminalModels({ agentId, ...(worktree ? { worktree } : {}) }) + } + if (!context.worktreeId) { + return { + success: false, + error: translate( + 'agents.terminalModels.workspaceRequired', + 'Terminal model discovery requires a workspace on this host.' + ) + } + } + return callRuntimeRpc( + context.target, + 'agent.discoverTerminalModels', + { worktree, agentId }, + { + timeoutMs: TEXT_GENERATION_CLIENT_TIMEOUT_MS + } + ) +} diff --git a/src/renderer/src/web/preload-api/web-git-api.ts b/src/renderer/src/web/preload-api/web-git-api.ts index 84ae7eefd54..657c5da54f6 100644 --- a/src/renderer/src/web/preload-api/web-git-api.ts +++ b/src/renderer/src/web/preload-api/web-git-api.ts @@ -235,6 +235,13 @@ export function createGitApi(): NonNullable['git']> { 'Commit message generation is unavailable in the web client.' ) }), + discoverTerminalModels: async () => ({ + success: false, + error: translate( + 'agents.terminalModels.hostRequired', + 'Terminal model discovery requires a connected host.' + ) + }), discoverCommitMessageModels: async () => ({ success: false, error: translate( diff --git a/src/shared/agent-launch/picker/agent-launch-picker-authority.ts b/src/shared/agent-launch/picker/agent-launch-picker-authority.ts index 706bbf4f8ee..93a5976a85e 100644 --- a/src/shared/agent-launch/picker/agent-launch-picker-authority.ts +++ b/src/shared/agent-launch/picker/agent-launch-picker-authority.ts @@ -1,8 +1,12 @@ -import type { AgentPickerEntry, AgentPickerDraft } from './agent-launch-picker' +import type { + AgentPickerEntry, + AgentPickerDraft, + AgentPickerCatalogView +} from './agent-launch-picker' export function agentPickerCatalogAuthoritative( - entry: AgentPickerEntry -): entry is AgentPickerEntry & { + entry: AgentPickerCatalogView +): entry is AgentPickerCatalogView & { catalog: Exclude } { return ( diff --git a/src/shared/agent-launch/picker/agent-launch-picker-catalog.ts b/src/shared/agent-launch/picker/agent-launch-picker-catalog.ts index b632ae1936c..d5dc2bfb142 100644 --- a/src/shared/agent-launch/picker/agent-launch-picker-catalog.ts +++ b/src/shared/agent-launch/picker/agent-launch-picker-catalog.ts @@ -1,3 +1,4 @@ +import { agentPickerCatalogView } from './agent-launch-picker-source' import { modelMenuOptions } from '../../agent-session/options/model-menu-options' import { listedModelDescribing } from '../../agent-session/options/structured-agent-session-listed-model' import { @@ -44,18 +45,16 @@ export function agentPickerEntryOptions( ] : [] } + const view = agentPickerCatalogView(entry, surface) let options = agentPickerOptions(entry.agent, model, surface) - const rows = agentPickerModels(entry, surface) - const composer = agentPickerUsesComposerModelMenu(entry, surface) - const live = composer - ? model - ? listedModelDescribing(rows, undefined, model) - : rows.find((row) => row.isDefault) - : rows.find((row) => row.id === model || (model === undefined && row.isDefault)) - if (composer && !live && model) { + const rows = agentPickerModelMenu(entry, surface).rows + const live = model + ? listedModelDescribing(rows, undefined, model) + : rows.find((row) => row.isDefault) + if (!live && model) { return [] } - if (entry.catalog.origin === 'unknown' || !live) { + if (view.catalog.origin === 'unknown' || !live) { return options.filter( (option) => option.kind.type !== 'select' || option.kind.choices.length > 0 ) @@ -64,13 +63,13 @@ export function agentPickerEntryOptions( options = createClaudeCatalogOptions({ effortLevelIds: live.efforts.map((choice) => choice.value), supportsFastMode: - live.supportsFastMode === true && entry.catalog.fastModeSupport?.supported !== false + live.supportsFastMode === true && view.catalog.fastModeSupport?.supported !== false }) } if (surface === 'chat' || entry.agent === 'codex') { const dynamic = discoveredModel( live, - entry.catalog.fastModeSupport?.supported !== false, + view.catalog.fastModeSupport?.supported !== false, entry.agent ).options if (entry.agent === 'codex') { @@ -90,7 +89,7 @@ export function agentPickerEntryOptions( return [option] } if (!live.efforts.length) { - return !composer && live.effortsKnown === false ? [option] : [] + return [] } return [ { @@ -116,12 +115,13 @@ export function agentPickerModelMenu( surface: AgentPickerSurface = entry.defaultSurface, saved?: Readonly> ) { - return modelMenuOptions(entry.catalog, { + const view = agentPickerCatalogView(entry, surface) + return modelMenuOptions(view.catalog, { agent: entry.agent, surface: entry.textGeneration ? 'textGeneration' : surface, seed: getAgentSessionOptionLaunchCatalog(entry.agent) ?? { models: [], modelApply: {} }, - pending: entry.catalogRead === 'pending', - coherentCatalog: entry.coherentCatalog, + pending: view.catalogRead === 'pending', + coherentCatalog: view.coherentCatalog, newLaunch: true, seedsModel: true, saved @@ -132,27 +132,20 @@ export function agentPickerModels( entry: AgentPickerEntry, surface: AgentPickerSurface = entry.defaultSurface ): AgentPickerModel[] { - if (!agentPickerUsesComposerModelMenu(entry, surface)) { - if (entry.catalog.origin !== 'unknown') { - return entry.catalog.models - } - return (getAgentSessionOptionLaunchCatalog(entry.agent)?.models ?? []).map((model) => ({ - id: model.id, - label: model.label, - description: model.description, - isDefault: model.isDefault === true, - efforts: model.options.flatMap((option) => - option.id === 'effort' && option.kind.type === 'select' ? option.kind.choices : [] - ) - })) + if (entry.textGeneration && entry.catalog.origin !== 'unknown') { + return entry.catalog.models } return agentPickerModelMenu(entry, surface).rows } -/** Terminal discovery is a separate change; these menus keep their existing catalog policy. */ -export function agentPickerUsesComposerModelMenu( +export function agentPickerNamesConfiguredModel( entry: AgentPickerEntry, surface: AgentPickerSurface ) { - return !entry.textGeneration && !(entry.agent === 'antigravity' && surface === 'terminal') + const { catalog } = agentPickerCatalogView(entry, surface) + return ( + catalog.origin !== 'unknown' && + (catalog.listingNamesConfiguredModel ?? + getAgentSessionOptionLaunchCatalog(entry.agent)?.hostListingNamesConfiguredModel === true) + ) } diff --git a/src/shared/agent-launch/picker/agent-launch-picker-edits.ts b/src/shared/agent-launch/picker/agent-launch-picker-edits.ts index 7418b53c3d1..d0f46825a8f 100644 --- a/src/shared/agent-launch/picker/agent-launch-picker-edits.ts +++ b/src/shared/agent-launch/picker/agent-launch-picker-edits.ts @@ -1,3 +1,6 @@ +import { modelCatalogChoiceEdit } from '../../agent-session/options/model-catalog-source' +import { agentPickerModels } from './agent-launch-picker-catalog' +import { agentPickerCatalogSource } from './agent-launch-picker-source' import { analyzeAgentChoiceArgs } from '../choices/agent-choice-args' import { reconcileAgentChoiceArgsDetailed } from '../choices/agent-choice-reconciliation' import { projectAgentLaunchProfile } from '../choices/agent-launch-profile' @@ -173,7 +176,12 @@ export function applyAgentPickerEdit( } const patch: AgentChoicePatch = edit.kind === 'choice' - ? edit.patch + ? modelCatalogChoiceEdit( + agentPickerCatalogSource(entry, draft.surface), + agentPickerModels(entry, draft.surface), + agentPickerEffectiveChoices(entry, draft).model, + edit.patch + ) : edit.kind === 'permission' ? { permissionMode: edit.value } : edit.kind === 'speed' diff --git a/src/shared/agent-launch/picker/agent-launch-picker-entry.ts b/src/shared/agent-launch/picker/agent-launch-picker-entry.ts new file mode 100644 index 00000000000..ae2d3055e38 --- /dev/null +++ b/src/shared/agent-launch/picker/agent-launch-picker-entry.ts @@ -0,0 +1,33 @@ +import type { AgentSessionModelCatalogResult } from '../../agent-session/agent-session-wire' +import type { ModelCatalogSource } from '../../agent-session/options/model-catalog-source' +import type { AgentDedicatedChoices } from '../choices/agent-launch-choices' +import type { TuiAgent } from '../catalog/tui-agent' +import type { TextActionPickerCatalog } from './agent-launch-picker-text-action' +import type { NewTabAgentMenuRow } from './agent-launch-picker-rows' +import type { AgentPickerSurface } from './agent-launch-picker' + +export type AgentPickerCatalogView = { + catalog: AgentSessionModelCatalogResult + coherentCatalog?: boolean + catalogRead?: 'pending' | 'settled' | 'failed' | 'unsupported' +} +export type AgentPickerEntry = AgentPickerCatalogView & { + sourceCatalogs?: Partial> + textGeneration?: TextActionPickerCatalog + agent: TuiAgent + label: string + description?: string + aliases?: string[] + rows: NewTabAgentMenuRow[] + surfaces: AgentPickerSurface[] + defaultSurface: AgentPickerSurface + terminal: AgentDedicatedChoices + structured: AgentDedicatedChoices + arguments?: string | null + ownerKey?: string + draftTarget?: { key: string; worktreeId?: string; repoId?: string; executionHostId: string } + /** The workspace the agent launches in, whose files and skills its first prompt can name. */ + worktreeId?: string + defaultsPending?: boolean + structuredDefaultsPending?: boolean +} diff --git a/src/shared/agent-launch/picker/agent-launch-picker-search.ts b/src/shared/agent-launch/picker/agent-launch-picker-search.ts index f25308bd40c..1d2bd37a80c 100644 --- a/src/shared/agent-launch/picker/agent-launch-picker-search.ts +++ b/src/shared/agent-launch/picker/agent-launch-picker-search.ts @@ -1,10 +1,11 @@ import { agentPickerModels } from './agent-launch-picker-catalog' import { resolveAgentChoiceLayers } from '../choices/agent-choice-layers' -import type { AgentPickerEntry, AgentPickerModel } from './agent-launch-picker' +import type { AgentPickerEntry, AgentPickerModel, AgentPickerSurface } from './agent-launch-picker' import type { AgentDedicatedChoices } from '../choices/agent-launch-choices' export type AgentPickerSetup = { entry: AgentPickerEntry + surface: AgentPickerSurface model: AgentPickerModel choices: AgentDedicatedChoices label: string @@ -26,7 +27,8 @@ const score = (word: string, values: readonly string[]): number => export function searchAgentPickerSetups( entries: readonly AgentPickerEntry[], query: string, - limit = 8 + limit = 8, + surfaceForEntry: (entry: AgentPickerEntry) => AgentPickerSurface = (entry) => entry.defaultSurface ): AgentPickerSetup[] { const words = tokens(query) if (!words.length) { @@ -41,7 +43,8 @@ export function searchAgentPickerSetups( if (words.every((word) => score(word, agentWords))) { continue } - for (const model of agentPickerModels(entry)) { + const surface = surfaceForEntry(entry) + for (const model of agentPickerModels(entry, surface)) { if (model.isLegacy || model.hidden) { continue } @@ -74,6 +77,7 @@ export function searchAgentPickerSetups( matches.push({ setup: { entry, + surface, model, choices, label: [entry.label, model.label, effort?.label].filter(Boolean).join(' · ') diff --git a/src/shared/agent-launch/picker/agent-launch-picker-source.ts b/src/shared/agent-launch/picker/agent-launch-picker-source.ts new file mode 100644 index 00000000000..ce15fd12fd6 --- /dev/null +++ b/src/shared/agent-launch/picker/agent-launch-picker-source.ts @@ -0,0 +1,47 @@ +import { + modelCatalogSource, + type ModelCatalogSource +} from '../../agent-session/options/model-catalog-source' +import type { + AgentPickerEntry, + AgentPickerSurface, + AgentPickerCatalogView +} from './agent-launch-picker' + +const pending: AgentPickerCatalogView = { + catalog: { origin: 'unknown' }, + catalogRead: 'pending', + coherentCatalog: true +} + +export function agentPickerCatalogSource(entry: AgentPickerEntry, surface = entry.defaultSurface) { + return entry.textGeneration ? 'structured' : modelCatalogSource(entry.agent, surface) +} + +export function agentPickerSourceView( + entry: AgentPickerEntry, + source: ModelCatalogSource +): AgentPickerCatalogView { + return source === 'structured' ? entry : (entry.sourceCatalogs?.[source] ?? pending) +} + +export function agentPickerCatalogView( + entry: AgentPickerEntry, + surface: AgentPickerSurface = entry.defaultSurface +) { + return agentPickerSourceView(entry, agentPickerCatalogSource(entry, surface)) +} + +export function withAgentPickerSourceView( + entry: AgentPickerEntry, + source: ModelCatalogSource, + view: AgentPickerCatalogView +): AgentPickerEntry { + return source === 'structured' + ? { ...entry, ...view } + : { ...entry, sourceCatalogs: { ...entry.sourceCatalogs, [source]: view } } +} + +export function agentPickerCatalogSources(entry: AgentPickerEntry): ModelCatalogSource[] { + return [...new Set(entry.surfaces.map((surface) => agentPickerCatalogSource(entry, surface)))] +} diff --git a/src/shared/agent-launch/picker/agent-launch-picker.ts b/src/shared/agent-launch/picker/agent-launch-picker.ts index ca1f3675565..1adde62f238 100644 --- a/src/shared/agent-launch/picker/agent-launch-picker.ts +++ b/src/shared/agent-launch/picker/agent-launch-picker.ts @@ -1,5 +1,5 @@ +import type { AgentPickerEntry } from './agent-launch-picker-entry' import { parseExecutionHostId, type ExecutionHostId } from '../../execution-host' -import type { TextActionPickerCatalog } from './agent-launch-picker-text-action' import { agentPickerLaunchChoices } from './agent-launch-picker-effective-choices' import { agentPickerPanelArguments } from './agent-launch-picker-arguments' import { agentPickerArgumentsKnown } from './agent-launch-picker-authority' @@ -11,10 +11,7 @@ import { reconcileAgentChoiceArgs, reconcileAgentChoiceArgsDetailed } from '../choices/agent-choice-reconciliation' -import type { - AgentSessionModelCatalogResult, - AgentSessionModelOption -} from '../../agent-session/agent-session-wire' +import type { AgentSessionModelOption } from '../../agent-session/agent-session-wire' import { orderAgentLaunchPickerAgents, type NewTabAgentMenuRow } from './agent-launch-picker-rows' import type { TuiAgent } from '../catalog/tui-agent' import type { CurrentActionSelection } from '../../source-control/ai/recipes/source-control-action-selection' @@ -22,28 +19,7 @@ import type { CurrentActionSelection } from '../../source-control/ai/recipes/sou export type AgentPickerSurface = 'chat' | 'terminal' export type AgentPickerDraftOwner = object export type AgentPickerModel = AgentSessionModelOption & { isLegacy?: true; hidden?: true } -export type AgentPickerEntry = { - textGeneration?: TextActionPickerCatalog - agent: TuiAgent - label: string - description?: string - aliases?: string[] - rows: NewTabAgentMenuRow[] - surfaces: AgentPickerSurface[] - defaultSurface: AgentPickerSurface - terminal: AgentDedicatedChoices - structured: AgentDedicatedChoices - arguments?: string | null - catalog: AgentSessionModelCatalogResult - coherentCatalog?: boolean - catalogRead?: 'pending' | 'settled' | 'failed' | 'unsupported' - ownerKey?: string - draftTarget?: { key: string; worktreeId?: string; repoId?: string; executionHostId: string } - /** The workspace the agent launches in, whose files and skills its first prompt can name. */ - worktreeId?: string - defaultsPending?: boolean - structuredDefaultsPending?: boolean -} +export type { AgentPickerEntry, AgentPickerCatalogView } from './agent-launch-picker-entry' export type AgentPickerDraft = { agent: TuiAgent surface: AgentPickerSurface diff --git a/src/shared/agent-session/options/host-model-catalog-snapshot-rules.ts b/src/shared/agent-session/options/host-model-catalog-snapshot-rules.ts index 163ac76206b..79d65e43663 100644 --- a/src/shared/agent-session/options/host-model-catalog-snapshot-rules.ts +++ b/src/shared/agent-session/options/host-model-catalog-snapshot-rules.ts @@ -139,7 +139,12 @@ export const HOST_MODEL_CATALOG_ACCOUNT_SETTINGS = [ 'activeClaudeManagedAccountIdsByRuntime', 'claudeManagedAccounts', 'agentDefaultEnv', - 'agentCmdOverrides' + 'agentCmdOverrides', + 'terminalWindowsShell', + 'terminalWindowsWslDistro', + 'terminalDefaultShell', + 'localWindowsRuntimeDefault', + 'experimentalWslHosts' ] as const satisfies readonly (keyof GlobalSettings)[] /** A host that advertises saved-only reads answers every agent without starting its CLI. */ diff --git a/src/shared/agent-session/options/model-catalog-source.ts b/src/shared/agent-session/options/model-catalog-source.ts new file mode 100644 index 00000000000..648737a42d5 --- /dev/null +++ b/src/shared/agent-session/options/model-catalog-source.ts @@ -0,0 +1,32 @@ +import type { AgentChoicePatch } from '../../agent-launch/choices/agent-launch-choices' +import type { AgentSessionModelOption } from '../agent-session-wire' + +export type ModelCatalogSource = 'structured' | 'cli' +export type ModelCatalogSurface = 'chat' | 'terminal' | 'textGeneration' + +const sources: Readonly>>> = + { + antigravity: { terminal: 'cli' } + } + +export function modelCatalogSource( + agent: string, + surface: ModelCatalogSurface +): ModelCatalogSource { + return sources[agent]?.[surface] ?? 'structured' +} + +/** Only an explicit replacement may clear menu-owned options the new source row cannot express. */ +export function modelCatalogChoiceEdit( + source: ModelCatalogSource, + rows: readonly AgentSessionModelOption[], + currentModel: string | undefined, + patch: AgentChoicePatch +): AgentChoicePatch { + return source === 'cli' && + patch.model && + patch.model !== currentModel && + rows.some((row) => row.id === patch.model && row.efforts.length === 0) + ? { ...patch, options: { ...patch.options, effort: null } } + : patch +} diff --git a/src/shared/project-runtime-repair-message.ts b/src/shared/project-runtime-repair-message.ts index 38ef79e96e4..f4edb12a88e 100644 --- a/src/shared/project-runtime-repair-message.ts +++ b/src/shared/project-runtime-repair-message.ts @@ -42,3 +42,12 @@ export function agentLaunchRepairRefusal(repair: ProjectExecutionRuntimeRepair): : '' return `No agent was started. ${projectRuntimeRepairSentence(repair, english)}${byDefault}` } + +/** Legacy Git refuses with text; terminal launch also supplies the typed refusal code. */ +export function isProjectRuntimeRepairRefusal(error: unknown): error is Error { + return ( + error instanceof Error && + (('code' in error && error.code === PROJECT_RUNTIME_REPAIR_REQUIRED_CODE) || + error.message.startsWith('Project runtime requires repair before git execution:')) + ) +} diff --git a/src/shared/rpc-contract/agent-model-discovery-params.ts b/src/shared/rpc-contract/agent-model-discovery-params.ts new file mode 100644 index 00000000000..b2d4a26013a --- /dev/null +++ b/src/shared/rpc-contract/agent-model-discovery-params.ts @@ -0,0 +1,3 @@ +import { z } from 'zod' +import { WorktreeSelector } from './git-params' +export const AgentDiscoverTerminalModels = WorktreeSelector.extend({ agentId: z.string().min(1) }) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index d68a27482b2..127e22d1987 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -73,6 +73,7 @@ import { AgentActivityClearParams, AgentActivitySetReadParams } from './agent-ac import { PrepareCodexForWslPaneParams } from './agent-hooks-params' import { AgentLaunch, AgentLaunchReplay } from './agent-launch-params' import { AgentLaunchSettingsMutation } from './agent-launch-settings-params' +import { AgentDiscoverTerminalModels } from './agent-model-discovery-params' import { AttachmentReadParams, AttachmentTextReadParams, @@ -818,6 +819,7 @@ export const RPC_PARAMS_BY_METHOD = { 'accounts.zcodePlanClearApiKey': null, 'accounts.zcodePlanCredentialsStatus': null, 'accounts.zcodePlanSaveApiKey': UsageCredentialApiKeyParams, + 'agent.discoverTerminalModels': AgentDiscoverTerminalModels, 'agent.launch': AgentLaunch, 'agent.launchReplay': AgentLaunchReplay, 'agentActivity.clear': AgentActivityClearParams, diff --git a/src/shared/terminal/effective-terminal-execution-context.test.ts b/src/shared/terminal/effective-terminal-execution-context.test.ts new file mode 100644 index 00000000000..87b1ae5799d --- /dev/null +++ b/src/shared/terminal/effective-terminal-execution-context.test.ts @@ -0,0 +1,14 @@ +import { expect, it } from 'vitest' +import { selectEffectiveTerminalExecutionContext } from './effective-terminal-execution-context' + +it('retains the PTY worktree identity over a native cwd and shell', () => { + expect( + selectEffectiveTerminalExecutionContext({ + platform: 'win32', + cwd: 'C:\\plain', + shell: 'powershell.exe', + preferredDistro: 'Debian', + worktreeContext: { distro: 'Ubuntu', treatPosixCwdAsWsl: true } + }) + ).toEqual({ kind: 'wsl', context: { distro: 'Ubuntu', treatPosixCwdAsWsl: true } }) +}) diff --git a/src/shared/terminal/effective-terminal-execution-context.ts b/src/shared/terminal/effective-terminal-execution-context.ts new file mode 100644 index 00000000000..922876c0fd8 --- /dev/null +++ b/src/shared/terminal/effective-terminal-execution-context.ts @@ -0,0 +1,36 @@ +import { isWslShellName } from '../local-windows-terminal-runtime' +import { parseWslUncPath } from '../wsl-paths' + +export type TerminalWslContext = { distro: string; treatPosixCwdAsWsl: true } +export type EffectiveTerminalExecutionContext = + | { kind: 'native' } + | { kind: 'wsl'; context: TerminalWslContext } + | { kind: 'unresolved-wsl' } + +/** Select execution without preparing a shell, directory, or environment. */ +export function selectEffectiveTerminalExecutionContext(args: { + platform: NodeJS.Platform + cwd?: string + worktreeContext?: TerminalWslContext + shell?: string + preferredDistro?: string | null + defaultDistro?: string | null +}): EffectiveTerminalExecutionContext { + if (args.platform !== 'win32') { + return { kind: 'native' } + } + const cwdDistro = args.cwd ? parseWslUncPath(args.cwd)?.distro : undefined + const authoritative = cwdDistro ?? args.worktreeContext?.distro + if (authoritative) { + return { kind: 'wsl', context: { distro: authoritative, treatPosixCwdAsWsl: true } } + } + if (!isWslShellName(args.shell)) { + return { kind: 'native' } + } + const distro = args.preferredDistro?.trim() || args.defaultDistro?.trim() + return distro + ? { kind: 'wsl', context: { distro, treatPosixCwdAsWsl: true } } + : { kind: 'unresolved-wsl' } +} + +export const TERMINAL_EXECUTION_CONTEXT_UNRESOLVED = 'terminal_execution_context_unresolved'