Files
archived-orca/src/main/runtime/runtime-client-settings.ts
T
Neil d3341196b8 feat(codex): history follows you into ~/.codex on system default, with a per-host opt-out (#24511) (#34981)
* fix(codex): link managed-account history into the user's own ~/.codex on system default

When system default launches Codex on the real ~/.codex, bridge every trusted
managed host account home into it so sessions started on a managed account
stay resumable after switching back (#25000).

Split from #33578 (host half). Needs an owner product decision (#10770 vs #24511).

* feat(codex): a per-host opt-out for sharing Codex history across accounts (#24511)

Adds codexShareHistoryAcrossAccounts (absent = on, today's #10770 behaviour).
Off, the host that launches Codex starts none of its history bridges: system
default into the shared runtime home, accounts and ~/.codex into a per-account
home, managed accounts into the real ~/.codex, and the WSL distro and sibling
accounts into a WSL account home. Turning it off removes nothing already linked.

The setting lives in each host's own store, since that host writes the links.
Settings → Agents shows it for the selected host: local writes update this app,
a paired SSH or WSL host is read and written over settings.get/settings.update.
New hosts always publish the key; a host that doesn't is shown as needing an
update and is never sent it, because older hosts' strict update schema would
reject the call. Strings are localized for all 11 locales.

The system-default lane moves into the launch class, keeping managed-home under
the line cap.

* fix(codex): ~/.codex gets hardlinks or nothing, and a WSL history source is left to the WSL lane

The system-default lane wrote into codexSessionSourceHome when set, which can be
a \\wsl.localhost path: the background scan would boot a stopped distro over 9P
and its cross-volume symlinks are ignored by codex resume. That lane now returns
early for a WSL UNC target; the WSL lane owns those homes.

Into the user's own ~/.codex the bridge now links with hardlinks only: a failed
hardlink (EXDEV across volumes) skips the rollout, counted as skippedFiles,
removes any folder it just created, and never falls back to a symlink that
codex resume ignores and that would dangle once an account is removed. Bridges
between Orca-managed homes keep the symlink fallback.

Also: the setting's JSDoc sits above its own field, and Settings search finds
the switch (codex, history, share, shared, account; existing localized keys).
2026-10-28 21:26:42 -07:00

302 lines
14 KiB
TypeScript

import { publishedLegacyChatPermissionMode } from '../../shared/agent-chat-permission-mode'
import { getClaudeAgentViewService } from '../claude/agent-view-service'
import { getAppEnvironment } from '../../shared/app-environment'
import { isArtifactSharingEnabled } from '../../shared/artifact-sharing-gate'
import { isAgentSkillSharingEnabled } from '../../shared/agent-skill-sharing-gate'
import { applyPRBotAuthorOverride } from '../../shared/pr-bot-author-overrides'
import { TASK_PROVIDERS } from '../../shared/task-providers'
import {
applyTerminalQuickCommandMutation,
type TerminalQuickCommandMutation
} from '../../shared/terminal-quick-commands'
import { haveSameDisabledTuiAgents } from '../../shared/tui-agent-selection'
import { normalizeSourceControlAiSettings } from '../../shared/source-control-ai'
import { normalizeSourceControlGroupOrder } from '../../shared/source-control-group-order'
import { SOURCE_CONTROL_LAUNCH_ACTION_IDS } from '../../shared/source-control-ai-actions'
import type { GlobalSettings } from '../../shared/global-settings-types'
import { applyNativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-option-defaults'
import type { NativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-options'
import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides'
import type { TerminalQuickCommand } from '../../shared/terminal-quick-command-types'
import { recordManagedHookInstallFailure } from '../agent-hooks/install-telemetry'
import { applyAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls'
import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path'
import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-status-hooks-setting'
import type { RuntimeStore } from './runtime-store-contract'
import {
agentLaunchSettingsMutationUpdates,
projectAgentLaunchSettings,
type AgentLaunchSettings,
type AgentLaunchSettingsMutation
} from '../../shared/agent-launch-settings'
import { legacyLaunchTextUpdates } from '../../shared/agent-launch-permission-updates'
import { composeAgentLaunchProfile } from '../../shared/tui-agent-launch-defaults'
import { agentLaunchSettingsRollbackUpdates } from './agent-launch-settings-rollback'
import type {
RuntimeClientSettings,
RuntimeClientSettingsUpdate,
RuntimeClientSourceControlAi,
RuntimeHostDisplayLabelOverrides
} from './runtime-client-settings-shape'
/** Which Orca cloud services this host registered; headless hosts register none. */
export type RuntimeSharingServicePresence = {
artifacts(): boolean
skills(): boolean
}
export class RuntimeClientSettingsController {
private reconciliationGeneration = 0
private reconciliationTail: Promise<void> = Promise.resolve()
constructor(
private readonly store: Pick<
RuntimeStore,
'getSettings' | 'updateSettings' | 'runDurableMutation'
> | null,
private readonly notifyReposChanged: (() => void) | undefined = undefined,
private readonly sharingServices: RuntimeSharingServicePresence | undefined = undefined
) {}
get(): RuntimeClientSettings {
if (!this.store?.getSettings) {
throw new Error('runtime_unavailable')
}
const settings = this.store.getSettings()
// Older clients read permission from composed argument text, before a stored choice existed.
const launchProfile = composeAgentLaunchProfile(settings, process.platform)
return {
defaultTuiAgent: settings.defaultTuiAgent ?? null,
newWorkspaceSetupOnly: false,
disabledTuiAgents: settings.disabledTuiAgents ?? [],
agentCmdOverrides: settings.agentCmdOverrides ?? {},
agentDefaultArgs: launchProfile.agentDefaultArgs,
agentDefaultEnv: launchProfile.agentDefaultEnv,
agentStatusHooksEnabled: settings.agentStatusHooksEnabled !== false,
// Always present, so a client can tell this host accepts the setting (older hosts omit it).
codexShareHistoryAcrossAccounts: settings.codexShareHistoryAcrossAccounts !== false,
claudeSubagentNavigationEnabled: settings.claudeSubagentNavigationEnabled !== false,
// Mobile honors this Copy option; absence from older hosts means on (#19770).
terminalCopyTrimsGutter: settings.terminalCopyTrimsGutter !== false,
defaultTaskSource: settings.defaultTaskSource ?? 'github',
defaultTaskViewPreset: settings.defaultTaskViewPreset ?? 'issues',
visibleTaskProviders: settings.visibleTaskProviders ?? [...TASK_PROVIDERS],
defaultRepoSelection: settings.defaultRepoSelection ?? null,
// Persisted settings can violate the paired client's string-array contract.
defaultLinearTeamSelection: Array.isArray(settings.defaultLinearTeamSelection)
? settings.defaultLinearTeamSelection.filter((id): id is string => typeof id === 'string')
: null,
githubProjects: settings.githubProjects,
experimentalNewWorktreeCardStyle: settings.experimentalNewWorktreeCardStyle === true,
experimentalNativeChat: settings.experimentalNativeChat === true,
// Older clients use this key to fall back to terminal-backed chat. Keep their default terminal.
openAgentTabsInChatByDefault: false,
experimentalStructuredNativeChat: settings.experimentalNativeChat === true,
compactWorktreeCards: settings.compactWorktreeCards === true,
minimaxGroupId: settings.minimaxGroupId ?? '',
minimaxUsageModels: settings.minimaxUsageModels ?? 'general',
minimaxEndpoint: settings.minimaxEndpoint ?? 'overseas',
zcodePlanSite: settings.zcodePlanSite ?? 'zai',
prBotAuthorOverrides: settings.prBotAuthorOverrides ?? [],
// Paired clients order their Source Control lists the way this desktop does.
sourceControlGroupOrder: normalizeSourceControlGroupOrder(settings.sourceControlGroupOrder),
sourceControlCompareAgainstUpstream: settings.sourceControlCompareAgainstUpstream === true,
diffShowWhitespace: settings.diffShowWhitespace === true,
// Omitted without a service: clients treat absence as "ask the host", which names the real cause.
...(this.sharingServices?.artifacts() === false
? {}
: { artifactSharingEnabled: isArtifactSharingEnabled(settings) }),
worktreeVisibilityDefaults: settings.worktreeVisibilityDefaults ?? { external: 'hide' },
...(this.sharingServices?.skills() === false
? {}
: { agentSkillSharingEnabled: isAgentSkillSharingEnabled(settings) }),
machineName: settings.machineName ?? '',
nativeChatPermissionMode: publishedLegacyChatPermissionMode(settings),
// Phone sends queue mid-turn only while this is on; absence from older hosts means on.
nativeChatQueueFollowUps: settings.nativeChatQueueFollowUps !== false,
// Why projected: a paired client's AI buttons start these actions' agents, and must honour
// the agent saved for each one as the desktop does. Absent on older hosts.
sourceControlAi: projectSourceControlLaunchRecipes(settings),
hostSettingOverrides: Object.fromEntries(
[
...getHostDisplayLabelOverrides({ hostSettingOverrides: settings.hostSettingOverrides })
].map(([hostId, displayLabel]) => [hostId, { displayLabel }])
) as RuntimeHostDisplayLabelOverrides
}
}
async update(updates: RuntimeClientSettingsUpdate): Promise<RuntimeClientSettings> {
if (!this.store?.getSettings || !this.store.updateSettings) {
throw new Error('runtime_unavailable')
}
const beforeSettings = this.store.getSettings()
const before = beforeSettings.agentStatusHooksEnabled !== false
// Legacy clients can select an agent or a shell, but cannot select None.
this.store.updateSettings(
{
...updates,
// An older client writes Arguments as it reads them, flag included.
...(updates.agentDefaultArgs !== undefined || updates.agentDefaultEnv !== undefined
? legacyLaunchTextUpdates(
beforeSettings,
{
agentDefaultArgs: updates.agentDefaultArgs,
agentDefaultEnv: updates.agentDefaultEnv
},
process.platform
)
: {}),
...(updates.defaultTuiAgent !== undefined ? { newWorkspaceSetupOnly: false } : {})
},
{ notifyListeners: true }
)
const settings = this.store.getSettings()
await getClaudeAgentViewService().reconcile(settings)
if (updates.worktreeVisibilityDefaults !== undefined) {
this.notifyReposChanged?.()
}
if (
(typeof updates.agentStatusHooksEnabled === 'boolean' &&
before !== updates.agentStatusHooksEnabled) ||
(updates.disabledTuiAgents !== undefined &&
!haveSameDisabledTuiAgents(beforeSettings.disabledTuiAgents, settings.disabledTuiAgents))
) {
await this.reconcileManagedAgentHooks()
}
return this.get()
}
getTerminalQuickCommands(): TerminalQuickCommand[] {
if (!this.store?.getSettings) {
throw new Error('runtime_unavailable')
}
return this.store.getSettings().terminalQuickCommands ?? []
}
getAgentLaunch(): AgentLaunchSettings {
if (!this.store?.getSettings) {
throw new Error('runtime_unavailable')
}
return projectAgentLaunchSettings(this.store.getSettings(), process.platform)
}
async mutateAgentLaunch(mutation: AgentLaunchSettingsMutation): Promise<AgentLaunchSettings> {
const store = this.store
if (!store?.getSettings || !store.updateSettings || !store.runDurableMutation) {
throw new Error('runtime_unavailable')
}
const applySettings = store.updateSettings.bind(store)
const committed = await store.runDurableMutation(() => {
const before = store.getSettings()
const updates = agentLaunchSettingsMutationUpdates(before, mutation, process.platform)
applySettings(updates, { notifyListeners: true })
const applied = store.getSettings()
return {
value: {
settings: projectAgentLaunchSettings(applied, process.platform),
reconcileHooks:
updates.disabledTuiAgents !== undefined &&
!haveSameDisabledTuiAgents(before.disabledTuiAgents, applied.disabledTuiAgents)
},
rollback: () => {
const rollback = agentLaunchSettingsRollbackUpdates(
before,
applied,
store.getSettings(),
updates
)
if (Object.keys(rollback).length > 0) {
applySettings(rollback, { notifyListeners: true })
}
}
}
})
if (committed.reconcileHooks) {
void this.reconcileManagedAgentHooks().catch((error) => {
console.error(
'[agent-hooks] Failed to reconcile managed hooks after saving launch settings:',
error
)
})
}
return committed.settings
}
updateTerminalQuickCommands(mutation: TerminalQuickCommandMutation): TerminalQuickCommand[] {
if (!this.store?.getSettings || !this.store.updateSettings) {
throw new Error('runtime_unavailable')
}
const current = this.getTerminalQuickCommands()
const next = applyTerminalQuickCommandMutation(current, mutation)
this.store.updateSettings({ terminalQuickCommands: next }, { notifyListeners: true })
return this.getTerminalQuickCommands()
}
updatePRBotAuthorOverride(args: { author: string; isBot: boolean }): RuntimeClientSettings {
if (!this.store?.getSettings || !this.store.updateSettings) {
throw new Error('runtime_unavailable')
}
const current = this.store.getSettings().prBotAuthorOverrides
this.store.updateSettings(
{ prBotAuthorOverrides: applyPRBotAuthorOverride(current, args.author, args.isBot) },
{ notifyListeners: true }
)
return this.get()
}
updateNativeChatSessionOptions(mutation: NativeChatSessionOptionSettingsMutation): void {
if (!this.store?.getSettings || !this.store.updateSettings) {
throw new Error('runtime_unavailable')
}
const next = applyNativeChatSessionOptionSettingsMutation(
this.store.getSettings().nativeChatSessionOptions,
mutation
)
if (next) {
this.store.updateSettings({ nativeChatSessionOptions: next }, { notifyListeners: true })
}
}
private reconcileManagedAgentHooks(): Promise<void> {
const generation = ++this.reconciliationGeneration
const reconciliation = this.reconciliationTail.then(async () => {
if (generation !== this.reconciliationGeneration) {
return
}
const settings = this.store?.getSettings()
if (!settings) {
return
}
await applyAgentStatusHooksEnabled(settings.agentStatusHooksEnabled !== false, settings, {
// R42, COMPAT(wsl-bridge): the bridge's panes in this distro share these entries; drop at D4.
keepSharedEntries: isWslHostOrcadProcess(),
shouldHydrateShellPath: getAppEnvironment().isPackaged(),
onInstallError: recordManagedHookInstallFailure,
shouldContinue: (agent) => {
const current = this.store?.getSettings()
return current !== undefined && isAgentStatusHooksEnabledForAgent(current, agent)
}
})
})
this.reconciliationTail = reconciliation.catch(() => {})
return reconciliation
}
}
function projectSourceControlLaunchRecipes(
settings: Partial<Pick<GlobalSettings, 'sourceControlAi' | 'commitMessageAi'>>
): RuntimeClientSourceControlAi {
const { actions } = normalizeSourceControlAiSettings(
settings.sourceControlAi,
settings.commitMessageAi
)
return {
actions: Object.fromEntries(
SOURCE_CONTROL_LAUNCH_ACTION_IDS.flatMap((actionId) => {
const recipe = actions?.[actionId]
return recipe ? [[actionId, recipe]] : []
})
)
}
}