mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
* [comment audit] Align legacy failure-read counts with cached display * [comment audit] Condense shared provider lifecycle and browser recovery comments [skip ci] * [comment audit] Condense shared generation, path and preview comments [skip ci] * [comment audit] Condense host, file and Git contract rationale [skip ci] * [comment audit] Tighten Git lifecycle and provider contract comments [skip ci] * [comment audit] Clarify shared host authority and launch isolation [skip ci] * [comment audit] simplify local access mobile and native chat contracts [skip ci] * [comment audit] simplify native chat presentation and state contracts [skip ci] * [comment audit] simplify native runtime and provider contracts [skip ci] * [comment audit] simplify migration and orchestration contracts [skip ci] * [comment audit] simplify plugin trust and process capture rationale [skip ci] * [comment audit] simplify terminal delivery and remote compatibility rationale [skip ci] * [comment audit] clarify remote recovery and launch wire rationale [skip ci] * [comment audit] shorten shared RPC compatibility and runtime evidence comments [skip ci] * [comment audit] simplify secure storage shell startup and sidebar rationale [skip ci] * [comment audit] clarify sidebar, skill and SSH invariants [skip ci] * [comment audit] condense structured chat delivery and timing rationale [skip ci] * [comment audit] condense terminal replay and telemetry invariants [skip ci] * [comment audit] clarify launch permission and terminal delivery rationale [skip ci] * [comment audit] clarify workspace ownership and layout contracts [skip ci] * [comment audit] wait for fitted and painted SSH terminal links * [comment audit] clarify layout persistence and session ownership [skip ci] * [comment audit] clarify host routing and workspace lifecycle contracts [skip ci] * [comment audit] clarify startup persistence and app lifetime comments [skip ci] * [comment audit] clarify recovery and activity boundaries [skip ci] * [comment audit] condense activity and artifact invariants [skip ci] * [comment audit] condense automation authority contracts [skip ci] * [comment audit] simplify automation scheduling and history contracts [skip ci] * [comment audit] clarify browser chrome and annotation lifecycles [skip ci] * [comment audit] clarify browser routing and retained guest ownership [skip ci] * [comment audit] clarify browser recovery and document ownership comments [skip ci] * [comment audit] restore hosted runners required by native IME fixtures * [comment audit] shorten preview, palette and dashboard invariants [skip ci] * [comment audit] clarify terminal preview, dashboard and retention comments [skip ci] * [comment audit] clarify diff-note recovery and editor lifecycle comments [skip ci] * [comment audit] shorten rich-text and combined-diff ownership comments [skip ci] * [comment audit] shorten autosave, draft recovery and model ownership comments [skip ci] * [comment audit] shorten save-queue, notebook and Markdown constraints [skip ci] * [comment audit] shorten Monaco, PDF and rich Markdown safeguards [skip ci] * [comment audit] clarify rich Markdown source and selection safeguards [skip ci] * [comment audit] clarify editor loading and emulator stream lifetimes [skip ci] * [comment audit] trim emulator and feature tour narration [skip ci] * [comment audit] clarify floating workspace and GitHub cache ownership [skip ci] * [comment audit] trim provider controls and Linear filter explanations [skip ci] * [comment audit] clarify pairing and chat resume lifetimes [skip ci] * [comment audit] clarify chat delivery and transcript lifetimes [skip ci] * [comment audit] clarify session options and host-owned status [skip ci] * [comment audit] clarify draft durability and live-status precedence [skip ci] * [comment audit] Trim chat send and model ownership explanations [skip ci] * [comment audit] Shorten transcript ownership and send recovery comments [skip ci] * [comment audit] Simplify native chat composer and transcript hook comments [skip ci] * [comment audit] Shorten native chat scroll and structured session explanations [skip ci] * [comment audit] Trim workspace picker and onboarding commentary [skip ci] * [comment audit] Simplify pet rendering, review cache and quick open comments [skip ci] * [comment audit] Trim sidebar and session history explanations [skip ci] * [comment audit] Condense session resume and review checks comments [skip ci] * [comment audit] Shorten checks state and file explorer refresh comments [skip ci] * [comment audit] Trim plugin bridge and source-control action rationale [skip ci] * [comment audit] Trim source-control listing and review rationale [skip ci] * [comment audit] Shorten sidebar lifecycle and explorer safeguards [skip ci] * [comment audit] Condense Settings account and appearance rationale [skip ci] * [comment audit] Trim pairing and repository Settings explanations [skip ci] * [comment audit] Condense Settings search SSH and terminal safeguards [skip ci] * [comment audit] Shorten Settings voice and provider ownership comments [skip ci] * [comment audit] Condense Settings draft persistence and host-state rationale [skip ci] * [comment audit] Trim Settings hooks and sidebar setup rationale [skip ci] * [comment audit] Condense sidebar deletion and board-filter safeguards [skip ci] * [comment audit] Condense worktree cards, host ownership and Markdown contracts [skip ci] * [comment audit] Condense sidebar drag, folder and filtering contracts [skip ci] * [comment audit] Condense sidebar parity, sleep and host ownership contracts [skip ci] * [comment audit] Prune focus-read baseline after comment cleanup * [comment audit] Clarify sidebar visibility, board drops and agent evidence [skip ci] * [comment audit] Tighten sidebar listing, drag and reveal contracts [skip ci] * [comment audit] Clarify viewport geometry and skill update safeguards [skip ci] * [comment audit] Tighten skill inventory, usage and host status comments [skip ci] * [comment audit] Clarify usage ownership and resource kill safeguards [skip ci] * [comment audit] Tighten tab selection, rename and search contracts [skip ci] * [comment audit] Tighten tab-strip geometry and drag ownership comments [skip ci] * [comment audit] Tighten Tasks recovery, pagination and mutation comments [skip ci] * [comment audit] Tighten provider loading and terminal recovery comments [skip ci] * [comment audit] Tighten completion, cadence and PTY ownership comments [skip ci] * [comment audit] Clarify terminal restore and parked-pane boundaries [skip ci] * [comment audit] Tighten PTY startup and replay explanations [skip ci] * [comment audit] Clarify PTY identity and delivery ownership [skip ci] * [comment audit] Shorten remote reconnect and input replay rationale [skip ci] * [comment audit] Condense terminal parking clipboard and file link comments [skip ci] * [comment audit] Clarify IME ownership and trim trace history [skip ci] * [comment audit] Shorten pane recovery and parked watcher explanations [skip ci] * [comment audit] Condense snapshot replay and visibility recovery rationale [skip ci] * [comment audit] Shorten terminal parking and keyboard ownership rationale [skip ci] * [comment audit] Trim renderer lifecycle and menu rationale [skip ci] * [comment audit] Condense workspace cleanup ownership and settlement notes [skip ci] * [comment audit] Clarify renderer hook evidence and source ownership [skip ci] * [comment audit] Tighten IPC ownership and reconnect explanations [skip ci] * [comment audit] Trim renderer focus, paste and attention comments [skip ci] * [comment audit] Shorten scroll, locale and agent lifecycle comments [skip ci] * [comment audit] Trim agent launch, resume and ownership commentary [skip ci] * [comment audit] Shorten account, browser and editor comments [skip ci] * [comment audit] Clarify host-mirror waits, previews and input ownership [skip ci] * [comment audit] Condense launch recovery and editor tokenization comments [skip ci] * [comment audit] Condense workspace selection and terminal pane rationale [skip ci] * [comment audit] Condense terminal fitting and rendering recovery comments [skip ci] * [comment audit] Condense terminal input and host routing explanations [skip ci] * [comment audit] Condense ownership and sleeping-session recovery rationale [skip ci] * [comment audit] Condense structured launch and terminal link explanations [skip ci] * [comment audit] Condense terminal ownership and workspace file routing rationale [skip ci] * [comment audit] Condense session persistence and workspace activation rationale [skip ci] * [comment audit] Condense workspace routing and browser ownership rationale [skip ci] * [comment audit] Condense mirror recovery and layout authority rationale [skip ci] * [comment audit] Condense runtime transport and file safety rationale [skip ci] * [comment audit] Condense runtime graph and structured session rationale [skip ci] * [comment audit] Condense browser creation and remote tab recovery rationale [skip ci] * [comment audit] Condense snapshot authority and publisher recovery rationale [skip ci] * [comment audit] Condense frame, startup and provider cache rationale [skip ci] * [comment audit] Condense host twin and agent lifecycle rationale [skip ci] * [comment audit] Condense browser authority and editor cleanup rationale [skip ci] * [comment audit] Condense editor buffer identity and review cache rationale [skip ci] * [comment audit] Condense provider lifetime and repository ownership rationale [skip ci] * [comment audit] Condense reconnect, hydration and terminal retirement rationale [skip ci] * [comment audit] Condense recovery, reconciliation and persistence rationale [skip ci] * [comment audit] Condense cleanup ownership and listing admission rationale [skip ci] * [comment audit] Condense teardown ordering and terminal ownership rationale [skip ci] * [comment audit] Condense recovery ledger and web host-boundary rationale [skip ci] * [comment audit] Condense web reconnect and credential lifecycle rationale [skip ci] * [comment audit] Condense cloud rollout and assignment safety rationale [skip ci] * [comment audit] Condense relay session and database recovery rationale [skip ci] * [comment audit] Condense relay placement and protocol compatibility rationale [skip ci] * [comment audit] Condense build and packaging constraints [skip ci] * [comment audit] Condense CI gates and validation isolation rationale [skip ci] * [comment audit] Condense catalog identity and browser validation rationale [skip ci] * [comment audit] Condense mobile browser and frame-budget rationale [skip ci] * [comment audit] Shorten mobile route and browser test explanations [skip ci] * [comment audit] Condense editor and session seam test rationale [skip ci] * [comment audit] Trim session and terminal closure history [skip ci] * [comment audit] Shorten terminal browser and census explanations [skip ci] * [comment audit] Preserve root-only E2E diagnostic baseline * [comment audit] Condense mobile seam and HTML preview test rationale [skip ci] * [comment audit] Condense preview instrumentation and render harness rationale [skip ci] * [comment audit] Condense bundle contracts and native-build constraints [skip ci] * [comment audit] Shorten native packaging and CI routing rationale [skip ci] * [comment audit] Condense release tooling and benchmark constraints [skip ci] * [comment audit] Condense packaging and platform gate rationale [skip ci] * [comment audit] Shorten mobile route and history rationale [skip ci] * [comment audit] Condense mobile browser and component rationale [skip ci] * [comment audit] Shorten drawer and workspace-form rationale [skip ci] * [comment audit] Trim mobile review and editor-document explanations [skip ci] * [comment audit] Condense editor lifecycle and Markdown explanations [skip ci] * [comment audit] Trim mobile file, diagnostics and dictation commentary [skip ci] * [comment audit] Simplify mobile host-list and workspace-view explanations [skip ci] * [comment audit] Clarify mobile shell lifetime and bridge delivery constraints [skip ci] * [comment audit] Condense bridge stream, native request and audio rationale [skip ci] * [comment audit] Reduce bridge schema and page-client commentary [skip ci] * [comment audit] Tighten mobile page bridge contracts [skip ci] * [comment audit] Clarify mobile cache and session constraints [skip ci] * [comment audit] Condense mobile route and lifecycle rationale [skip ci] * [comment audit] Tighten mobile shell hook timing rationale [skip ci] * [comment audit] Clarify route handoff and notification compatibility [skip ci] * [comment audit] Clarify push registration and dictation cleanup constraints [skip ci] * [comment audit] Condense keyboard geometry and native media ownership rationale [skip ci] * [comment audit] Tighten mobile chat scroll and composer concurrency rationale [skip ci] * [comment audit] Condense mobile reply compatibility and upload ownership rationale [skip ci] * [comment audit] Condense optimistic echo and scroll ownership rationale [skip ci] * [comment audit] Tighten stream replay and queued session ownership rationale [skip ci] * [comment audit] Condense mobile composer and reply-schema constraints [skip ci] * [comment audit] Clarify mobile transcript recovery and session ownership [skip ci] * [comment audit] Clarify mobile queue and source-control compatibility [skip ci] * [comment audit] Condense storage and task launch constraints [skip ci] * [comment audit] Clarify task schemas and terminal document ownership [skip ci] * [comment audit] Tighten terminal input and viewport rationale [skip ci] * [comment audit] Shorten terminal and RPC recorder contracts [skip ci] * [comment audit] Condense recorder engine and connection contracts [skip ci] * [comment audit] Shorten host credential and relay recovery comments [skip ci] * [comment audit] Tighten pairing recovery and bundle transport rationale [skip ci] * [comment audit] Clarify RPC delivery and workspace catalog boundaries [skip ci] * [comment audit] Condense catalog and relay entry contracts [skip ci] * [comment audit] Shorten shutdown and SSH relay delivery contracts [skip ci] * [comment audit] Condense WSL relay and E2E regression rationale [skip ci] * [comment audit] Shorten cross-version harness and renderer fixture explanations [skip ci] * [comment audit] Condense paired-host and E2E lifecycle rationale [skip ci] * [comment audit] Shorten layout oracle and regression explanations [skip ci] * [comment audit] Condense paired recovery and ownership regression contracts [skip ci] * [comment audit] Shorten restart, sidebar and SSH lifecycle contracts [skip ci] * [comment audit] Condense terminal rendering and IME regression rationale [skip ci] * [comment audit] Shorten terminal recovery and benchmark contracts [skip ci] * [comment audit] Condense tooling and Windows lifecycle proof rationale [skip ci] * [comment audit] Condense workflow routing and release rationale [skip ci] * [comment audit] Condense mobile security and installer contracts [skip ci] * [comment audit] Shorten native rationale and stylesheet workarounds [skip ci] * [comment audit] Shorten Windows visibility probe rationale [skip ci] * [comment audit] Condense embedded release and signing rationale [skip ci] * [comment audit] Retain current main test behavior in final reconciliation [skip ci] * [comment audit] Complete final comment review across current source inventory * [comment audit] Handle consolidated audit reports before final CI * [comment audit] Preserve credential storage census detail [skip ci] * [comment audit] Scale broad changed E2E selections with verified timing shards * [comment audit] Align E2E assertions with browser close and settled session metadata * [comment audit] Match existing E2Es to current resource and windowing contracts * [comment audit] Observe the shared server outage notice in reconnect coverage * [comment audit] Make existing renderer probes measure settled tab and PTY work * [comment audit] Align palette E2E selector with task search * [comment audit] Refresh remaining palette search selectors * [comment audit] Keep selector correction within selected audit specs * [comment audit] Await emoji fixture settings inside renderer evaluation * [comment audit] Cancel fixture fit retries between terminal tests --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
639 lines
25 KiB
TypeScript
639 lines
25 KiB
TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||
import {
|
||
existsSync,
|
||
openSync,
|
||
closeSync,
|
||
lstatSync,
|
||
mkdirSync,
|
||
mkdtempSync,
|
||
readFileSync,
|
||
readdirSync,
|
||
rmSync,
|
||
statSync,
|
||
symlinkSync,
|
||
utimesSync,
|
||
writeFileSync
|
||
} from 'node:fs'
|
||
import { tmpdir } from 'node:os'
|
||
import { join } from 'node:path'
|
||
import { pathToFileURL } from 'node:url'
|
||
import { setAppEnvironment } from '../../shared/app-environment'
|
||
|
||
const { getPathMock } = vi.hoisted(() => ({
|
||
getPathMock: vi.fn<(name: string) => string>()
|
||
}))
|
||
|
||
import {
|
||
OpenCodeHookService,
|
||
openCode2HookService,
|
||
_internals,
|
||
getOpenCodePluginSource
|
||
} from './hook-service'
|
||
import { resolveOpenCodeConfigDirectory } from '../../shared/opencode-config-directory'
|
||
|
||
beforeEach(() => {
|
||
vi.stubEnv('ORCA_OPENCODE_PLUGIN_API', 'v2')
|
||
setAppEnvironment({
|
||
getPath: getPathMock,
|
||
getAppPath: () => process.cwd(),
|
||
getVersion: () => '0.0.0-test',
|
||
isPackaged: () => false,
|
||
onWillQuit: () => {},
|
||
exit: () => {},
|
||
getAppMetrics: () => []
|
||
})
|
||
})
|
||
|
||
afterEach(() => vi.unstubAllEnvs())
|
||
|
||
const { isUsableId, toSafeDirName } = _internals
|
||
|
||
describe('OpenCode id safety guard', () => {
|
||
it('accepts the daemon-path sessionId shape (worktreeId@@uuid with ::/...)', () => {
|
||
const daemonSessionId =
|
||
'50c010a2-bc8e-4eb1-8847-5812133ad6df::/Users/thebr/ghostx/workspaces/noqa/autoheal@@a1b2c3d4'
|
||
expect(isUsableId(daemonSessionId)).toBe(true)
|
||
})
|
||
|
||
it('accepts ids at the inclusive upper length bound', () => {
|
||
expect(isUsableId('x'.repeat(1024))).toBe(true)
|
||
})
|
||
|
||
it('rejects empty or oversized ids', () => {
|
||
expect(isUsableId('')).toBe(false)
|
||
expect(isUsableId('x'.repeat(1025))).toBe(false)
|
||
})
|
||
|
||
it('rejects non-string runtime values even though the type says string', () => {
|
||
expect(isUsableId(undefined as unknown as string)).toBe(false)
|
||
expect(isUsableId(null as unknown as string)).toBe(false)
|
||
expect(isUsableId(42 as unknown as string)).toBe(false)
|
||
})
|
||
|
||
it('derives a filesystem-safe directory name independent of the raw id', () => {
|
||
const name = toSafeDirName('50c010::/Users/thebr/x/y@@uuid')
|
||
expect(name).toMatch(/^[0-9a-f]{32}$/)
|
||
})
|
||
|
||
it('is stable across calls for the same id', () => {
|
||
const id = 'some-session-id'
|
||
expect(toSafeDirName(id)).toBe(toSafeDirName(id))
|
||
})
|
||
|
||
it('produces different names for different ids', () => {
|
||
expect(toSafeDirName('a')).not.toBe(toSafeDirName('b'))
|
||
})
|
||
})
|
||
|
||
describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => {
|
||
const daemonSessionId =
|
||
'50c010a2-bc8e-4eb1-8847-5812133ad6df::/Users/thebr/ghostx/workspaces/noqa/autoheal@@a1b2c3d4'
|
||
const plainUuidId = 'c0ffee00-0000-4000-8000-000000000000'
|
||
let userDataDir: string
|
||
const originalXdgConfigHome = process.env.XDG_CONFIG_HOME
|
||
|
||
beforeAll(() => {
|
||
userDataDir = mkdtempSync(join(tmpdir(), 'orca-opencode-hooks-'))
|
||
process.env.XDG_CONFIG_HOME = userDataDir
|
||
getPathMock.mockImplementation((name: string) => {
|
||
if (name === 'userData') {
|
||
return userDataDir
|
||
}
|
||
throw new Error(`unexpected getPath(${name})`)
|
||
})
|
||
})
|
||
|
||
afterAll(() => {
|
||
if (originalXdgConfigHome === undefined) {
|
||
delete process.env.XDG_CONFIG_HOME
|
||
} else {
|
||
process.env.XDG_CONFIG_HOME = originalXdgConfigHome
|
||
}
|
||
rmSync(userDataDir, { recursive: true, force: true })
|
||
})
|
||
|
||
afterEach(() => {
|
||
rmSync(join(userDataDir, 'opencode-hooks'), { recursive: true, force: true })
|
||
rmSync(join(userDataDir, 'opencode-config-overlays'), { recursive: true, force: true })
|
||
})
|
||
|
||
it('installs the plugin without overriding OpenCode config discovery', () => {
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(daemonSessionId)
|
||
|
||
expect(env).toEqual({})
|
||
const pluginPath = join(resolveOpenCodeConfigDirectory(), 'plugins', 'orca-opencode-status.js')
|
||
expect(existsSync(pluginPath)).toBe(true)
|
||
const pluginSource = readFileSync(pluginPath, 'utf8')
|
||
expect(pluginSource).toContain('messageID: part.messageID')
|
||
const tuiEntry = join(
|
||
resolveOpenCodeConfigDirectory(),
|
||
'plugins',
|
||
'orca-opencode-status-tui',
|
||
'tui.js'
|
||
)
|
||
const past = new Date('2020-01-01T00:00:00Z')
|
||
utimesSync(tuiEntry, past, past)
|
||
service.buildPtyEnv(daemonSessionId)
|
||
expect(statSync(tuiEntry).mtimeMs).toBe(past.getTime())
|
||
})
|
||
|
||
// OpenCode 2 reloads on mtime changes, resetting status mid-turn.
|
||
it('leaves a current installed plugin untouched and replaces a stale one', () => {
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(daemonSessionId)
|
||
const pluginPath = join(resolveOpenCodeConfigDirectory(), 'plugins', 'orca-opencode-status.js')
|
||
const past = new Date('2020-01-01T00:00:00Z')
|
||
utimesSync(pluginPath, past, past)
|
||
|
||
service.buildPtyEnv(daemonSessionId)
|
||
expect(statSync(pluginPath).mtimeMs).toBe(past.getTime())
|
||
|
||
writeFileSync(pluginPath, 'stale plugin')
|
||
service.buildPtyEnv(daemonSessionId)
|
||
expect(readFileSync(pluginPath, 'utf8')).toBe(_internals.getOpenCodePluginSource())
|
||
})
|
||
|
||
// OpenCode 2 stats file-level symlink targets used by dotfile managers.
|
||
it.skipIf(process.platform === 'win32')(
|
||
'compares a symlinked plugin by its target and writes through only when stale',
|
||
() => {
|
||
const service = new OpenCodeHookService()
|
||
const pluginPath = join(
|
||
resolveOpenCodeConfigDirectory(),
|
||
'plugins',
|
||
'orca-opencode-status.js'
|
||
)
|
||
const targetPath = join(userDataDir, 'dotfiles-orca-opencode-status.js')
|
||
writeFileSync(targetPath, _internals.getOpenCodePluginSource())
|
||
rmSync(pluginPath, { force: true })
|
||
symlinkSync(targetPath, pluginPath)
|
||
const past = new Date('2020-01-01T00:00:00Z')
|
||
utimesSync(targetPath, past, past)
|
||
|
||
service.buildPtyEnv(daemonSessionId)
|
||
expect(statSync(targetPath).mtimeMs).toBe(past.getTime())
|
||
|
||
writeFileSync(targetPath, 'stale plugin')
|
||
service.buildPtyEnv(daemonSessionId)
|
||
expect(lstatSync(pluginPath).isSymbolicLink()).toBe(true)
|
||
expect(readFileSync(targetPath, 'utf8')).toBe(_internals.getOpenCodePluginSource())
|
||
rmSync(pluginPath, { force: true })
|
||
rmSync(targetPath, { force: true })
|
||
}
|
||
)
|
||
|
||
// A service reloading between writes must already find the TUI copy and stand down.
|
||
it('writes the TUI copy before the server plugin file', () => {
|
||
const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins')
|
||
const serverPath = join(pluginsDir, 'orca-opencode2-status.js')
|
||
const tuiDir = join(pluginsDir, 'orca-opencode2-status-tui')
|
||
rmSync(serverPath, { recursive: true, force: true })
|
||
rmSync(tuiDir, { recursive: true, force: true })
|
||
mkdirSync(serverPath, { recursive: true })
|
||
try {
|
||
openCode2HookService.buildPtyEnv(daemonSessionId)
|
||
expect(existsSync(join(tuiDir, 'tui.js'))).toBe(true)
|
||
} finally {
|
||
rmSync(serverPath, { recursive: true, force: true })
|
||
rmSync(tuiDir, { recursive: true, force: true })
|
||
}
|
||
})
|
||
|
||
it('installs a plugin whose default export satisfies both the v1 and v2 loaders', async () => {
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(daemonSessionId)
|
||
|
||
const pluginPath = join(resolveOpenCodeConfigDirectory(), 'plugins', 'orca-opencode-status.js')
|
||
// Use .mjs to load installed ESM without a package.json.
|
||
const modulePath = join(userDataDir, `installed-opencode-plugin-${Date.now()}.mjs`)
|
||
writeFileSync(modulePath, readFileSync(pluginPath, 'utf8'))
|
||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the assertions below validate the shape this names.
|
||
const module = (await import(pathToFileURL(modulePath).href)) as {
|
||
default?: { id?: unknown; server?: unknown; setup?: unknown }
|
||
}
|
||
|
||
expect(module.default?.id).toBe('orca-opencode-status')
|
||
expect(module.default?.server).toBeTypeOf('function')
|
||
expect(module.default?.setup).toBeTypeOf('function')
|
||
})
|
||
|
||
// Pre-1.4.209 installs left server-only plugins in this retired but still-used directory.
|
||
it('refreshes a stale plugin left in the retired shared hooks dir', async () => {
|
||
const legacyPluginPath = join(
|
||
userDataDir,
|
||
'opencode-hooks',
|
||
'shared',
|
||
'plugins',
|
||
'orca-opencode-status.js'
|
||
)
|
||
mkdirSync(join(legacyPluginPath, '..'), { recursive: true })
|
||
writeFileSync(
|
||
legacyPluginPath,
|
||
'export default { id: "orca-opencode-status", server: async () => ({}) };\n'
|
||
)
|
||
|
||
new OpenCodeHookService().buildPtyEnv(daemonSessionId)
|
||
|
||
const modulePath = join(userDataDir, `legacy-opencode-plugin-${Date.now()}.mjs`)
|
||
writeFileSync(modulePath, readFileSync(legacyPluginPath, 'utf8'))
|
||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the assertions below validate the shape this names.
|
||
const module = (await import(pathToFileURL(modulePath).href)) as {
|
||
default?: { id?: unknown; server?: unknown; setup?: unknown }
|
||
}
|
||
expect(module.default?.id).toBe('orca-opencode-status')
|
||
expect(module.default?.server).toBeTypeOf('function')
|
||
expect(module.default?.setup).toBeTypeOf('function')
|
||
// Services stand down only when their TUI copy exists alongside them.
|
||
expect(
|
||
readFileSync(join(legacyPluginPath, '..', 'orca-opencode-status-tui', 'tui.js'), 'utf8')
|
||
).toContain('tui: setupLegacyOpenCodeTui')
|
||
})
|
||
|
||
it('repairs late and overwritten legacy plugins atomically on the same service', () => {
|
||
const service = new OpenCodeHookService()
|
||
service.refreshLegacySharedPlugin()
|
||
const path = join(userDataDir, 'opencode-hooks', 'shared', 'plugins', 'orca-opencode-status.js')
|
||
mkdirSync(join(path, '..'), { recursive: true })
|
||
for (const stale of ['// late old install', '// old process overwrote repair']) {
|
||
writeFileSync(path, stale)
|
||
const reader = openSync(path, 'r')
|
||
try {
|
||
service.refreshLegacySharedPlugin()
|
||
expect(readFileSync(path, 'utf8')).toBe(getOpenCodePluginSource())
|
||
expect(readFileSync(reader, 'utf8')).toBe(stale)
|
||
expect(readdirSync(join(path, '..')).sort()).toEqual([
|
||
'orca-opencode-status-tui',
|
||
'orca-opencode-status.js'
|
||
])
|
||
} finally {
|
||
closeSync(reader)
|
||
}
|
||
}
|
||
})
|
||
|
||
it('reports repair failures and retries after the obstruction is removed', () => {
|
||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||
const path = join(userDataDir, 'opencode-hooks', 'shared', 'plugins', 'orca-opencode-status.js')
|
||
const service = new OpenCodeHookService()
|
||
try {
|
||
service.refreshLegacySharedPlugin()
|
||
expect(warn).not.toHaveBeenCalled()
|
||
mkdirSync(path, { recursive: true })
|
||
service.refreshLegacySharedPlugin()
|
||
expect(warn).toHaveBeenCalledWith(
|
||
'[OpenCode] Failed to repair legacy status plugin:',
|
||
path,
|
||
expect.any(Error)
|
||
)
|
||
rmSync(path, { recursive: true })
|
||
writeFileSync(path, '// stale')
|
||
service.refreshLegacySharedPlugin()
|
||
expect(readFileSync(path, 'utf8')).toBe(getOpenCodePluginSource())
|
||
} finally {
|
||
warn.mockRestore()
|
||
}
|
||
})
|
||
|
||
it('leaves an up-to-date legacy plugin untouched and never creates the retired dir', () => {
|
||
const legacyDir = join(userDataDir, 'opencode-hooks')
|
||
new OpenCodeHookService().buildPtyEnv(daemonSessionId)
|
||
expect(existsSync(legacyDir)).toBe(false)
|
||
|
||
const legacyPluginPath = join(legacyDir, 'shared', 'plugins', 'orca-opencode-status.js')
|
||
mkdirSync(join(legacyPluginPath, '..'), { recursive: true })
|
||
writeFileSync(legacyPluginPath, getOpenCodePluginSource())
|
||
const past = new Date('2020-01-01T00:00:00Z')
|
||
utimesSync(legacyPluginPath, past, past)
|
||
new OpenCodeHookService().buildPtyEnv(daemonSessionId)
|
||
expect(statSync(legacyPluginPath).mtimeMs).toBe(past.getTime())
|
||
})
|
||
|
||
// OpenCode 2 disables later plugins with duplicate IDs; verify installed artifacts.
|
||
it('installs both family plugins into one config dir under distinct ids', async () => {
|
||
expect(new OpenCodeHookService().buildPtyEnv(daemonSessionId)).toEqual({})
|
||
expect(openCode2HookService.buildPtyEnv(daemonSessionId)).toEqual({})
|
||
|
||
const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins')
|
||
const ids: string[] = []
|
||
for (const fileName of ['orca-opencode-status.js', 'orca-opencode2-status.js']) {
|
||
// Use .mjs to load installed ESM without a package.json.
|
||
const modulePath = join(userDataDir, `installed-${fileName}-${Date.now()}.mjs`)
|
||
writeFileSync(modulePath, readFileSync(join(pluginsDir, fileName), 'utf8'))
|
||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the assertions below validate the shape this names.
|
||
const module = (await import(pathToFileURL(modulePath).href)) as {
|
||
default?: { id?: unknown }
|
||
}
|
||
ids.push(String(module.default?.id))
|
||
}
|
||
|
||
expect(ids).toEqual(['orca-opencode-status', 'orca-opencode2-status'])
|
||
})
|
||
|
||
it('clearPty leaves the shared OpenCode config dir off the teardown hot path', () => {
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(daemonSessionId)
|
||
const configDir = resolveOpenCodeConfigDirectory()
|
||
expect(existsSync(configDir)).toBe(true)
|
||
mkdirSync(join(configDir, 'node_modules', 'opencode-runtime'), { recursive: true })
|
||
writeFileSync(join(configDir, 'node_modules', 'opencode-runtime', 'index.js'), '')
|
||
|
||
service.clearPty(daemonSessionId)
|
||
expect(existsSync(configDir)).toBe(true)
|
||
expect(existsSync(join(configDir, 'node_modules', 'opencode-runtime', 'index.js'))).toBe(true)
|
||
})
|
||
|
||
it('buildPtyEnv returns {} for an unusable id and creates nothing on disk', () => {
|
||
const service = new OpenCodeHookService()
|
||
const hooksRoot = join(userDataDir, 'opencode-hooks')
|
||
const overlaysRoot = join(userDataDir, 'opencode-config-overlays')
|
||
|
||
expect(service.buildPtyEnv('')).toEqual({})
|
||
expect(existsSync(hooksRoot)).toBe(false)
|
||
expect(existsSync(overlaysRoot)).toBe(false)
|
||
})
|
||
|
||
it('buildPtyEnv preserves a user-set OPENCODE_CONFIG_DIR when the id is unusable', () => {
|
||
const service = new OpenCodeHookService()
|
||
const userDir = mkdtempSync(join(tmpdir(), 'orca-opencode-userdir-'))
|
||
try {
|
||
expect(service.buildPtyEnv('', userDir)).toEqual({ OPENCODE_CONFIG_DIR: userDir })
|
||
} finally {
|
||
rmSync(userDir, { recursive: true, force: true })
|
||
}
|
||
})
|
||
|
||
it('works end-to-end for a plain UUID id (non-daemon path)', () => {
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(plainUuidId)
|
||
|
||
const configDir = resolveOpenCodeConfigDirectory()
|
||
expect(existsSync(join(configDir, 'plugins', 'orca-opencode-status.js'))).toBe(true)
|
||
|
||
service.clearPty(plainUuidId)
|
||
expect(existsSync(configDir)).toBe(true)
|
||
})
|
||
})
|
||
|
||
describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () => {
|
||
const ptyId = 'overlay-pty-1'
|
||
let userDataDir: string
|
||
let userConfigDir: string
|
||
|
||
beforeAll(() => {
|
||
userDataDir = mkdtempSync(join(tmpdir(), 'orca-opencode-overlay-userdata-'))
|
||
getPathMock.mockImplementation((name: string) => {
|
||
if (name === 'userData') {
|
||
return userDataDir
|
||
}
|
||
throw new Error(`unexpected getPath(${name})`)
|
||
})
|
||
})
|
||
|
||
afterAll(() => {
|
||
rmSync(userDataDir, { recursive: true, force: true })
|
||
})
|
||
|
||
beforeEach(() => {
|
||
userConfigDir = mkdtempSync(join(tmpdir(), 'orca-opencode-overlay-userconfig-'))
|
||
writeFileSync(join(userConfigDir, 'opencode.json'), '{"userTheme":"solarized"}')
|
||
writeFileSync(join(userConfigDir, 'auth.json'), 'user-auth-token')
|
||
mkdirSync(join(userConfigDir, 'plugins'), { recursive: true })
|
||
writeFileSync(join(userConfigDir, 'plugins', 'user-plugin.js'), 'export default () => {}')
|
||
})
|
||
|
||
afterEach(() => {
|
||
rmSync(userConfigDir, { recursive: true, force: true })
|
||
rmSync(join(userDataDir, 'opencode-hooks'), { recursive: true, force: true })
|
||
rmSync(join(userDataDir, 'opencode-config-overlays'), { recursive: true, force: true })
|
||
})
|
||
|
||
function expectUserConfigIntact(): void {
|
||
expect(readFileSync(join(userConfigDir, 'opencode.json'), 'utf8')).toBe(
|
||
'{"userTheme":"solarized"}'
|
||
)
|
||
expect(readFileSync(join(userConfigDir, 'auth.json'), 'utf8')).toBe('user-auth-token')
|
||
expect(readFileSync(join(userConfigDir, 'plugins', 'user-plugin.js'), 'utf8')).toBe(
|
||
'export default () => {}'
|
||
)
|
||
}
|
||
|
||
it('builds an overlay under userData and exposes user config + Orca plugin together', () => {
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(env.OPENCODE_CONFIG_DIR).toBe(
|
||
join(userDataDir, 'opencode-config-overlays', toSafeDirName(`source:${userConfigDir}`))
|
||
)
|
||
expect(env.OPENCODE_CONFIG_DIR).not.toBe(userConfigDir)
|
||
|
||
expect(readFileSync(join(env.OPENCODE_CONFIG_DIR!, 'opencode.json'), 'utf8')).toBe(
|
||
'{"userTheme":"solarized"}'
|
||
)
|
||
expect(readFileSync(join(env.OPENCODE_CONFIG_DIR!, 'auth.json'), 'utf8')).toBe(
|
||
'user-auth-token'
|
||
)
|
||
expect(readFileSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'user-plugin.js'), 'utf8')).toBe(
|
||
'export default () => {}'
|
||
)
|
||
|
||
const orcaPluginPath = join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js')
|
||
expect(existsSync(orcaPluginPath)).toBe(true)
|
||
expect(readFileSync(orcaPluginPath, 'utf8')).toContain('OrcaOpenCodeStatusPlugin')
|
||
|
||
expectUserConfigIntact()
|
||
})
|
||
|
||
it.skipIf(process.platform === 'win32')(
|
||
'mirrors top-level entries via symlinks so plugins/ is a real directory',
|
||
() => {
|
||
// Only plugins needs per-entry links; other links preserve live user edits.
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
const overlay = env.OPENCODE_CONFIG_DIR!
|
||
expect(lstatSync(join(overlay, 'opencode.json')).isSymbolicLink()).toBe(true)
|
||
expect(lstatSync(join(overlay, 'auth.json')).isSymbolicLink()).toBe(true)
|
||
expect(lstatSync(join(overlay, 'plugins')).isDirectory()).toBe(true)
|
||
expect(lstatSync(join(overlay, 'plugins')).isSymbolicLink()).toBe(false)
|
||
expect(lstatSync(join(overlay, 'plugins', 'user-plugin.js')).isSymbolicLink()).toBe(true)
|
||
}
|
||
)
|
||
|
||
it("does not overwrite a user plugin file with the same filename as Orca's plugin", () => {
|
||
// Mirroring this filename would let plugin installation overwrite the user’s file.
|
||
const userOrcaSentinel = 'USER OWNED ORCA-NAMED PLUGIN — DO NOT CLOBBER'
|
||
writeFileSync(join(userConfigDir, 'plugins', 'orca-opencode-status.js'), userOrcaSentinel)
|
||
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(readFileSync(join(userConfigDir, 'plugins', 'orca-opencode-status.js'), 'utf8')).toBe(
|
||
userOrcaSentinel
|
||
)
|
||
|
||
const overlayPlugin = readFileSync(
|
||
join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js'),
|
||
'utf8'
|
||
)
|
||
expect(overlayPlugin).toContain('OrcaOpenCodeStatusPlugin')
|
||
expect(overlayPlugin).not.toBe(userOrcaSentinel)
|
||
expectUserConfigIntact()
|
||
})
|
||
|
||
it('installs the TUI copy in the overlay without mirroring a user dir of the same name', () => {
|
||
const userTuiDir = join(userConfigDir, 'plugins', 'orca-opencode-status-tui')
|
||
mkdirSync(userTuiDir)
|
||
writeFileSync(join(userTuiDir, 'tui.js'), 'USER OWNED')
|
||
|
||
const env = new OpenCodeHookService().buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
const overlayTui = join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status-tui')
|
||
expect(lstatSync(overlayTui).isSymbolicLink()).toBe(false)
|
||
expect(readFileSync(join(overlayTui, 'tui.js'), 'utf8')).toContain(
|
||
'tui: setupLegacyOpenCodeTui'
|
||
)
|
||
expect(readFileSync(join(overlayTui, 'tui.js'), 'utf8')).toContain(
|
||
'setup: setupOpenCode2Status'
|
||
)
|
||
expect(readFileSync(join(userTuiDir, 'tui.js'), 'utf8')).toBe('USER OWNED')
|
||
})
|
||
|
||
it.skipIf(process.platform === 'win32')(
|
||
'does not write through a symlinked plugins/ directory into the user filesystem',
|
||
() => {
|
||
// Writing through a symlinked plugins directory would modify user-owned files.
|
||
const realPluginsDir = mkdtempSync(join(tmpdir(), 'orca-real-plugins-'))
|
||
try {
|
||
writeFileSync(join(realPluginsDir, 'real-plugin.js'), 'REAL USER PLUGIN')
|
||
|
||
rmSync(join(userConfigDir, 'plugins'), { recursive: true, force: true })
|
||
symlinkSync(realPluginsDir, join(userConfigDir, 'plugins'), 'dir')
|
||
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(existsSync(join(realPluginsDir, 'orca-opencode-status.js'))).toBe(false)
|
||
expect(lstatSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins')).isSymbolicLink()).toBe(false)
|
||
expect(
|
||
existsSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js'))
|
||
).toBe(true)
|
||
expect(
|
||
readFileSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'real-plugin.js'), 'utf8')
|
||
).toBe('REAL USER PLUGIN')
|
||
} finally {
|
||
rmSync(realPluginsDir, { recursive: true, force: true })
|
||
}
|
||
}
|
||
)
|
||
|
||
it("preserves the user's OPENCODE_CONFIG_DIR when the path does not exist", () => {
|
||
// Preserve typo paths so OpenCode reports them instead of silently hiding user config.
|
||
const service = new OpenCodeHookService()
|
||
const missingPath = join(tmpdir(), `orca-opencode-nope-${Date.now()}`)
|
||
expect(existsSync(missingPath)).toBe(false)
|
||
|
||
const env = service.buildPtyEnv(ptyId, missingPath)
|
||
expect(env).toEqual({ OPENCODE_CONFIG_DIR: missingPath })
|
||
expect(existsSync(missingPath)).toBe(false)
|
||
expect(
|
||
existsSync(
|
||
join(userDataDir, 'opencode-config-overlays', toSafeDirName(`source:${missingPath}`))
|
||
)
|
||
).toBe(false)
|
||
})
|
||
|
||
it("preserves the user's OPENCODE_CONFIG_DIR when the mirror step fails", async () => {
|
||
const overlayMirror = await import('../pty/overlay-mirror')
|
||
const mirrorSpy = vi.spyOn(overlayMirror, 'mirrorEntry').mockImplementation(() => {
|
||
throw new Error('simulated EPERM on symlink')
|
||
})
|
||
try {
|
||
const service = new OpenCodeHookService()
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
expect(env).toEqual({ OPENCODE_CONFIG_DIR: userConfigDir })
|
||
// Fallback overlays may contain live Windows runtime files; defer cleanup.
|
||
const overlayDir = join(
|
||
userDataDir,
|
||
'opencode-config-overlays',
|
||
toSafeDirName(`source:${userConfigDir}`)
|
||
)
|
||
expect(existsSync(overlayDir)).toBe(true)
|
||
expectUserConfigIntact()
|
||
} finally {
|
||
mirrorSpy.mockRestore()
|
||
}
|
||
})
|
||
|
||
it.skipIf(process.platform === 'win32')(
|
||
'clearPty leaves the source overlay off the teardown hot path',
|
||
() => {
|
||
// Runtime files can make recursive overlay deletion block Electron main.
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
const overlayDir = join(
|
||
userDataDir,
|
||
'opencode-config-overlays',
|
||
toSafeDirName(`source:${userConfigDir}`)
|
||
)
|
||
expect(existsSync(overlayDir)).toBe(true)
|
||
|
||
service.clearPty(ptyId)
|
||
|
||
expect(existsSync(overlayDir)).toBe(true)
|
||
expectUserConfigIntact()
|
||
expect(readdirSync(join(userConfigDir, 'plugins'))).toEqual(['user-plugin.js'])
|
||
}
|
||
)
|
||
|
||
it('rebuilding the overlay for the same ptyId does not corrupt the user dir', () => {
|
||
const service = new OpenCodeHookService()
|
||
service.buildPtyEnv(ptyId, userConfigDir)
|
||
service.buildPtyEnv(ptyId, userConfigDir)
|
||
const env = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(
|
||
readFileSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js'), 'utf8')
|
||
).toContain('OrcaOpenCodeStatusPlugin')
|
||
expectUserConfigIntact()
|
||
})
|
||
|
||
it('leaves a current overlay plugin file in place across spawns', () => {
|
||
const service = new OpenCodeHookService()
|
||
const overlayDir = service.buildPtyEnv(ptyId, userConfigDir).OPENCODE_CONFIG_DIR!
|
||
const pluginPath = join(overlayDir, 'plugins', 'orca-opencode-status.js')
|
||
const past = new Date('2020-01-01T00:00:00Z')
|
||
utimesSync(pluginPath, past, past)
|
||
|
||
service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(statSync(pluginPath).mtimeMs).toBe(past.getTime())
|
||
expect(readFileSync(pluginPath, 'utf8')).toBe(_internals.getOpenCodePluginSource())
|
||
})
|
||
|
||
it('reconciles stale mirrored entries while preserving OpenCode runtime files', () => {
|
||
const service = new OpenCodeHookService()
|
||
const firstEnv = service.buildPtyEnv(ptyId, userConfigDir)
|
||
const overlayDir = firstEnv.OPENCODE_CONFIG_DIR!
|
||
|
||
mkdirSync(join(overlayDir, 'node_modules', 'opencode-runtime'), { recursive: true })
|
||
writeFileSync(join(overlayDir, 'node_modules', 'opencode-runtime', 'index.js'), '')
|
||
|
||
rmSync(join(userConfigDir, 'auth.json'), { force: true })
|
||
writeFileSync(join(userConfigDir, 'auth.json'), 'rotated-user-auth-token')
|
||
rmSync(join(userConfigDir, 'plugins', 'user-plugin.js'), { force: true })
|
||
writeFileSync(join(userConfigDir, 'plugins', 'new-plugin.js'), 'export default "new"')
|
||
|
||
const secondEnv = service.buildPtyEnv(ptyId, userConfigDir)
|
||
|
||
expect(secondEnv.OPENCODE_CONFIG_DIR).toBe(overlayDir)
|
||
expect(readFileSync(join(overlayDir, 'auth.json'), 'utf8')).toBe('rotated-user-auth-token')
|
||
expect(existsSync(join(overlayDir, 'plugins', 'user-plugin.js'))).toBe(false)
|
||
expect(readFileSync(join(overlayDir, 'plugins', 'new-plugin.js'), 'utf8')).toBe(
|
||
'export default "new"'
|
||
)
|
||
expect(existsSync(join(overlayDir, 'node_modules', 'opencode-runtime', 'index.js'))).toBe(true)
|
||
})
|
||
})
|