Compare commits

...

20 Commits

Author SHA1 Message Date
0xmrpeter
c112cafa13 chore: bump version to 2026.408.4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 23:39:19 +07:00
0xmrpeter
99ec609e88 fix(agents): complete global fallback chain for all catalog methods
PR #219 added global→instance fallback for read methods but missed
resolve(), getAvailable(), and uninstall(). Also removed `as any`
cast on filePath (already readonly).

- resolve(): fall through to globalStore so agents can actually spawn
- getAvailable(): use merged installed entries for consistent listing
- uninstall(): distinguish local, global-only, and missing agents
- Constructor: use this.store.filePath directly instead of as any cast

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 23:38:09 +07:00
Mr.Peter
c7b5647803
Merge pull request #219 from lngdao/fix/ensure-default-agent-on-boot
fix(agents): implement global-to-instance agent fallback chain
2026-04-08 23:23:24 +07:00
0xmrpeter
6d39fea411 feat: detect parent .openacp instance in CLI prompt
Walk up directory tree to find nearest parent .openacp/ when no
instance found in exact CWD. Shows as priority option with
"detected" label. Non-TTY and first-run also prefer parent over
global fallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 23:04:09 +07:00
lngdao
e13e46adda fix: AgentCatalog fallback chain — instance agents inherit from global
AgentCatalog now loads both instance-local and global (~/.openacp/)
agent stores. Lookups check instance first, then fall back to global.
This ensures all globally installed agents are available in every
workspace instance without copying files.

Changes:
- AgentStore.filePath made readonly (was private) for path comparison
- AgentCatalog constructor detects if instance != global, loads both
- getInstalled/getInstalledEntries merge global into instance (instance wins)
- getInstalledAgent falls through: instance → global
- Removed hardcoded fallback from core.ts (no longer needed)
2026-04-08 22:58:50 +07:00
0xmrpeter
fc9f4c92c9 feat: resolve nearest running instance for handoff adopt
Walk up directory tree from agent CWD to find the closest running
.openacp/ instance instead of always targeting global ~/.openacp.
Skips dead instances, falls back to global if no local found.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 22:34:15 +07:00
0xmrpeter
e05745075f docs: fix spec after code review
- resolveInstanceRoot() already exists in instance-context.ts (sync)
- Add new async resolveRunningInstance() instead of replacing
- Reuse checkHealth() from instance-discovery.ts
- Reuse findPackageRoot() walk-up pattern from agent-instance.ts
- Note that adopt.ts is the only CLI command missing instanceRoot

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 22:18:58 +07:00
0xmrpeter
5f39e6403e docs: add handoff instance resolution design spec
When multiple instances run on the same machine, handoff should
route to the nearest running instance by walking up the directory
tree from the agent's CWD, instead of always targeting global.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 22:14:29 +07:00
hightman
efc9214e4d
fix: restore apply_patch diff stats/viewer and align tool card rendering (#214)
* fix: improve apply_patch compatibility and tool-card rendering

Unify apply_patch detection, harden diff/viewer extraction for tool_update payloads, prioritize highest-churn files for multi-file viewer links, and map apply_patch cards to edit-style rendering for consistent UI behavior.

Co-authored-by: Codex <noreply@openai.com>

* fix: remove duplicate TodoWrite title branch

Keep a single TodoWrite title formatter in buildTitle to reduce ambiguity while preserving existing compatibility behavior.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-04-08 17:11:59 +07:00
0xmrpeter
6b2bb29864 chore: bump version to 2026.408.3
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 17:10:16 +07:00
0xmrpeter
4037bb221d fix(agents): robust npx/uvx resolution with fallback search
- Step 3: return resolved full path for non-node commands found via `which`
  (previously fell through silently)
- Step 4: search multiple locations for npx/uvx — process.execPath dir,
  its realpath, /opt/homebrew/bin, /usr/local/bin
- Add logging for fallback resolution to aid debugging

Fixes spawn ENOENT when daemon's PATH doesn't include npx directory.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 17:10:09 +07:00
0xmrpeter
7835713c77 chore: bump version to 2026.408.2
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 16:31:51 +07:00
Mr.Peter
c9c6f3951a
Merge pull request #217 from Open-ACP/feat/tunnel-reconnect-on-restart
feat(tunnel): reconnect to existing tunnels on restart + fix npx resolution
2026-04-08 16:31:05 +07:00
0xmrpeter
b6d6b356a7 fix(agents): resolve npx/uvx from Node bin directory when not on PATH
When openacp is installed globally (e.g. via Homebrew or nvm), npx lives
next to the same node binary executing the process. The user's shell PATH
may not include that directory in non-interactive shells, so resolve it
explicitly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 16:28:02 +07:00
0xmrpeter
204fe661e4 docs: add tunnel reconnect on restart plan
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 16:27:55 +07:00
0xmrpeter
6130025fae perf(tunnel): restore user tunnels in parallel instead of sequentially
Use Promise.allSettled() instead of sequential for...of loop in restore(),
so all user tunnels start concurrently rather than waiting for each one
to fully connect before starting the next.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 16:01:16 +07:00
0xmrpeter
85b3d5eaa1 perf(tunnel): resolve startup immediately on cloudflared connection registration instead of waiting 15s timeout
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 15:57:45 +07:00
0xmrpeter
bf1fab5224 feat(tunnel): preserve state on shutdown, drop sessionId on restore, guard double shutdown
- shutdown() now passes preserveState=true to providers, saves tunnels.json
  before clearing entries, and guards against double-shutdown
- flush() becomes a no-op after shutdown to prevent overwriting preserved state
- restore() omits sessionId since sessions don't survive restart

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 15:48:01 +07:00
0xmrpeter
a9cb2b67d3 feat(tunnel): skip worker deletion when preserveState=true in OpenACP provider
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 15:45:08 +07:00
0xmrpeter
c577814e35 feat(tunnel): add preserveState param to TunnelProvider.stop() interface
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 15:45:02 +07:00
24 changed files with 1717 additions and 117 deletions

View File

@ -0,0 +1,483 @@
# Tunnel Reconnect on Restart — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Preserve tunnel URLs across graceful restarts by reconnecting to existing Cloudflare tunnels instead of creating new ones every time.
**Architecture:** During shutdown, skip deleting the tunnel from the Cloudflare worker and preserve the tunnel state in plugin storage. On restart, the OpenACP provider's existing `resolveCredentials()` logic already pings the worker and reuses the tunnel if it's still alive (within 24h TTL). The only changes needed are: (1) don't destroy state on shutdown, (2) persist `tunnels.json` before clearing in-memory entries, (3) drop stale `sessionId` on restore.
**Tech Stack:** TypeScript, Vitest
---
## File Structure
| File | Action | Responsibility |
|------|--------|----------------|
| `src/plugins/tunnel/provider.ts` | Modify | Add `preserveState` param to `stop()` interface |
| `src/plugins/tunnel/providers/openacp.ts` | Modify | Skip worker deletion and storage cleanup when `preserveState=true` |
| `src/plugins/tunnel/tunnel-registry.ts` | Modify | Pass `preserveState=true` during shutdown, persist entries before clearing, drop sessionId on restore, guard double shutdown |
| `src/plugins/tunnel/__tests__/openacp-provider.test.ts` | Modify | Add tests for `stop()` with `preserveState` (file already exists — append to it) |
| `src/plugins/tunnel/__tests__/tunnel-registry.test.ts` | Modify | Add tests for shutdown persistence and restore sessionId behavior |
---
## Callsite Safety Analysis
Before implementing, confirm all `provider.stop()` callsites behave correctly:
| Callsite | Location | Args after change | Behavior | Correct? |
|----------|----------|-------------------|----------|----------|
| `registry.shutdown()` | `tunnel-registry.ts:274` | `stop(true, true)` | Kill process, preserve state for reconnect | Yes — this is the change |
| `registry.stop(port)` | `tunnel-registry.ts:239` | `stop()` → `stop(false, false)` | Full cleanup (delete from worker + storage) | Yes — user-initiated stop |
| Keepalive dead detection | `tunnel-registry.ts:142` | `stop()` → `stop(false, false)` | Full cleanup — tunnel is dead on worker anyway | Yes — correct |
| Other providers (cloudflare, ngrok, bore, tailscale) | various | `preserveState` ignored | No state to preserve | Yes — no change needed |
---
### Task 1: Update TunnelProvider Interface
**Files:**
- Modify: `src/plugins/tunnel/provider.ts`
- [ ] **Step 1: Add `preserveState` parameter to `stop()` in the interface**
```typescript
export interface TunnelProvider {
start(localPort: number): Promise<string> // returns public URL
/** Stop the tunnel. When force=true, skip graceful shutdown and SIGKILL immediately.
* When preserveState=true, keep tunnel alive on remote (don't delete from worker/storage) for reconnect on restart. */
stop(force?: boolean, preserveState?: boolean): Promise<void>
getPublicUrl(): string
/** Register a callback invoked when the tunnel process exits unexpectedly after establishment. */
onExit(callback: (code: number | null) => void): void
}
```
- [ ] **Step 2: Verify build passes**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build`
Expected: No errors — existing providers implement `stop(force?)` which is still compatible since `preserveState` is optional.
- [ ] **Step 3: Commit**
```bash
git add src/plugins/tunnel/provider.ts
git commit -m "feat(tunnel): add preserveState param to TunnelProvider.stop() interface"
```
---
### Task 2: Implement `preserveState` in OpenACP Provider
**Files:**
- Modify: `src/plugins/tunnel/providers/openacp.ts`
- Modify: `src/plugins/tunnel/__tests__/openacp-provider.test.ts` (existing file)
- [ ] **Step 1: Add the failing test to the existing test file**
Append a new `describe` block at the end of `src/plugins/tunnel/__tests__/openacp-provider.test.ts`:
```typescript
describe('OpenACPTunnelProvider — preserveState', () => {
let storage: ReturnType<typeof makeStorage>
let fetchMock: ReturnType<typeof vi.fn>
beforeEach(() => {
storage = makeStorage()
fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
vi.useFakeTimers()
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
it('stop(true, true) kills process but does NOT delete from worker or clear storage', async () => {
const saved = { '3100': { tunnelId: 'cf-ps', token: 'tok-ps', publicUrl: 'https://ps.tunnel.openacp.ai' } }
storage = makeStorage({ 'openacp-tunnels': saved })
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
await vi.advanceTimersByTimeAsync(15_001)
await startPromise
// Stop WITH preserveState
await provider.stop(true, true)
// Should have killed the process
expect(proc.kill).toHaveBeenCalledWith('SIGKILL')
// Should NOT have called DELETE on worker
const deleteCalls = fetchMock.mock.calls.filter(
([url, init]: [any, any]) => init?.method === 'DELETE'
)
expect(deleteCalls.length).toBe(0)
// Storage should still have the tunnel state
const state = await storage.get<Record<string, unknown>>('openacp-tunnels')
expect(state).toEqual(saved)
})
it('stop(false, false) still deletes from worker and clears storage (default behavior)', async () => {
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock
.mockResolvedValueOnce({ ok: true, json: async () => ({ tunnelId: 'cf-del', token: 'tok-del', publicUrl: 'https://del.tunnel.openacp.ai' }) })
.mockResolvedValue({ ok: true, json: async () => ({}) })
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
await vi.advanceTimersByTimeAsync(15_001)
await startPromise
await provider.stop()
const deleteCalls = fetchMock.mock.calls.filter(
([url, init]: [any, any]) => String(url).includes('/tunnel/cf-del') && init?.method === 'DELETE'
)
expect(deleteCalls.length).toBe(1)
expect(storage.set).toHaveBeenLastCalledWith('openacp-tunnels', {})
})
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test -- src/plugins/tunnel/__tests__/openacp-provider.test.ts`
Expected: First test fails because `stop()` currently always deletes from worker and clears storage regardless of args.
- [ ] **Step 3: Implement `preserveState` logic in `stop()`**
In `src/plugins/tunnel/providers/openacp.ts`, change the `stop()` method:
```typescript
async stop(force = false, preserveState = false): Promise<void> {
this.stopHeartbeat()
const child = this.child
const tunnelId = this.tunnelId
const localPort = this.localPort
this.child = null
this.exitCallback = null
if (child) {
child.kill(force ? 'SIGKILL' : 'SIGTERM')
if (!force) {
// Escalate to SIGKILL asynchronously if process doesn't exit on its own
const killTimer = setTimeout(() => {
if (!child.killed) child.kill('SIGKILL')
}, SIGKILL_TIMEOUT_MS)
child.once('exit', () => clearTimeout(killTimer))
}
}
if (tunnelId && !preserveState) {
this.deleteFromWorker(tunnelId).catch(err => {
log.warn({ err: (err as Error).message }, 'Failed to delete tunnel from worker')
})
const all = await this.loadState()
delete all[String(localPort)]
await this.storage.set(STORAGE_KEY, all)
}
log.info({ localPort, preserveState }, 'OpenACP tunnel stopped')
}
```
The only change is adding `preserveState = false` parameter and wrapping the deletion block with `if (tunnelId && !preserveState)`.
- [ ] **Step 4: Run tests to verify they pass**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test -- src/plugins/tunnel/__tests__/openacp-provider.test.ts`
Expected: All tests pass (both existing and new).
- [ ] **Step 5: Commit**
```bash
git add src/plugins/tunnel/providers/openacp.ts src/plugins/tunnel/__tests__/openacp-provider.test.ts
git commit -m "feat(tunnel): skip worker deletion when preserveState=true in OpenACP provider"
```
---
### Task 3: Update TunnelRegistry Shutdown and Restore
**Files:**
- Modify: `src/plugins/tunnel/tunnel-registry.ts`
- Modify: `src/plugins/tunnel/__tests__/tunnel-registry.test.ts`
- [ ] **Step 1: Write failing tests**
Add to `src/plugins/tunnel/__tests__/tunnel-registry.test.ts`, as a new `describe` block at the end:
```typescript
describe('TunnelRegistry — shutdown persistence', () => {
beforeEach(() => {
vi.useFakeTimers()
mockProviderInstances = []
nextMockOverride = null
})
afterEach(() => {
vi.useRealTimers()
})
it('shutdown passes preserveState=true to providers', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'system', provider: 'cloudflare' })
await registry.add(3200, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
for (const mock of mockProviderInstances) {
expect(mock.stop).toHaveBeenCalledWith(true, true)
}
})
it('shutdown persists entries to tunnels.json before clearing', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'system', provider: 'cloudflare' })
await registry.add(3200, { type: 'user', provider: 'cloudflare', label: 'my-app' })
await registry.shutdown()
// writeFileSync should have been called with the entries (not empty array)
const writeCalls = vi.mocked(fs.writeFileSync).mock.calls
const lastWrite = writeCalls[writeCalls.length - 1]
const persisted = JSON.parse(lastWrite[1] as string) as Array<{ port: number; type: string }>
expect(persisted).toHaveLength(2)
expect(persisted.map(e => e.port).sort()).toEqual([3100, 3200])
})
it('flush() is a no-op after shutdown (does not overwrite with empty)', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
const writeCountAfterShutdown = vi.mocked(fs.writeFileSync).mock.calls.length
// flush() after shutdown should not write again
registry.flush()
expect(vi.mocked(fs.writeFileSync).mock.calls.length).toBe(writeCountAfterShutdown)
})
it('double shutdown does not overwrite preserved tunnels.json', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
const writeCountAfterFirst = vi.mocked(fs.writeFileSync).mock.calls.length
// Second shutdown should be a no-op (entries already cleared, shuttingDown already true)
await registry.shutdown()
expect(vi.mocked(fs.writeFileSync).mock.calls.length).toBe(writeCountAfterFirst)
})
})
```
- [ ] **Step 2: Add restore sessionId test**
Add this test inside the existing `describe('TunnelRegistry — restore', ...)` block:
```typescript
it('restores user tunnels without sessionId (sessions do not survive restart)', async () => {
const persisted = [
{ port: 3200, type: 'user', provider: 'cloudflare', label: 'my-app', sessionId: 'sess-old', createdAt: new Date().toISOString() },
]
vi.mocked(fs.existsSync).mockReturnValue(true)
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(persisted))
const registry = new TunnelRegistry()
await registry.restore()
const restored = registry.list(false)
expect(restored).toHaveLength(1)
expect(restored[0].label).toBe('my-app')
expect(restored[0].sessionId).toBeUndefined()
})
```
- [ ] **Step 3: Run tests to verify they fail**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test -- src/plugins/tunnel/__tests__/tunnel-registry.test.ts`
Expected: New tests fail:
- `preserveState=true` — shutdown calls `stop(true)` without second arg
- Persistence — shutdown clears entries before save
- flush no-op — flush still saves after shutdown
- double shutdown — second shutdown overwrites with empty
- restore sessionId — sessionId is currently passed through
- [ ] **Step 4: Implement changes in TunnelRegistry**
In `src/plugins/tunnel/tunnel-registry.ts`, make these changes:
**Change `shutdown()` method:**
```typescript
async shutdown(): Promise<void> {
if (this.shuttingDown) return
this.keepalive.stop()
this.shuttingDown = true
// Cancel any pending save timers
if (this.saveTimeout) {
clearTimeout(this.saveTimeout)
this.saveTimeout = null
}
const stopPromises: Promise<void>[] = []
for (const [, live] of this.entries) {
if (live.retryTimer) clearTimeout(live.retryTimer)
if (live.process) {
stopPromises.push(live.process.stop(true, true).catch(() => { /* ignore */ }))
}
}
await Promise.all(stopPromises)
// Persist current state so tunnels can reconnect on next startup
this.save()
this.entries.clear()
}
```
**Change `flush()` to skip after shutdown:**
```typescript
flush(): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout)
this.saveTimeout = null
}
if (!this.shuttingDown) {
this.save()
}
}
```
**Change `restore()` to drop sessionId:**
```typescript
async restore(): Promise<void> {
if (!fs.existsSync(this.registryPath)) return
try {
const raw = JSON.parse(fs.readFileSync(this.registryPath, 'utf-8')) as PersistedEntry[]
log.info({ count: raw.length }, 'Restoring tunnels')
// Only restore user tunnels — system tunnel is registered separately by TunnelService.start()
const userEntries = raw.filter(e => e.type === 'user')
for (const persisted of userEntries) {
try {
await this.add(persisted.port, {
type: persisted.type,
provider: persisted.provider,
label: persisted.label,
// sessionId intentionally omitted — sessions don't survive restart
})
} catch (err) {
log.warn({ port: persisted.port, err: (err as Error).message }, 'Failed to restore tunnel')
}
}
} catch (err) {
log.warn({ err: (err as Error).message }, 'Failed to read tunnels.json')
}
}
```
Note: `restore()` already omits `sessionId` in the current code — `persisted.sessionId` is passed through.
Check the current code: if `sessionId` IS being passed, remove it. If it's already omitted, no change needed.
- [ ] **Step 5: Run tests to verify they pass**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test -- src/plugins/tunnel/__tests__/tunnel-registry.test.ts`
Expected: All tests pass (both existing and new).
- [ ] **Step 6: Commit**
```bash
git add src/plugins/tunnel/tunnel-registry.ts src/plugins/tunnel/__tests__/tunnel-registry.test.ts
git commit -m "feat(tunnel): preserve state on shutdown, drop sessionId on restore, guard double shutdown"
```
---
### Task 4: Run Full Test Suite and Verify Build
**Files:** None (verification only)
- [ ] **Step 1: Run full tunnel test suite**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test -- src/plugins/tunnel/`
Expected: All tests pass.
- [ ] **Step 2: Run full project build**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm build`
Expected: No TypeScript errors.
- [ ] **Step 3: Run full test suite**
Run: `cd /Users/lucas/code/openacp-workspace/OpenACP && pnpm test`
Expected: All tests pass.
- [ ] **Step 4: Commit (if any fixes were needed)**
Only if test failures required fixes.
---
## Callsite Safety Analysis
All `provider.stop()` and `registry.shutdown()` callsites reviewed:
| Callsite | File:Line | After Change | Safe? |
|----------|-----------|-------------|-------|
| `registry.shutdown()` → `process.stop(true, true)` | `tunnel-registry.ts:274` | Preserves state for reconnect | Yes |
| `registry.stop(port)` → `process.stop()` | `tunnel-registry.ts:239` | Full cleanup (user-initiated) | Yes |
| Keepalive dead → `live.process?.stop()` | `tunnel-registry.ts:142` | Full cleanup (tunnel dead on worker) | Yes |
| `registry.stopBySession()` → `this.stop()` | `tunnel-registry.ts:252` | Full cleanup per tunnel | Yes |
| `registry.stopAllUser()` → `this.stop()` | `tunnel-registry.ts:262` | Full cleanup per tunnel | Yes |
| `TunnelService.stop()` → `registry.shutdown()` + `registry.flush()` | `tunnel-service.ts:91-96` | shutdown preserves, flush is no-op after | Yes |
| Plugin `teardown()` → `service.stop()` | `index.ts:271-275` | Triggers TunnelService.stop() | Yes |
## Edge Cases Handled
| Edge Case | Handling |
|-----------|----------|
| **Double shutdown** | Guard `if (this.shuttingDown) return` at top of `shutdown()` |
| **Restart within 24h** | `resolveCredentials()` pings worker → tunnel alive → reuse same URL |
| **Restart after 24h** | Worker cron expired tunnel → ping fails → creates new tunnel (graceful) |
| **API port change** | No saved state for new port → creates new tunnel. Old state orphaned (minor, harmless) |
| **Provider change** | New provider ignores old openacp state. Old state orphaned (minor, harmless) |
| **Crash (SIGKILL)** | `stop()` never ran → state already preserved → reconnect works |
| **Stale sessionId** | Dropped on restore — restored tunnels have no session binding |
| **Non-openacp user tunnels** | Restored from tunnels.json → new URL (no state reuse for these providers) but tunnel auto-restarts |
| **flush() after shutdown** | No-op — won't overwrite preserved tunnels.json |
## Summary of Behavior After Changes
| Scenario | Before | After |
|----------|--------|-------|
| **Graceful shutdown** (Ctrl+C) | Deletes tunnel from CF worker, clears storage, saves empty `tunnels.json` | Kills cloudflared only, keeps tunnel alive on worker, preserves storage, saves full `tunnels.json` |
| **User `/tunnel stop`** | Full cleanup (delete from worker + storage) | Same — full cleanup (unchanged) |
| **Restart within 24h** | Always creates new tunnel with new URL | Pings worker → if alive, reuses same tunnel with same URL |
| **Restart after 24h** | Creates new tunnel | Worker cron already expired the tunnel → creates new tunnel (graceful fallback) |
| **Crash (SIGKILL)** | State preserved (stop never ran) → reconnect works | Same — state preserved → reconnect works |
| **User tunnels** | Lost on restart (tunnels.json emptied) | Restored on restart, sessionId dropped, same URL if openacp provider |

View File

@ -0,0 +1,119 @@
# Handoff Instance Resolution Design
**Date**: 2026-04-08
**Status**: Draft
## Problem
When multiple OpenACP instances run on the same machine (e.g., global `~/.openacp/` + local project `~/workspace/.openacp/`), the handoff flow always targets the global instance. The CLI `adopt` command calls `readApiPort()` with no arguments, which defaults to `~/.openacp/api.port` — it has no awareness of local instances.
Note: other CLI commands (`api.ts`, `config.ts`, `tunnel.ts`, `remote.ts`) already pass `instanceRoot` to `readApiPort()` correctly. `adopt.ts` is the outlier.
Users commonly work in workspaces with nested project directories. An agent running in `~/workspace/project-A/src/core/` should handoff to the instance at `~/workspace/.openacp/` if one is running, not to the unrelated global instance.
## Design
### Instance Resolution Algorithm
Enhance the existing `resolveInstanceRoot()` in `instance-context.ts` to walk up the directory tree from the agent's working directory, looking for a running `.openacp/` instance. Currently it only checks the exact CWD — it needs to climb like `findPackageRoot()` in `agent-instance.ts`.
```
resolveRunningInstance(cwd):
dir = cwd
while dir != path.dirname(dir): // stop at filesystem root
candidate = path.join(dir, '.openacp')
if candidate exists:
port = read candidate/api.port
if port exists AND health check passes:
return candidate // found running instance
else:
continue walking up // instance exists but not running, skip
dir = path.dirname(dir)
// fallback: global instance
global = ~/.openacp
if global has api.port AND health check passes:
return global
// nothing running
return null
```
**Key behaviors:**
- Nearest running instance wins (like `.git` discovery)
- Dead instances (exist but not running) are skipped — continue walking up
- Fallback to global `~/.openacp/` if no local instance found
- Health check: read `api.port` file + HTTP GET to `/api/v1/system/health` (reuse `checkHealth()` from `instance-discovery.ts`)
### Changes Required
#### 1. New async function: `resolveRunningInstance()`
**Location**: `src/core/instance/instance-context.ts` (alongside existing `resolveInstanceRoot()`)
```typescript
export async function resolveRunningInstance(cwd: string): Promise<string | null>
```
- New function — does NOT modify or replace the existing sync `resolveInstanceRoot()`, which is used by multiple CLI commands for non-network resolution
- Walks up directory tree using the same pattern as `findPackageRoot()` in `agent-instance.ts`
- At each `.openacp/` candidate: reads `api.port`, calls `checkHealth()` from `instance-discovery.ts`
- Returns instance root path, or `null` if nothing running
#### 2. Modify CLI `adopt.ts`
Replace the current port resolution:
```typescript
// Before
const port = readApiPort()
// After
const instanceRoot = await resolveRunningInstance(cwd ?? process.cwd())
if (!instanceRoot) {
console.error('No running OpenACP instance found')
process.exit(1)
}
const port = readApiPort(undefined, instanceRoot)
```
- `cwd` comes from the `--cwd` flag (already parsed in adopt.ts but unused for instance resolution)
- If `--cwd` not provided, falls back to `process.cwd()`
#### 3. No changes to shell scripts
The handoff scripts (`openacp-handoff.sh`, `openacp-inject-session.sh`) and slash commands remain unchanged. They already pass `--cwd` to `openacp adopt`. This means:
- Users who already integrated don't need to re-run `openacp integrate`
- Backward compatible — old installs work without changes
### Edge Cases
| Scenario | Behavior |
|----------|----------|
| Nested instances: `~/workspace/.openacp/` + `~/workspace/project/.openacp/` | Nearest running instance wins |
| Instance dir exists but daemon is dead | Skip, continue walking up |
| No local instance, global is running | Fallback to global |
| No instance running anywhere | Error: "No running OpenACP instance found" |
| `--cwd` not provided | Use `process.cwd()` |
| Agent in deeply nested dir (`~/workspace/project/src/core/utils/`) | Walks up all levels until finding `.openacp/` |
### What Does NOT Change
- Existing sync `resolveInstanceRoot()` — untouched, no breaking change
- Shell hook scripts (no re-integration needed)
- Daemon-side adopt logic (`core.adoptSession()`)
- API endpoints
- Session storage format
- Instance registry format
## Testing
1. **Unit tests for `resolveRunningInstance()`**:
- Walk up finds nearest running instance
- Skips dead instances (`.openacp/` exists, no running daemon), finds next running one
- Falls back to global when no local instance found
- Returns null when nothing is running
- Nested instances: nearest running wins over parent
2. **Integration test**:
- Two instances running (local + global), adopt from nested CWD routes to local

View File

@ -1,6 +1,6 @@
{
"name": "@openacp/cli",
"version": "2026.408.1",
"version": "2026.408.4",
"private": true,
"license": "MIT",
"type": "module",

View File

@ -211,5 +211,92 @@ describe('extractFileInfo', () => {
oldContent: 'old',
})
})
it('extracts apply_patch file info from rawOutput metadata files', () => {
const rawOutput = {
metadata: {
files: [
{
filePath: '/src/main.ts',
before: 'const a = 1',
after: 'const a = 2',
},
],
},
}
const result = extractFileInfo('apply_patch', 'other', null, null, null, rawOutput)
expect(result).toMatchObject({
filePath: '/src/main.ts',
content: 'const a = 2',
oldContent: 'const a = 1',
})
})
it('returns null for malformed apply_patch rawOutput', () => {
const rawOutput = {
metadata: {
files: [
{ additions: 1, deletions: 1 },
{ filePath: 123, after: 456 },
],
},
}
const result = extractFileInfo('apply_patch', 'other', null, null, null, rawOutput)
expect(result).toBeNull()
})
it('extracts apply_patch rawOutput when tool_update name is missing but patchText exists', () => {
const rawInput = { patchText: '*** Begin Patch\n*** Update File: src/main.ts\n*** End Patch' }
const rawOutput = {
metadata: {
files: [
{
filePath: '/src/main.ts',
before: 'const a = 1',
after: 'const a = 2',
},
],
},
}
const result = extractFileInfo('', 'other', null, rawInput, null, rawOutput)
expect(result).toMatchObject({
filePath: '/src/main.ts',
content: 'const a = 2',
oldContent: 'const a = 1',
})
})
it('prefers apply_patch file with largest diff score for viewer target', () => {
const rawOutput = {
metadata: {
files: [
{
filePath: '/src/small.ts',
before: 'a',
after: 'b',
additions: 1,
deletions: 1,
},
{
filePath: '/src/large.ts',
before: 'x',
after: 'y',
additions: 8,
deletions: 3,
},
],
},
}
const result = extractFileInfo('apply_patch', 'other', null, null, null, rawOutput)
expect(result).toMatchObject({
filePath: '/src/large.ts',
content: 'y',
oldContent: 'x',
})
})
})
})

View File

@ -0,0 +1,73 @@
import { describe, it, expect, afterEach } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { findParentInstance } from '../instance-prompt.js'
function tmpDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-prompt-test-'))
}
describe('findParentInstance', () => {
const dirs: string[] = []
function makeTmp() {
const d = tmpDir()
dirs.push(d)
return d
}
afterEach(() => {
for (const d of dirs) fs.rmSync(d, { recursive: true, force: true })
dirs.length = 0
})
it('finds .openacp in parent directory', () => {
const root = makeTmp()
const instance = path.join(root, '.openacp')
fs.mkdirSync(instance)
const nested = path.join(root, 'project', 'src')
fs.mkdirSync(nested, { recursive: true })
expect(findParentInstance(nested, '/fake/global')).toBe(instance)
})
it('finds nearest parent when multiple exist', () => {
const root = makeTmp()
fs.mkdirSync(path.join(root, '.openacp'))
const child = path.join(root, 'workspace')
const childInstance = path.join(child, '.openacp')
fs.mkdirSync(childInstance, { recursive: true })
const nested = path.join(child, 'project', 'src')
fs.mkdirSync(nested, { recursive: true })
expect(findParentInstance(nested, '/fake/global')).toBe(childInstance)
})
it('skips global root', () => {
const root = makeTmp()
const instance = path.join(root, '.openacp')
fs.mkdirSync(instance)
const nested = path.join(root, 'src')
fs.mkdirSync(nested, { recursive: true })
// When the found instance IS the global root, skip it
expect(findParentInstance(nested, instance)).toBeNull()
})
it('returns null when no parent instance exists', () => {
const root = makeTmp()
const nested = path.join(root, 'deep', 'path')
fs.mkdirSync(nested, { recursive: true })
expect(findParentInstance(nested, '/fake/global')).toBeNull()
})
it('does not check exact CWD', () => {
const root = makeTmp()
// .openacp is at exact CWD, not parent
fs.mkdirSync(path.join(root, '.openacp'))
expect(findParentInstance(root, '/fake/global')).toBeNull()
})
})

View File

@ -1,6 +1,7 @@
import { readApiPort } from '../api-client.js'
import { wantsHelp } from './helpers.js'
import { isJsonMode, jsonSuccess, jsonError, muteForJson, ErrorCodes } from '../output.js'
import { resolveRunningInstance } from '../../core/instance/instance-context.js'
export async function cmdAdopt(args: string[]): Promise<void> {
if (wantsHelp(args)) {
@ -58,10 +59,11 @@ as a messaging thread. Requires a running daemon.
const channelIdx = args.indexOf("--channel");
const channel = channelIdx !== -1 && args[channelIdx + 1] ? args[channelIdx + 1] : undefined;
const port = readApiPort();
const instanceRoot = await resolveRunningInstance(cwd);
const port = instanceRoot ? readApiPort(undefined, instanceRoot) : null;
if (!port) {
if (json) jsonError(ErrorCodes.DAEMON_NOT_RUNNING, 'OpenACP is not running. Start it with: openacp start')
console.log("OpenACP is not running. Start it with: openacp start");
if (json) jsonError(ErrorCodes.DAEMON_NOT_RUNNING, 'No running OpenACP instance found. Start one with: openacp start')
console.log("No running OpenACP instance found. Start one with: openacp start");
process.exit(1);
}
@ -71,7 +73,7 @@ as a messaging thread. Requires a running daemon.
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ agent, agentSessionId: sessionId, cwd, channel }),
})
}, instanceRoot ?? undefined)
const data = await res.json() as Record<string, unknown>;
if (data.ok) {

View File

@ -18,12 +18,16 @@ export async function promptForInstance(opts: {
const cwd = process.cwd()
const localRoot = path.join(cwd, '.openacp')
// Nothing exists anywhere — go to global (setup wizard will handle first-time)
if (!globalConfigExists) return globalRoot
// Walk up from CWD to find nearest parent .openacp/
const detectedParent = findParentInstance(cwd, globalRoot)
// Non-interactive: default to global
// Nothing exists anywhere — go to global (setup wizard will handle first-time)
// But if a parent instance exists, prefer it
if (!globalConfigExists) return detectedParent ?? globalRoot
// Non-interactive: prefer detected parent over global
const isTTY = process.stdin.isTTY && process.stdout.isTTY
if (!isTTY) return globalRoot
if (!isTTY) return detectedParent ?? globalRoot
// Collect existing instances from registry
const registryPath = path.join(globalRoot, 'instances.json')
@ -32,18 +36,33 @@ export async function promptForInstance(opts: {
const instances = registry.list().filter(e => fs.existsSync(e.root))
// Format labels: "Name (global — path)" or "Name (local — path)"
const instanceOptions = instances.map(e => {
let name = e.id
const instanceOptions = instances
// Exclude detected parent — it will be added at the top separately
.filter(e => !detectedParent || e.root !== detectedParent)
.map(e => {
let name = e.id
try {
const raw = fs.readFileSync(path.join(e.root, 'config.json'), 'utf-8')
const parsed = JSON.parse(raw)
if (parsed.instanceName) name = parsed.instanceName
} catch { /* use id */ }
const isGlobal = e.root === globalRoot
const displayPath = e.root.replace(os.homedir(), '~')
const type = isGlobal ? 'global' : 'local'
return { value: e.root, label: `${name} workspace (${type} — ${displayPath})` }
})
// Prepend detected parent instance at the top
if (detectedParent) {
let name = path.basename(path.dirname(detectedParent))
try {
const raw = fs.readFileSync(path.join(e.root, 'config.json'), 'utf-8')
const raw = fs.readFileSync(path.join(detectedParent, 'config.json'), 'utf-8')
const parsed = JSON.parse(raw)
if (parsed.instanceName) name = parsed.instanceName
} catch { /* use id */ }
const isGlobal = e.root === globalRoot
const displayPath = e.root.replace(os.homedir(), '~')
const type = isGlobal ? 'global' : 'local'
return { value: e.root, label: `${name} workspace (${type} — ${displayPath})` }
})
} catch { /* use dir name */ }
const displayPath = detectedParent.replace(os.homedir(), '~')
instanceOptions.unshift({ value: detectedParent, label: `${name} workspace (detected — ${displayPath})` })
}
// Fallback if registry is empty but global config exists
if (instanceOptions.length === 0) {
@ -83,3 +102,20 @@ export async function promptForInstance(opts: {
return choice as string
}
/**
* Walk up from `cwd` looking for a parent directory containing `.openacp/`.
* Skips exact CWD (already handled by resolveInstanceRoot) and global root.
* Returns the `.openacp/` path if found, or null.
*/
export function findParentInstance(cwd: string, globalRoot: string): string | null {
let dir = path.dirname(cwd) // start from parent, not CWD itself
while (true) {
const candidate = path.join(dir, '.openacp')
if (candidate !== globalRoot && fs.existsSync(candidate)) return candidate
const parent = path.dirname(dir)
if (parent === dir) break
dir = parent
}
return null
}

View File

@ -283,6 +283,189 @@ describe("MessageTransformer - extended", () => {
});
});
describe("diffStats compatibility", () => {
it("extracts apply_patch diffStats from rawOutput.metadata.files", () => {
const event: AgentEvent = {
type: "tool_call",
id: "tc-apply-patch-files",
name: "apply_patch",
kind: "other",
status: "completed",
rawOutput: {
metadata: {
files: [
{ additions: 4, deletions: 1 },
{ additions: 3, deletions: 2 },
],
},
},
};
const result = transformer.transform(event);
expect(result.metadata?.diffStats).toEqual({ added: 7, removed: 3 });
});
it("extracts apply_patch diffStats from rawOutput.metadata additions/deletions", () => {
const event: AgentEvent = {
type: "tool_call",
id: "tc-apply-patch-direct",
name: "apply_patch",
kind: "other",
status: "completed",
rawOutput: {
metadata: {
additions: 19,
deletions: 7,
},
},
};
const result = transformer.transform(event);
expect(result.metadata?.diffStats).toEqual({ added: 19, removed: 7 });
});
it("keeps rawInput-derived diffStats when already available", () => {
const event: AgentEvent = {
type: "tool_call",
id: "tc-write-existing-diffstats",
name: "Write",
kind: "write",
status: "completed",
rawInput: {
old_string: "a\nb",
new_string: "a\nb\nc",
},
rawOutput: {
metadata: {
additions: 99,
deletions: 99,
},
},
};
const result = transformer.transform(event);
expect(result.metadata?.diffStats).toEqual({ added: 1, removed: 0 });
});
it("builds viewer links for apply_patch from rawOutput metadata files", () => {
const tunnelStore = {
storeFile: vi.fn().mockReturnValue("file-id"),
storeDiff: vi.fn().mockReturnValue("diff-id"),
};
const tunnelService = {
getPublicUrl: vi.fn().mockReturnValue("https://tunnel.example"),
getStore: vi.fn().mockReturnValue(tunnelStore),
fileUrl: vi.fn().mockReturnValue("https://tunnel.example/view/file-id"),
diffUrl: vi.fn().mockReturnValue("https://tunnel.example/diff/diff-id"),
} as any;
const t = new MessageTransformer(tunnelService);
const event: AgentEvent = {
type: "tool_call",
id: "tc-apply-patch-viewer",
name: "apply_patch",
kind: "other",
status: "completed",
rawOutput: {
metadata: {
files: [
{
filePath: "/ws/src/main.ts",
before: "const a = 1;",
after: "const a = 2;",
additions: 1,
deletions: 1,
},
],
},
},
};
const result = t.transform(event, { id: "sess-1", workingDirectory: "/ws" });
expect(result.metadata?.diffStats).toEqual({ added: 1, removed: 1 });
expect(result.metadata?.viewerLinks).toEqual({
file: "https://tunnel.example/view/file-id",
diff: "https://tunnel.example/diff/diff-id",
});
expect(result.metadata?.viewerFilePath).toBe("/ws/src/main.ts");
});
it("handles malformed apply_patch rawOutput safely", () => {
const event: AgentEvent = {
type: "tool_call",
id: "tc-apply-patch-malformed",
name: "apply_patch",
kind: "other",
status: "completed",
rawOutput: {
metadata: {
files: [null, { additions: "x", deletions: -1 }, { filePath: 123 }],
additions: "bad",
deletions: null,
},
},
};
const result = transformer.transform(event);
expect(result.metadata?.diffStats).toBeUndefined();
expect(result.metadata?.viewerLinks).toBeUndefined();
});
it("handles apply_patch tool_update without name using cached patchText", () => {
const tunnelStore = {
storeFile: vi.fn().mockReturnValue("file-id"),
storeDiff: vi.fn().mockReturnValue("diff-id"),
};
const tunnelService = {
getPublicUrl: vi.fn().mockReturnValue("https://tunnel.example"),
getStore: vi.fn().mockReturnValue(tunnelStore),
fileUrl: vi.fn().mockReturnValue("https://tunnel.example/view/file-id"),
diffUrl: vi.fn().mockReturnValue("https://tunnel.example/diff/diff-id"),
} as any;
const t = new MessageTransformer(tunnelService);
const callEvent: AgentEvent = {
type: "tool_call",
id: "tc-apply-patch-update",
name: "apply_patch",
kind: "other",
status: "running",
rawInput: {
patchText: "*** Begin Patch\n*** Update File: /ws/src/main.ts\n*** End Patch",
},
};
t.transform(callEvent, { id: "sess-1", workingDirectory: "/ws" });
const updateEvent: AgentEvent = {
type: "tool_update",
id: "tc-apply-patch-update",
kind: "other",
status: "completed",
rawOutput: {
metadata: {
files: [
{
filePath: "/ws/src/main.ts",
before: "const a = 1;",
after: "const a = 2;",
additions: 1,
deletions: 1,
},
],
},
},
};
const result = t.transform(updateEvent, { id: "sess-1", workingDirectory: "/ws" });
expect(result.metadata?.diffStats).toEqual({ added: 1, removed: 1 });
expect(result.metadata?.viewerLinks).toEqual({
file: "https://tunnel.example/view/file-id",
diff: "https://tunnel.example/diff/diff-id",
});
});
});
describe("enrichWithViewerLinks (tunnel integration)", () => {
it("does nothing without tunnelService", () => {
const event: AgentEvent = {

View File

@ -344,6 +344,8 @@ describe("DisplaySpecBuilder.buildToolSpec", () => {
});
const spec = builder.buildToolSpec(entry, "medium");
expect(spec.title).toBe("/repo/src/app.ts");
expect(spec.kind).toBe("edit");
expect(spec.icon).toBe("✏️");
});
it("todowrite title summarizes progress when kind is other", () => {

View File

@ -4,6 +4,7 @@ import { KIND_ICONS } from "./format-types.js";
import type { OutputMode, ViewerLinks } from "./format-types.js";
import type { ToolEntry } from "./stream-accumulator.js";
import type { TunnelServiceInterface } from "../plugin/types.js";
import { isApplyPatchOtherTool } from "../utils/apply-patch-detection.js";
// ─── Output spec interfaces ────────────────────────────────────────────────
@ -93,6 +94,22 @@ function buildTitle(entry: ToolEntry, kind: string): string {
const input = asRecord(entry.rawInput);
const nameLower = entry.name.toLowerCase();
// apply_patch: keep title parsing based on patchText even when we map display
// kind to "edit" for simpler icon/label compatibility.
if (isApplyPatchOtherTool(entry.kind, entry.name, entry.rawInput)) {
const patchText = getStringField(input, ["patchText", "patch_text"]);
if (patchText) {
const targets = parseApplyPatchTargets(patchText);
if (targets.length === 1) return targets[0];
if (targets.length > 1) {
const shown = targets.slice(0, 2).join(", ");
const rest = targets.length - 2;
return rest > 0 ? `${shown} (+${rest} more)` : shown;
}
}
return "apply_patch";
}
if (kind === "read") {
// Support both snake_case (Claude Code) and camelCase (OpenCode) field names
const filePath = getStringField(input, ["file_path", "filePath", "path"]);
@ -155,39 +172,6 @@ function buildTitle(entry: ToolEntry, kind: string): string {
return capitalize(entry.name);
}
// Fallbacks for tools that often come through with kind="other"
if (nameLower === "apply_patch") {
const patchText = getStringField(input, ["patchText", "patch_text"]);
if (patchText) {
const targets = parseApplyPatchTargets(patchText);
if (targets.length === 1) return targets[0];
if (targets.length > 1) {
const shown = targets.slice(0, 2).join(", ");
const remaining = targets.length - 2;
return remaining > 0 ? `${shown} (+${remaining} more)` : shown;
}
}
return "apply_patch";
}
if (nameLower === "todowrite") {
const todos = Array.isArray(input.todos) ? input.todos : [];
if (todos.length > 0) {
const inProgress = todos.filter((t) => {
if (!t || typeof t !== "object") return false;
const status = (t as Record<string, unknown>).status;
return status === "in_progress";
}).length;
const completed = todos.filter((t) => {
if (!t || typeof t !== "object") return false;
const status = (t as Record<string, unknown>).status;
return status === "completed";
}).length;
return `Todo list (${completed}/${todos.length} done${inProgress > 0 ? `, ${inProgress} active` : ""})`;
}
return "Todo list";
}
if (kind === "fetch" || kind === "web") {
const url = typeof input.url === "string" ? input.url : null;
if (url && url !== "undefined") return url.length > 60 ? url.slice(0, 57) + "..." : url;
@ -201,22 +185,6 @@ function buildTitle(entry: ToolEntry, kind: string): string {
return input.skill;
}
// apply_patch: well-known tool used by multiple agents (OpenCode, Codex, etc.)
// Extract target file paths from the patch text for a meaningful title.
if (nameLower === "apply_patch") {
const patchText = getStringField(input, ["patchText", "patch_text"]);
if (patchText) {
const targets = parseApplyPatchTargets(patchText);
if (targets.length === 1) return targets[0];
if (targets.length > 1) {
const shown = targets.slice(0, 2).join(", ");
const rest = targets.length - 2;
return rest > 0 ? `${shown} (+${rest} more)` : shown;
}
}
return "apply_patch";
}
// todowrite / TodoWrite: well-known todo list tool (Claude Code, others)
// Summarise progress so the card shows "Todo list (2/5 done, 1 active)"
// rather than just the bare tool name.
@ -261,7 +229,7 @@ export class DisplaySpecBuilder {
mode: OutputMode,
sessionContext?: { id: string; workingDirectory: string },
): ToolDisplaySpec {
const effectiveKind = entry.displayKind ?? entry.kind;
const effectiveKind = entry.displayKind ?? (isApplyPatchOtherTool(entry.kind, entry.name, entry.rawInput) ? "edit" : entry.kind);
const icon = KIND_ICONS[effectiveKind] ?? KIND_ICONS["other"] ?? "🛠️";
const title = buildTitle(entry, effectiveKind);
const isHidden = entry.isNoise && mode !== "high";

View File

@ -28,6 +28,7 @@ interface RegistryCache {
export class AgentCatalog {
private store: AgentStore;
private globalStore: AgentStore | null = null;
private registryAgents: RegistryAgent[] = [];
private cachePath: string;
private agentsDir: string | undefined;
@ -36,10 +37,18 @@ export class AgentCatalog {
this.store = store ?? new AgentStore();
this.cachePath = cachePath ?? path.join(os.homedir(), ".openacp", "registry-cache.json");
this.agentsDir = agentsDir;
// If the instance store is NOT the global one, load global as fallback
const globalPath = path.join(os.homedir(), ".openacp", "agents.json");
const storePath = this.store.filePath;
if (path.resolve(storePath) !== path.resolve(globalPath)) {
this.globalStore = new AgentStore(globalPath);
}
}
load(): void {
this.store.load();
this.globalStore?.load();
this.loadRegistryFromCacheOrSnapshot();
this.enrichInstalledFromRegistry();
}
@ -87,24 +96,25 @@ export class AgentCatalog {
return this.registryAgents.find((a) => getAgentAlias(a.id) === keyOrId);
}
// --- Installed ---
// --- Installed (instance-first, global-fallback) ---
getInstalled(): InstalledAgent[] {
return Object.values(this.store.getInstalled());
const merged = { ...this.globalStore?.getInstalled(), ...this.store.getInstalled() };
return Object.values(merged);
}
getInstalledEntries(): Record<string, InstalledAgent> {
return this.store.getInstalled();
return { ...this.globalStore?.getInstalled(), ...this.store.getInstalled() };
}
getInstalledAgent(key: string): InstalledAgent | undefined {
return this.store.getAgent(key);
return this.store.getAgent(key) ?? this.globalStore?.getAgent(key);
}
// --- Discovery ---
getAvailable(): AgentListItem[] {
const installed = this.store.getInstalled();
const installed = this.getInstalledEntries();
const items: AgentListItem[] = [];
const seenKeys = new Set<string>();
@ -200,17 +210,20 @@ export class AgentCatalog {
}
async uninstall(key: string): Promise<{ ok: boolean; error?: string }> {
if (!this.store.hasAgent(key)) {
return { ok: false, error: `"${key}" is not installed.` };
if (this.store.hasAgent(key)) {
await uninstallAgent(key, this.store);
return { ok: true };
}
await uninstallAgent(key, this.store);
return { ok: true };
if (this.globalStore?.getAgent(key)) {
return { ok: false, error: `"${key}" is installed globally. Uninstall it from the global instance instead.` };
}
return { ok: false, error: `"${key}" is not installed.` };
}
// --- Resolution (for AgentManager) ---
resolve(key: string): AgentDefinition | undefined {
const agent = this.store.getAgent(key);
const agent = this.store.getAgent(key) ?? this.globalStore?.getAgent(key);
if (!agent) return undefined;
return {
name: key,

View File

@ -100,16 +100,51 @@ function resolveAgentCommand(cmd: string): { command: string; args: string[] } {
try {
const fullPath = execFileSync("which", [cmd], { encoding: "utf-8" }).trim();
if (fullPath) {
const content = fs.readFileSync(fullPath, "utf-8");
if (content.startsWith("#!/usr/bin/env node")) {
return { command: process.execPath, args: [fullPath] };
try {
const content = fs.readFileSync(fullPath, "utf-8");
if (content.startsWith("#!/usr/bin/env node")) {
return { command: process.execPath, args: [fullPath] };
}
} catch {
// Binary file (not readable as utf-8) — use full path directly
}
// Found via PATH but not a node script — use the resolved full path
return { command: fullPath, args: [] };
}
} catch {
// which failed
// which failed — command not on PATH
}
// 4. Fallback: use command as-is
// 4. For npx/uvx: derive from the running Node's bin directory.
// When openacp is installed globally (e.g. via Homebrew or nvm), npx lives
// next to the same node binary that is executing this process. The user's
// shell PATH may not include that directory (common with nvm in non-interactive
// shells), so resolve it explicitly.
if (cmd === "npx" || cmd === "uvx") {
// Collect candidate directories: process.execPath, its realpath, and well-known locations
const seen = new Set<string>();
const candidates: string[] = [];
const addCandidate = (dir: string) => {
if (!seen.has(dir)) { seen.add(dir); candidates.push(dir); }
};
addCandidate(path.dirname(process.execPath));
try { addCandidate(path.dirname(fs.realpathSync(process.execPath))); } catch { /* ignore */ }
// Well-known Node.js install locations on macOS/Linux
addCandidate("/opt/homebrew/bin");
addCandidate("/usr/local/bin");
for (const dir of candidates) {
const candidate = path.join(dir, cmd);
if (fs.existsSync(candidate)) {
log.info({ cmd, resolved: candidate }, "Resolved package runner from fallback search");
return { command: candidate, args: [] };
}
}
log.warn({ cmd, execPath: process.execPath, candidates }, "Could not find package runner");
}
// 5. Fallback: use command as-is
return { command: cmd, args: [] };
}

View File

@ -29,7 +29,7 @@ type AgentStoreData = z.infer<typeof AgentStoreSchema>;
export class AgentStore {
private data: AgentStoreData = { version: 1, installed: {} };
private filePath: string;
readonly filePath: string;
constructor(filePath?: string) {
this.filePath = filePath ?? path.join(os.homedir(), ".openacp", "agents.json");

View File

@ -100,6 +100,7 @@ export class OpenACPCore {
ctx?.paths.agentsDir,
);
this.agentCatalog.load();
this.agentManager = new AgentManager(this.agentCatalog);
const storePath = ctx?.paths.sessions ?? path.join(os.homedir(), ".openacp", "sessions.json");
this.sessionStore = new JsonFileSessionStore(

View File

@ -0,0 +1,132 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { resolveRunningInstance } from '../instance-context.js'
// Mock fetch for health checks
const mockFetch = vi.fn()
vi.stubGlobal('fetch', mockFetch)
function tmpDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'openacp-test-'))
}
function createInstanceDir(root: string, port?: number) {
const dir = path.join(root, '.openacp')
fs.mkdirSync(dir, { recursive: true })
if (port !== undefined) {
fs.writeFileSync(path.join(dir, 'api.port'), String(port))
}
return dir
}
function mockHealthy(port: number) {
mockFetch.mockImplementation((url: string, _opts?: RequestInit) => {
if (url === `http://127.0.0.1:${port}/api/v1/system/health`) {
return Promise.resolve({ ok: true })
}
return Promise.reject(new Error('Connection refused'))
})
}
function mockMultiHealthy(ports: number[]) {
const portSet = new Set(ports)
mockFetch.mockImplementation((url: string, _opts?: RequestInit) => {
for (const port of portSet) {
if (url === `http://127.0.0.1:${port}/api/v1/system/health`) {
return Promise.resolve({ ok: true })
}
}
return Promise.reject(new Error('Connection refused'))
})
}
describe('resolveRunningInstance', () => {
let tmpRoot: string
beforeEach(() => {
tmpRoot = tmpDir()
mockFetch.mockReset()
})
afterEach(() => {
fs.rmSync(tmpRoot, { recursive: true, force: true })
})
it('finds instance in exact cwd', async () => {
createInstanceDir(tmpRoot, 21420)
mockHealthy(21420)
const result = await resolveRunningInstance(tmpRoot)
expect(result).toBe(path.join(tmpRoot, '.openacp'))
})
it('walks up to find instance in parent directory', async () => {
createInstanceDir(tmpRoot, 21420)
mockHealthy(21420)
const nested = path.join(tmpRoot, 'project', 'src', 'core')
fs.mkdirSync(nested, { recursive: true })
const result = await resolveRunningInstance(nested)
expect(result).toBe(path.join(tmpRoot, '.openacp'))
})
it('skips dead instances and continues walking up', async () => {
// Parent has running instance on port 21420
createInstanceDir(tmpRoot, 21420)
// Child has dead instance (port file but not running)
const child = path.join(tmpRoot, 'project')
createInstanceDir(child, 99999)
mockHealthy(21420) // only parent is healthy
const nested = path.join(child, 'src')
fs.mkdirSync(nested, { recursive: true })
const result = await resolveRunningInstance(nested)
expect(result).toBe(path.join(tmpRoot, '.openacp'))
})
it('skips instance with no port file', async () => {
createInstanceDir(tmpRoot, 21420)
mockHealthy(21420)
const child = path.join(tmpRoot, 'project')
// Create .openacp dir without port file
fs.mkdirSync(path.join(child, '.openacp'), { recursive: true })
const result = await resolveRunningInstance(path.join(child, 'src'))
// Should skip child (no port) and find parent
expect(result).toBe(path.join(tmpRoot, '.openacp'))
})
it('nearest running instance wins over parent', async () => {
createInstanceDir(tmpRoot, 21420)
const child = path.join(tmpRoot, 'project')
createInstanceDir(child, 21421)
mockMultiHealthy([21420, 21421])
const result = await resolveRunningInstance(path.join(child, 'src'))
expect(result).toBe(path.join(child, '.openacp'))
})
it('returns null when no instance is running', async () => {
mockFetch.mockRejectedValue(new Error('Connection refused'))
const result = await resolveRunningInstance(tmpRoot)
expect(result).toBeNull()
})
it('returns null for empty directory tree', async () => {
mockFetch.mockRejectedValue(new Error('Connection refused'))
const empty = path.join(tmpRoot, 'empty', 'deep', 'path')
fs.mkdirSync(empty, { recursive: true })
const result = await resolveRunningInstance(empty)
expect(result).toBeNull()
})
})

View File

@ -89,3 +89,48 @@ export function resolveInstanceRoot(opts: ResolveOpts): string | null {
export function getGlobalRoot(): string {
return path.join(os.homedir(), '.openacp')
}
/**
* Walk up directory tree from `cwd` looking for a running `.openacp/` instance.
* Skips instances that exist but aren't running (dead daemon).
* Falls back to global `~/.openacp/` if no local instance found.
* Returns the instance root path, or null if nothing is running.
*/
export async function resolveRunningInstance(cwd: string): Promise<string | null> {
const globalRoot = getGlobalRoot()
let dir = path.resolve(cwd)
while (true) {
const candidate = path.join(dir, '.openacp')
// Skip global root during walk-up — checked as fallback at the end
if (candidate !== globalRoot && fs.existsSync(candidate)) {
if (await isInstanceRunning(candidate)) return candidate
}
const parent = path.dirname(dir)
if (parent === dir) break // filesystem root
dir = parent
}
// Fallback: global instance
if (fs.existsSync(globalRoot) && await isInstanceRunning(globalRoot)) return globalRoot
return null
}
async function isInstanceRunning(instanceRoot: string): Promise<boolean> {
const portFile = path.join(instanceRoot, 'api.port')
try {
const content = fs.readFileSync(portFile, 'utf-8').trim()
const port = parseInt(content, 10)
if (isNaN(port)) return false
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 2000)
const res = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`, {
signal: controller.signal,
})
clearTimeout(timeout)
return res.ok
} catch {
return false
}
}

View File

@ -2,6 +2,7 @@ import * as path from "node:path";
import type { AgentEvent, OutgoingMessage } from "./types.js";
import type { TunnelServiceInterface } from "./plugin/types.js";
import { extractFileInfo } from "./utils/extract-file-info.js";
import { isApplyPatchOtherTool } from "./utils/apply-patch-detection.js";
import { createChildLogger } from "./utils/log.js";
const log = createChildLogger({ module: "message-transformer" });
@ -46,6 +47,93 @@ function computeLineDiff(oldStr: string, newStr: string): { added: number; remov
};
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function asNonNegativeNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
}
/**
* OpenCode ACP apply_patch may include diff counts in rawOutput.metadata:
* - metadata.files[].additions/deletions
* - metadata.additions/deletions
*/
function extractDiffStatsFromRawOutput(rawOutput: unknown): { added: number; removed: number } | null {
const output = asRecord(rawOutput);
const metadata = asRecord(output?.metadata);
if (!metadata) return null;
const files = Array.isArray(metadata.files) ? metadata.files : null;
if (files && files.length > 0) {
let added = 0;
let removed = 0;
let hasAny = false;
for (const file of files) {
const fileMeta = asRecord(file);
if (!fileMeta) continue;
const fileAdded = asNonNegativeNumber(fileMeta.additions);
const fileRemoved = asNonNegativeNumber(fileMeta.deletions);
if (fileAdded === null && fileRemoved === null) continue;
added += fileAdded ?? 0;
removed += fileRemoved ?? 0;
hasAny = true;
}
if (hasAny && (added > 0 || removed > 0)) return { added, removed };
}
const added = asNonNegativeNumber(metadata.additions);
const removed = asNonNegativeNumber(metadata.deletions);
if (added === null && removed === null) return null;
if ((added ?? 0) === 0 && (removed ?? 0) === 0) return null;
return {
added: added ?? 0,
removed: removed ?? 0,
};
}
function extractDiffStatsFromToolPayload(
name: string,
kind: string | undefined,
rawInput: unknown,
rawOutput: unknown,
): { added: number; removed: number } | null {
if (kind === "edit" || kind === "write") {
const ri = asRecord(rawInput);
if (!ri) return null;
const oldStr = typeof ri.old_string === "string" ? ri.old_string : typeof ri.oldText === "string" ? ri.oldText : null;
const newStr = typeof ri.new_string === "string" ? ri.new_string : typeof ri.newText === "string" ? ri.newText : typeof ri.content === "string" ? ri.content : null;
if (oldStr !== null && newStr !== null) {
const stats = computeLineDiff(oldStr, newStr);
return stats.added > 0 || stats.removed > 0 ? stats : null;
}
if (oldStr === null && newStr !== null && kind === "write") {
// New file creation — no old content, count all new lines as added
const added = newStr.split("\n").length;
return added > 0 ? { added, removed: 0 } : null;
}
return null;
}
if (isApplyPatchOtherTool(kind, name, rawInput)) {
return extractDiffStatsFromRawOutput(rawOutput);
}
return null;
}
export class MessageTransformer {
tunnelService?: TunnelServiceInterface;
/** Cache rawInput from tool_call so it's available in tool_update (which often lacks it) */
@ -218,24 +306,13 @@ export class MessageTransformer {
metadata: Record<string, unknown>,
sessionContext?: { id: string; workingDirectory: string },
): void {
// Compute diffStats from rawInput even without tunnelService
const name = "name" in event ? event.name || "" : "";
// Compute diffStats from tool payload even without tunnelService.
// Includes edit/write rawInput and apply_patch rawOutput compatibility.
const kind = "kind" in event ? event.kind : undefined;
if (!metadata.diffStats && (kind === "edit" || kind === "write")) {
const ri = event.rawInput as Record<string, unknown> | undefined;
if (ri) {
const oldStr = typeof ri.old_string === "string" ? ri.old_string : typeof ri.oldText === "string" ? ri.oldText : null;
const newStr = typeof ri.new_string === "string" ? ri.new_string : typeof ri.newText === "string" ? ri.newText : typeof ri.content === "string" ? ri.content : null;
if (oldStr !== null && newStr !== null) {
const stats = computeLineDiff(oldStr, newStr);
if (stats.added > 0 || stats.removed > 0) {
metadata.diffStats = stats;
}
} else if (oldStr === null && newStr !== null && kind === "write") {
// New file creation — no old content, count all new lines as added
const added = newStr.split("\n").length;
if (added > 0) metadata.diffStats = { added, removed: 0 };
}
}
if (!metadata.diffStats) {
const stats = extractDiffStatsFromToolPayload(name, kind, event.rawInput, event.rawOutput);
if (stats) metadata.diffStats = stats;
}
if (!this.tunnelService || !sessionContext) {
@ -246,8 +323,6 @@ export class MessageTransformer {
return;
}
const name = "name" in event ? event.name || "" : "";
log.debug(
{ name, kind, status: event.status, hasContent: !!event.content, hasRawInput: !!event.rawInput },
"enrichWithViewerLinks: inspecting event",
@ -259,6 +334,7 @@ export class MessageTransformer {
event.content,
event.rawInput,
event.meta,
event.rawOutput,
);
if (!fileInfo) {
log.debug(

View File

@ -0,0 +1,16 @@
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
export function hasApplyPatchPatchText(rawInput: unknown): boolean {
const input = asRecord(rawInput);
return !!input && (typeof input.patchText === "string" || typeof input.patch_text === "string");
}
export function isApplyPatchOtherTool(kind: string | undefined, name: string, rawInput: unknown): boolean {
if (kind !== "other") return false;
if (name.toLowerCase() === "apply_patch") return true;
return hasApplyPatchPatchText(rawInput);
}

View File

@ -1,3 +1,5 @@
import { isApplyPatchOtherTool } from './apply-patch-detection.js'
export interface FileInfo {
filePath: string
content: string
@ -12,6 +14,7 @@ export interface FileInfo {
* - Content wrapper: [{ type: "content", content: { type: "text", text: "..." } }]
* - Text block: { type: "text", text: "..." }
* - rawInput: { file_path: "...", content: "..." }
* - rawOutput (OpenCode apply_patch): { metadata: { files: [{ filePath, before, after }] } }
*/
export function extractFileInfo(
name: string,
@ -19,8 +22,12 @@ export function extractFileInfo(
content: unknown,
rawInput?: unknown,
meta?: unknown,
rawOutput?: unknown,
): FileInfo | null {
// Only process file-related tool kinds
if (isApplyPatchOtherTool(kind, name, rawInput)) {
return parseApplyPatchRawOutput(rawOutput)
}
if (kind && !['read', 'edit', 'write'].includes(kind)) return null
let info: Partial<FileInfo> | null = null
@ -100,6 +107,51 @@ export function extractFileInfo(
return info as FileInfo
}
function parseApplyPatchRawOutput(rawOutput: unknown): FileInfo | null {
if (!rawOutput || typeof rawOutput !== 'object' || Array.isArray(rawOutput)) return null
const output = rawOutput as Record<string, unknown>
const metadata = output.metadata
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return null
const files = (metadata as Record<string, unknown>).files
if (!Array.isArray(files)) return null
const sortedFiles = [...files].sort((a, b) => getApplyPatchFileScore(b) - getApplyPatchFileScore(a))
for (const file of sortedFiles) {
if (!file || typeof file !== 'object' || Array.isArray(file)) continue
const f = file as Record<string, unknown>
const filePath = typeof f.filePath === 'string'
? f.filePath
: typeof f.relativePath === 'string'
? f.relativePath
: null
if (!filePath) continue
const after = typeof f.after === 'string' ? f.after : null
if (!after) continue
const before = typeof f.before === 'string' ? f.before : undefined
return {
filePath,
content: after,
oldContent: before,
}
}
return null
}
function getApplyPatchFileScore(file: unknown): number {
if (!file || typeof file !== 'object' || Array.isArray(file)) return 0
const f = file as Record<string, unknown>
const additions = typeof f.additions === 'number' && Number.isFinite(f.additions) && f.additions >= 0 ? f.additions : 0
const deletions = typeof f.deletions === 'number' && Number.isFinite(f.deletions) && f.deletions >= 0 ? f.deletions : 0
return additions + deletions
}
/**
* Resolve toolResponse from agent-specific _meta namespaces.
* Supports: _meta.claudeCode.toolResponse (Claude Code)

View File

@ -251,3 +251,128 @@ describe('OpenACPTunnelProvider', () => {
await expect(provider.start(3100)).rejects.toThrow('429')
})
})
describe('OpenACPTunnelProvider — preserveState', () => {
let storage: ReturnType<typeof makeStorage>
let fetchMock: ReturnType<typeof vi.fn>
beforeEach(() => {
storage = makeStorage()
fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
vi.useFakeTimers()
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
it('stop(true, true) kills process but does NOT delete from worker or clear storage', async () => {
const saved = { '3100': { tunnelId: 'cf-ps', token: 'tok-ps', publicUrl: 'https://ps.tunnel.openacp.ai' } }
storage = makeStorage({ 'openacp-tunnels': saved })
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
await vi.advanceTimersByTimeAsync(15_001)
await startPromise
await provider.stop(true, true)
expect(proc.kill).toHaveBeenCalledWith('SIGKILL')
const deleteCalls = fetchMock.mock.calls.filter(
([url, init]: [any, any]) => init?.method === 'DELETE'
)
expect(deleteCalls.length).toBe(0)
const state = await storage.get<Record<string, unknown>>('openacp-tunnels')
expect(state).toEqual(saved)
})
it('stop(false, false) still deletes from worker and clears storage (default behavior)', async () => {
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock
.mockResolvedValueOnce({ ok: true, json: async () => ({ tunnelId: 'cf-del', token: 'tok-del', publicUrl: 'https://del.tunnel.openacp.ai' }) })
.mockResolvedValue({ ok: true, json: async () => ({}) })
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
await vi.advanceTimersByTimeAsync(15_001)
await startPromise
await provider.stop()
const deleteCalls = fetchMock.mock.calls.filter(
([url, init]: [any, any]) => String(url).includes('/tunnel/cf-del') && init?.method === 'DELETE'
)
expect(deleteCalls.length).toBe(1)
expect(storage.set).toHaveBeenLastCalledWith('openacp-tunnels', {})
})
})
describe('OpenACPTunnelProvider — fast startup via stderr', () => {
let storage: ReturnType<typeof makeStorage>
let fetchMock: ReturnType<typeof vi.fn>
beforeEach(() => {
storage = makeStorage()
fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
vi.useFakeTimers()
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
it('resolves immediately when cloudflared logs "Registered tunnel connection"', async () => {
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ tunnelId: 'cf-fast', token: 'tok-fast', publicUrl: 'https://fast.tunnel.openacp.ai' }),
})
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
// Simulate cloudflared printing connection message after 2 seconds
await vi.advanceTimersByTimeAsync(2_000)
proc.stderr.emit('data', Buffer.from('2025-01-01T00:00:00Z INF Registered tunnel connection connIndex=0 connection=abc location=AMS protocol=quic\n'))
// Should resolve without needing to wait 15s
const url = await startPromise
expect(url).toBe('https://fast.tunnel.openacp.ai')
})
it('still falls back to timeout when no connection message received', async () => {
const proc = makeProcess()
vi.mocked(spawn).mockReturnValue(proc as any)
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ tunnelId: 'cf-slow', token: 'tok-slow', publicUrl: 'https://slow.tunnel.openacp.ai' }),
})
const provider = new OpenACPTunnelProvider({}, '/mock/bin', storage)
const startPromise = provider.start(3100)
// Emit some unrelated log output
proc.stderr.emit('data', Buffer.from('INF Starting tunnel\n'))
// Wait for timeout
await vi.advanceTimersByTimeAsync(15_001)
const url = await startPromise
expect(url).toBe('https://slow.tunnel.openacp.ai')
})
})

View File

@ -495,4 +495,127 @@ describe('TunnelRegistry — restore', () => {
await registry.restore()
expect(registry.list(true)).toHaveLength(0)
})
it('restores multiple user tunnels in parallel (not sequentially)', async () => {
const persisted = [
{ port: 3200, type: 'user', provider: 'cloudflare', label: 'app-a', createdAt: new Date().toISOString() },
{ port: 3300, type: 'user', provider: 'cloudflare', label: 'app-b', createdAt: new Date().toISOString() },
{ port: 3400, type: 'user', provider: 'cloudflare', label: 'app-c', createdAt: new Date().toISOString() },
]
vi.mocked(fs.existsSync).mockReturnValue(true)
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(persisted))
// Track the order of start() calls — all should be called before any resolves
const startOrder: number[] = []
let resolvers: Array<(url: string) => void> = []
vi.mocked(CloudflareTunnelProvider).mockImplementation(function (this: any) {
const mock = createMockProvider()
mock.start = vi.fn().mockImplementation((port: number) => {
startOrder.push(port)
return new Promise<string>(resolve => { resolvers.push(resolve) })
})
return mock as any
})
const registry = new TunnelRegistry()
const restorePromise = registry.restore()
// All 3 starts should have been called concurrently
await vi.advanceTimersByTimeAsync(0)
expect(startOrder).toHaveLength(3)
expect(startOrder).toEqual([3200, 3300, 3400])
// Resolve them
resolvers.forEach(r => r('https://test.trycloudflare.com'))
await restorePromise
expect(registry.list(false)).toHaveLength(3)
// Restore default mock so subsequent tests aren't affected
vi.mocked(CloudflareTunnelProvider).mockImplementation(function (this: any) {
return createProviderFromOverrideOrDefault()
})
})
it('restores user tunnels without sessionId (sessions do not survive restart)', async () => {
const persisted = [
{ port: 3200, type: 'user', provider: 'cloudflare', label: 'my-app', sessionId: 'sess-old', createdAt: new Date().toISOString() },
]
vi.mocked(fs.existsSync).mockReturnValue(true)
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(persisted))
const registry = new TunnelRegistry()
await registry.restore()
const restored = registry.list(false)
expect(restored).toHaveLength(1)
expect(restored[0].label).toBe('my-app')
expect(restored[0].sessionId).toBeUndefined()
})
})
describe('TunnelRegistry — shutdown persistence', () => {
beforeEach(() => {
vi.useFakeTimers()
mockProviderInstances = []
nextMockOverride = null
})
afterEach(() => {
vi.useRealTimers()
})
it('shutdown passes preserveState=true to providers', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'system', provider: 'cloudflare' })
await registry.add(3200, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
for (const mock of mockProviderInstances) {
expect(mock.stop).toHaveBeenCalledWith(true, true)
}
})
it('shutdown persists entries to tunnels.json before clearing', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'system', provider: 'cloudflare' })
await registry.add(3200, { type: 'user', provider: 'cloudflare', label: 'my-app' })
await registry.shutdown()
const writeCalls = vi.mocked(fs.writeFileSync).mock.calls
const lastWrite = writeCalls[writeCalls.length - 1]
const persisted = JSON.parse(lastWrite[1] as string) as Array<{ port: number; type: string }>
expect(persisted).toHaveLength(2)
expect(persisted.map(e => e.port).sort()).toEqual([3100, 3200])
})
it('flush() is a no-op after shutdown (does not overwrite with empty)', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
const writeCountAfterShutdown = vi.mocked(fs.writeFileSync).mock.calls.length
registry.flush()
expect(vi.mocked(fs.writeFileSync).mock.calls.length).toBe(writeCountAfterShutdown)
})
it('double shutdown does not overwrite preserved tunnels.json', async () => {
const registry = new TunnelRegistry()
await registry.add(3100, { type: 'user', provider: 'cloudflare' })
await registry.shutdown()
const writeCountAfterFirst = vi.mocked(fs.writeFileSync).mock.calls.length
await registry.shutdown()
expect(vi.mocked(fs.writeFileSync).mock.calls.length).toBe(writeCountAfterFirst)
})
})

View File

@ -1,7 +1,8 @@
export interface TunnelProvider {
start(localPort: number): Promise<string> // returns public URL
/** Stop the tunnel. When force=true, skip graceful shutdown and SIGKILL immediately. */
stop(force?: boolean): Promise<void>
/** Stop the tunnel. When force=true, skip graceful shutdown and SIGKILL immediately.
* When preserveState=true, keep tunnel alive on remote (don't delete from worker/storage) for reconnect on restart. */
stop(force?: boolean, preserveState?: boolean): Promise<void>
getPublicUrl(): string
/** Register a callback invoked when the tunnel process exits unexpectedly after establishment. */
onExit(callback: (code: number | null) => void): void

View File

@ -78,7 +78,7 @@ export class OpenACPTunnelProvider implements TunnelProvider {
return this.publicUrl
}
async stop(force = false): Promise<void> {
async stop(force = false, preserveState = false): Promise<void> {
this.stopHeartbeat()
const child = this.child
@ -100,7 +100,7 @@ export class OpenACPTunnelProvider implements TunnelProvider {
}
}
if (tunnelId) {
if (tunnelId && !preserveState) {
this.deleteFromWorker(tunnelId).catch(err => {
log.warn({ err: (err as Error).message }, 'Failed to delete tunnel from worker')
})
@ -110,7 +110,7 @@ export class OpenACPTunnelProvider implements TunnelProvider {
await this.storage.set(STORAGE_KEY, all)
}
log.info({ localPort }, 'OpenACP tunnel stopped')
log.info({ localPort, preserveState }, 'OpenACP tunnel stopped')
}
getPublicUrl(): string {
@ -166,6 +166,17 @@ export class OpenACPTunnelProvider implements TunnelProvider {
this.child = child
const onData = (data: Buffer): void => {
const line = data.toString()
if (/Registered tunnel connection/.test(line)) {
clearTimeout(timeout)
log.info({ port }, 'cloudflared connection registered')
settle(resolve)
}
}
child.stdout?.on('data', onData)
child.stderr?.on('data', onData)
child.on('error', (err) => {
clearTimeout(timeout)
settle(() => reject(new Error(`cloudflared failed to start: ${err.message}`)))

View File

@ -264,19 +264,29 @@ export class TunnelRegistry {
}
async shutdown(): Promise<void> {
if (this.shuttingDown) return
this.keepalive.stop()
this.shuttingDown = true
// Cancel any pending save timers
if (this.saveTimeout) {
clearTimeout(this.saveTimeout)
this.saveTimeout = null
}
const stopPromises: Promise<void>[] = []
for (const [, live] of this.entries) {
if (live.retryTimer) clearTimeout(live.retryTimer)
if (live.process) {
stopPromises.push(live.process.stop(true).catch(() => { /* ignore */ }))
stopPromises.push(live.process.stop(true, true).catch(() => { /* ignore */ }))
}
}
await Promise.all(stopPromises)
// Persist current state so tunnels can reconnect on next startup
this.save()
this.entries.clear()
this.scheduleSave()
}
list(includeSystem = false): TunnelEntry[] {
@ -309,16 +319,21 @@ export class TunnelRegistry {
// Only restore user tunnels — system tunnel is registered separately by TunnelService.start()
const userEntries = raw.filter(e => e.type === 'user')
for (const persisted of userEntries) {
try {
await this.add(persisted.port, {
const results = await Promise.allSettled(
userEntries.map(persisted =>
this.add(persisted.port, {
type: persisted.type,
provider: persisted.provider,
label: persisted.label,
sessionId: persisted.sessionId,
// sessionId intentionally omitted — sessions don't survive restart
})
} catch (err) {
log.warn({ port: persisted.port, err: (err as Error).message }, 'Failed to restore tunnel')
)
)
for (let i = 0; i < results.length; i++) {
if (results[i].status === 'rejected') {
const reason = (results[i] as PromiseRejectedResult).reason as Error
log.warn({ port: userEntries[i].port, err: reason.message }, 'Failed to restore tunnel')
}
}
} catch (err) {
@ -381,6 +396,8 @@ export class TunnelRegistry {
clearTimeout(this.saveTimeout)
this.saveTimeout = null
}
this.save()
if (!this.shuttingDown) {
this.save()
}
}
}