Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions src/main/opencode/hook-service-atomic-write.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import {
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type * as NodeFs from 'node:fs'
import { setAppEnvironment } from '../../shared/app-environment'

const { directWrites } = vi.hoisted(() => {
const writes: string[] = []
return { directWrites: writes }
})

vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof NodeFs>()
return {
...actual,
writeFileSync: (...args: Parameters<typeof actual.writeFileSync>) => {
directWrites.push(String(args[0]))
return actual.writeFileSync(...args)
}
}
})

import { OpenCodeHookService, _internals } from './hook-service'
import { resolveOpenCodeConfigDirectory } from '../../shared/opencode-config-directory'

// Why: OpenCode 2 reloads a plugin on mtime change; a reload must never see it truncated mid-write.
describe('OpenCodeHookService canonical plugin write', () => {
const ptyId = 'c0ffee00-0000-4000-8000-000000000000'
const originalXdgConfigHome = process.env.XDG_CONFIG_HOME
let userDataDir: string
let pluginPath: string

beforeAll(() => {
userDataDir = mkdtempSync(join(tmpdir(), 'orca-opencode-atomic-'))
process.env.XDG_CONFIG_HOME = userDataDir
setAppEnvironment({
getPath: () => userDataDir,
getAppPath: () => process.cwd(),
getVersion: () => '0.0.0-test',
isPackaged: () => false,
onWillQuit: () => {},
exit: () => {},
getAppMetrics: () => []
})
})

afterAll(() => {
if (originalXdgConfigHome === undefined) {
delete process.env.XDG_CONFIG_HOME
} else {
process.env.XDG_CONFIG_HOME = originalXdgConfigHome
}
rmSync(userDataDir, { recursive: true, force: true })
})

beforeEach(() => {
const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins')
rmSync(pluginsDir, { recursive: true, force: true })
mkdirSync(pluginsDir, { recursive: true })
pluginPath = join(pluginsDir, 'orca-opencode-status.js')
directWrites.length = 0
})

it('replaces a stale plugin without writing to its path in place', () => {
writeFileSync(pluginPath, 'stale plugin')
directWrites.length = 0

new OpenCodeHookService().buildPtyEnv(ptyId)

expect(readFileSync(pluginPath, 'utf8')).toBe(_internals.getOpenCodePluginSource())
expect(directWrites).not.toContain(pluginPath)
expect(readdirSync(join(pluginPath, '..'))).toEqual(['orca-opencode-status.js'])
})

it.skipIf(process.platform === 'win32')(
'keeps a symlinked plugin linked and replaces its target atomically',
() => {
const targetPath = join(userDataDir, 'dotfiles-orca-opencode-status.js')
writeFileSync(targetPath, 'stale plugin')
symlinkSync(targetPath, pluginPath)
directWrites.length = 0

new OpenCodeHookService().buildPtyEnv(ptyId)

expect(lstatSync(pluginPath).isSymbolicLink()).toBe(true)
expect(readFileSync(targetPath, 'utf8')).toBe(_internals.getOpenCodePluginSource())
expect(directWrites).not.toContain(pluginPath)
expect(directWrites).not.toContain(realpathSync(targetPath))
rmSync(targetPath, { force: true })
}
)
})
13 changes: 4 additions & 9 deletions src/main/opencode/hook-service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import { getAppEnvironment } from '../../shared/app-environment'
import { writeOpenCodePluginFile } from '../../shared/opencode-plugin-file-write'
import { join } from 'node:path'
import {
existsSync,
Expand All @@ -8,7 +9,6 @@ import {
readdirSync,
realpathSync,
statSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { createHash } from 'node:crypto'
Expand Down Expand Up @@ -277,19 +277,14 @@ export class OpenCodeHookService {
this.writeOverlayManifest(overlayDir, nextManifest)
}

// Why: pre-write unlink guards against POSIX writeFileSync writing through a mirrored symlink and clobbering a same-named user plugin.
// Why: 'replace-link' renames over a mirrored symlink rather than writing through it, so a same-named user plugin is never clobbered.
private writePluginIntoOverlay(overlayDir: string): void {
const pluginsDir = join(overlayDir, 'plugins')
mkdirSync(pluginsDir, { recursive: true })
const pluginPath = join(pluginsDir, this.pluginFileName)
const source = this.pluginSource()
if (!isOverlayOpenCodePluginCurrent(pluginPath, source)) {
try {
unlinkSync(pluginPath)
} catch {
// File may not exist on a fresh overlay; a real failure surfaces on writeFileSync below.
}
writeFileSync(pluginPath, source)
writeOpenCodePluginFile(pluginPath, source, 'replace-link')
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}
}

Expand All @@ -299,7 +294,7 @@ export class OpenCodeHookService {
const pluginPath = join(pluginsDir, this.pluginFileName)
const source = this.pluginSource()
if (!isInstalledOpenCodePluginCurrent(pluginPath, source)) {
writeFileSync(pluginPath, source)
writeOpenCodePluginFile(pluginPath, source, 'write-through-link')
}
}
}
Expand Down
96 changes: 96 additions & 0 deletions src/main/ssh/ssh-relay-session-managed-hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,100 @@ describe('SshRelaySession managed hooks', () => {
session.dispose()
expect(cleanup).toHaveBeenCalledOnce()
})

// Why: a timed-out install left the relay on the old sources (a disabled agent kept its plugin) until the next reconnect.
it('retries a settings-triggered plugin install that failed, using the latest settings', async () => {
muxRequestMock.mockResolvedValue({ agents: [] })
const { mockStore, mockConn, mockPortForward, getMainWindow } = createMockDeps()
const settings = getDefaultSettings('/synthetic-home')
mockStore.getSettings = () => settings
let listener: Parameters<Store['onSettingsChanged']>[0] | undefined
mockStore.onSettingsChanged = (callback) => {
listener = callback
return vi.fn()
}
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const session = new SshRelaySession(
'target-settings',
getMainWindow,
mockStore,
mockPortForward
)
await session.establish(mockConn)
const installCalls = () =>
muxRequestMock.mock.calls.filter(([method]) => method === AGENT_HOOK_INSTALL_PLUGINS_METHOD)

vi.useFakeTimers()
try {
const before = installCalls().length
muxRequestMock.mockImplementationOnce(async (method: string) => {
if (method !== AGENT_HOOK_INSTALL_PLUGINS_METHOD) {
return { agents: [] }
}
throw Object.assign(new Error('timed out'), { code: 'SSH_MUX_REQUEST_TIMEOUT' })
})
settings.disabledTuiAgents = ['opencode2']
listener?.({ disabledTuiAgents: settings.disabledTuiAgents }, settings)
await vi.advanceTimersByTimeAsync(60_000)

const calls = installCalls().slice(before)
expect(calls.length).toBeGreaterThan(1)
expect(calls.at(-1)?.[1]).toMatchObject({ opencode2PluginSource: '' })
} finally {
vi.useRealTimers()
warn.mockRestore()
session.dispose()
}
})

// Why: two overlapping failed installs must leave one retry chain, not two the next install can't cancel.
it('retries once when overlapping settings-triggered installs both fail', async () => {
muxRequestMock.mockResolvedValue({ agents: [] })
const { mockStore, mockConn, mockPortForward, getMainWindow } = createMockDeps()
const settings = getDefaultSettings('/synthetic-home')
mockStore.getSettings = () => settings
let listener: Parameters<Store['onSettingsChanged']>[0] | undefined
mockStore.onSettingsChanged = (callback) => {
listener = callback
return vi.fn()
}
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const session = new SshRelaySession(
'target-settings',
getMainWindow,
mockStore,
mockPortForward
)
await session.establish(mockConn)
const installCalls = () =>
muxRequestMock.mock.calls.filter(([method]) => method === AGENT_HOOK_INSTALL_PLUGINS_METHOD)

vi.useFakeTimers()
try {
const before = installCalls().length
const pendingInstalls: ((error: Error) => void)[] = []
muxRequestMock.mockImplementation((method: string) => {
if (method === AGENT_HOOK_INSTALL_PLUGINS_METHOD && pendingInstalls.length < 2) {
return new Promise((_resolve, reject) => pendingInstalls.push(reject))
}
return Promise.resolve({ agents: [] })
})
settings.disabledTuiAgents = ['opencode2']
listener?.({ disabledTuiAgents: settings.disabledTuiAgents }, settings)
settings.disabledTuiAgents = ['opencode']
listener?.({ disabledTuiAgents: settings.disabledTuiAgents }, settings)
expect(pendingInstalls).toHaveLength(2)

for (const reject of pendingInstalls) {
reject(Object.assign(new Error('timed out'), { code: 'SSH_MUX_REQUEST_TIMEOUT' }))
}
await vi.advanceTimersByTimeAsync(60_000)

expect(installCalls().slice(before)).toHaveLength(3)
} finally {
vi.useRealTimers()
warn.mockRestore()
session.dispose()
}
})
})
43 changes: 42 additions & 1 deletion src/main/ssh/ssh-relay-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ const SSH_REJECTED_PTY_RECOVERY_MAX_ATTEMPTS = 2
// store read, an attach round trip and a store write.
const SSH_REJECTED_PTY_RECOVERY_MAX_GENERATION_ATTEMPTS = 12
const SSH_REJECTED_PTY_RECOVERY_RETRY_DELAY_MS = 150
const SSH_PLUGIN_INSTALL_RETRY_DELAY_MS = 5_000
const SSH_PLUGIN_INSTALL_MAX_RETRIES = 3
const SSH_SOURCE_RECOVERY_CANCELLATION_FAILED = 'ssh_source_recovery_cancellation_failed'

// Why: superseded attempts stop quietly; a dead mux still owned by this attempt must enter recovery.
Expand Down Expand Up @@ -321,6 +323,8 @@ export class SshRelaySession {
// Why: hold the notification-handler disposer so teardownProviders can release it on reconnect/shutdown (symmetric with muxDisposeCleanup).
private muxNotificationCleanup: (() => void) | null = null
private pluginSettingsCleanup: (() => void) | null = null
private pluginInstallRetryTimer: ReturnType<typeof setTimeout> | null = null
private pluginInstallGeneration = 0
// Why: onStateChange never fires when the relay channel closes but SSH stays up; this callback lets ssh.ts drive relay-level reconnect.
private _onRelayLost: ((targetId: string) => void) | null = null
// Why: a version mismatch or a blocked owner admission is terminal, so it needs a separate callback
Expand Down Expand Up @@ -1548,10 +1552,15 @@ export class SshRelaySession {
}

// Why: ship plugin/extension source from Orca so agent-event changes don't force a relay redeploy — the relay is versioned independently. Best-effort: failure only costs agent status on this host.
private async installPluginsOnRelay(mux: SshChannelMultiplexer): Promise<void> {
private async installPluginsOnRelay(
mux: SshChannelMultiplexer,
attempt = 0,
generation = ++this.pluginInstallGeneration
): Promise<void> {
if (!isRemoteAgentHooksEnabled()) {
return
}
this.clearPluginInstallRetry()
try {
const hooksEnabled = this.areAgentStatusHooksEnabled()
await mux.request(
Expand Down Expand Up @@ -1585,6 +1594,37 @@ export class SshRelaySession {
err instanceof Error ? err.message : String(err)
}`
)
this.schedulePluginInstallRetry(mux, attempt, generation)
}
}

// Why: without a retry a timed-out install leaves the relay on stale sources until the next reconnect; each retry re-reads current settings.
// A superseded install (older generation) must not start a retry chain the newer one can't cancel.
private schedulePluginInstallRetry(
mux: SshChannelMultiplexer,
attempt: number,
generation: number
): void {
if (
attempt >= SSH_PLUGIN_INSTALL_MAX_RETRIES ||
this.mux !== mux ||
generation !== this.pluginInstallGeneration
) {
return
}
this.pluginInstallRetryTimer = setTimeout(() => {
this.pluginInstallRetryTimer = null
if (this.mux === mux && !mux.isDisposed()) {
Comment on lines +1615 to +1617

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Overlapping retries lose cancellation

Two settings changes can start installs on the same connection before either request finishes. If both fail, the second retry timer overwrites the first timer’s handle; a callback can also clear the handle for another pending timer. A newer install or session teardown can no longer cancel every retry, so unnecessary install requests may still run after a later attempt succeeds.

Knowledge Base Used: Remote connectivity and execution

void this.installPluginsOnRelay(mux, attempt + 1, generation)
}
}, SSH_PLUGIN_INSTALL_RETRY_DELAY_MS)
this.pluginInstallRetryTimer.unref?.()
}

private clearPluginInstallRetry(): void {
if (this.pluginInstallRetryTimer) {
clearTimeout(this.pluginInstallRetryTimer)
this.pluginInstallRetryTimer = null
}
}

Expand Down Expand Up @@ -1698,6 +1738,7 @@ export class SshRelaySession {
this.releaseRelayLossWatcher()
this.pluginSettingsCleanup?.()
this.pluginSettingsCleanup = null
this.clearPluginInstallRetry()
this.muxNotificationCleanup?.()
this.muxNotificationCleanup = null
for (const cleanup of this.ptyRecoveryNotificationCleanups) {
Expand Down
10 changes: 3 additions & 7 deletions src/relay/opencode-canonical-config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { mkdirSync, unlinkSync, writeFileSync } from 'node:fs'
import { mkdirSync } from 'node:fs'
import { isAbsolute, join, relative, resolve } from 'node:path'
import { resolveOpenCodeConfigDirectory } from '../shared/opencode-config-directory'
import { isInstalledOpenCodePluginCurrent } from '../shared/opencode-installed-plugin'
import { writeOpenCodePluginFile } from '../shared/opencode-plugin-file-write'

const RELAY_HOOKS_DIR = '.orca-relay'

Expand All @@ -20,12 +21,7 @@ export function installOpenCodePluginInCanonicalConfig(
const pluginPath = join(configDir, 'plugins', pluginFileName)
mkdirSync(join(configDir, 'plugins'), { recursive: true })
if (!isInstalledOpenCodePluginCurrent(pluginPath, source)) {
try {
unlinkSync(pluginPath)
} catch {
// The file may not exist on the first install.
}
writeFileSync(pluginPath, source)
writeOpenCodePluginFile(pluginPath, source, 'replace-link')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use write-through-link for the relay canonical path.

If the canonical plugin is a symlink to stale content, replace-link renames the temporary file over the symlink rather than its target. On Linux, rename replaces a destination symlink itself. (man7.org)

The canonical path becomes a regular file, and the dotfile-manager target remains stale. Use the same canonical policy as the app. Add a relay test that checks both link preservation and target replacement.

Proposed fix
-      writeOpenCodePluginFile(pluginPath, source, 'replace-link')
+      writeOpenCodePluginFile(pluginPath, source, 'write-through-link')

The supplied PR objective requires preserving canonical-path symlinks.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
writeOpenCodePluginFile(pluginPath, source, 'replace-link')
writeOpenCodePluginFile(pluginPath, source, 'write-through-link')

Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}
return true
} catch (err) {
Expand Down
Loading
Loading