Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Add harness package updates with rollback and Store actions

Deecae9778557f7
diff --git a/cli/scripts/smoke-dsh-updates.ts b/cli/scripts/smoke-dsh-updates.ts
new file mode 100644
index 000000000..b993b47a3
--- /dev/null
+++ b/cli/scripts/smoke-dsh-updates.ts
@@ -0,0 +1,117 @@
+/** Desktop → real websocket/daemon → git/setup/doctor → existing workspace/viewer.
+ * Only runs against the explicit temporary profile passed by store_update_e2e_test.dart. */
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { WebSocketServer } from 'ws'
+import { BackendSocket } from '../src/backendSocket.js'
+import { env } from '../src/config/env.js'
+import { mutateDsh } from '../src/dsh/service.js'
+import { installedDsh, readInstalledIndex } from '../src/dsh/installed.js'
+import { materializeWorkspace } from '../src/dsh/materialize.js'
+import { resetBundledDshRegistry } from '../src/dsh/registry.js'
+import { DshViewerManager } from '../src/dsh/viewer.js'
+
+const root = process.argv[2]
+if (process.env.HARNESS_DSH_UPDATE_SMOKE !== '1' || !root ||
+ env.DSH_DIR !== join(resolve(root), 'installed') || env.ADAPTER_DATA_DIR !== join(resolve(root), 'data')) {
+ throw new Error('An explicit, isolated update test profile is required')
+}
+const repo = join(root, 'repo')
+const workspace = join(root, 'workspace')
+const packagePath = 'store/agents/thing'
+const viewerPath = 'store/viewers/pane'
+const id = 'acme/thing'
+const viewerId = 'acme/pane'
+const write = (name: string, body: string): void => {
+ const file = join(repo, name)
+ mkdirSync(join(file, '..'), { recursive: true })
+ writeFileSync(file, body, { mode: name.endsWith('.sh') ? 0o755 : 0o644 })
+}
+const git = (...args: string[]): string => execFileSync('git', ['-C', repo, ...args], {
+ encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_NAME: 'test', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'test', GIT_COMMITTER_EMAIL: '[email protected]' },
+}).trim()
+const shell = join(root, 'test-shell')
+writeFileSync(shell, '#!/bin/sh\nexec /bin/sh -c "$2"\n', { mode: 0o755 })
+process.env.SHELL = shell
+write(`${packagePath}/harness.json`, JSON.stringify({ spec: 1, id, name: 'Update smoke', engine: 'claude',
+ agent: { instructions: 'AGENTS.md', skills: ['skills'] }, workspace: { template: 'template', marker: 'project.txt' },
+ viewer: { use: viewerId }, toolchain: { setup: './setup.sh', doctor: './doctor.sh' } }))
+write(`${packagePath}/AGENTS.md`, 'original instructions')
+write(`${packagePath}/skills/task/SKILL.md`, 'skill version 1')
+write(`${packagePath}/template/project.txt`, 'starter')
+write(`${packagePath}/setup.sh`, '#!/bin/sh\nprintf "%s" "$HARNESS_DSH_DIR" > setup-path\nsleep 0.4\necho "ok setup"\n')
+write(`${packagePath}/doctor.sh`, '#!/bin/sh\ntest -f setup-path\n')
+write(`${viewerPath}/harness.json`, JSON.stringify({ spec: 1, kind: 'viewer', id: viewerId, name: 'Smoke viewer',
+ viewer: { command: './viewer.sh', url: 'http://127.0.0.1:${port}/' } }))
+write(`${viewerPath}/viewer.sh`, `#!/bin/sh\nexec '${process.execPath}' server.mjs\n`)
+write(`${viewerPath}/server.mjs`, `import {createServer} from 'node:http'; import {readFileSync} from 'node:fs';
+createServer((req,res)=>res.end(readFileSync(process.env.HARNESS_WORKSPACE+'/project.txt'))).listen(Number(process.env.HARNESS_VIEWER_PORT),'127.0.0.1');\n`)
+git('init', '-q', '-b', 'main')
+let version = 0
+function publish(fail = false, viewerOnly = false): string {
+ version++
+ if (viewerOnly) write(`${viewerPath}/release.txt`, `viewer ${version}`)
+ else {
+ write(`${packagePath}/skills/task/SKILL.md`, `skill version ${version}`)
+ write(`${packagePath}/doctor.sh`, `#!/bin/sh\ntest -f setup-path || exit 1\necho "${fail ? 'miss broken release' : 'ok ready'}"\nexit ${fail ? 1 : 0}\n`)
+ }
+ git('add', '-A'); git('commit', '-qm', `release ${version}`)
+ const ref = git('rev-parse', 'HEAD')
+ Object.assign(globalThis, { __DSH_REGISTRY__: JSON.stringify([
+ { id, name: 'Update smoke', engine: 'claude', repo, ref, path: packagePath, revision: git('rev-parse', `HEAD:${packagePath}`) },
+ { id: viewerId, name: 'Smoke viewer', kind: 'viewer', repo, ref, path: viewerPath, revision: git('rev-parse', `HEAD:${viewerPath}`) },
+ ]) })
+ resetBundledDshRegistry()
+ return ref
+}
+publish()
+const installed = await mutateDsh({ id }, () => {})
+if (!installed.ok) throw new Error(installed.detail)
+mkdirSync(workspace)
+await materializeWorkspace(installedDsh(id)!, workspace)
+writeFileSync(join(workspace, 'project.txt'), 'my finished project')
+writeFileSync(join(workspace, 'AGENTS.md'), 'my custom instructions')
+writeFileSync(join(workspace, '.harness', 'verdict.json'), '{"ready":true,"summary":"finished"}')
+publish(true)
+let viewerUrl: string | null = null
+const viewers = new DshViewerManager({ onUrl: (_, url) => { viewerUrl = url } })
+await viewers.start('smoke-agent', installedDsh(id)!, workspace)
+const backend = new BackendSocket('fixture-token')
+backend.onDshInstall = (input, progress) => mutateDsh(input, progress)
+backend.onDshUpdate = (packageId, progress) => mutateDsh({ id: packageId, update: true }, progress)
+const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
+await new Promise<void>(done => server.once('listening', done))
+let sequence = 0
+server.on('connection', socket => {
+ const client = `local:update-smoke-${++sequence}`
+ backend.registerLocalClient(client, { sendFrame: frame => { socket.send(JSON.stringify(frame)); return true }, sendBinary: () => true })
+ socket.on('close', () => { void backend.unregisterLocalClient(client) })
+ socket.on('message', async raw => {
+ const frame = JSON.parse(raw.toString())
+ if (frame.type === 'machine_select') {
+ socket.send(JSON.stringify({ type: 'connected', payload: { machineId: 'm' } })); return
+ }
+ if (frame.type === 'smoke_publish') {
+ const ref = publish(frame.payload.fail === true, frame.payload.viewerOnly === true)
+ socket.send(JSON.stringify({ type: 'smoke_publish_result', payload: { requestId: frame.payload.requestId, ref } })); return
+ }
+ if (frame.type === 'smoke_reopen') {
+ await viewers.stopAll()
+ await materializeWorkspace(installedDsh(id)!, workspace)
+ await viewers.start('smoke-agent', installedDsh(id)!, workspace)
+ const preview = viewerUrl ? await (await fetch(viewerUrl)).text() : null
+ socket.send(JSON.stringify({ type: 'smoke_reopen_result', payload: { requestId: frame.payload.requestId, preview,
+ instructions: readFileSync(join(workspace, 'AGENTS.md'), 'utf8'),
+ skill: readFileSync(join(workspace, '.claude', 'skills', 'task', 'SKILL.md'), 'utf8'),
+ verdict: JSON.parse(readFileSync(join(workspace, '.harness', 'verdict.json'), 'utf8')), installed: readInstalledIndex() } })); return
+ }
+ if (frame.type === 'engines_probe') {
+ socket.send(JSON.stringify({ type: 'engines_probe_result', payload: { requestId: frame.payload.requestId, engines: [] } })); return
+ }
+ backend.handleLocalFrame(client, frame)
+ })
+})
+console.log(JSON.stringify({ port: (server.address() as { port: number }).port }))
+process.stdin.resume()
+process.stdin.on('end', () => { void viewers.stopAll().then(() => process.exit(0)) })
diff --git a/cli/src/backendSocket.dsh.spec.ts b/cli/src/backendSocket.dsh.spec.ts
index 4d8c72cc8..76fe8cf35 100644
--- a/cli/src/backendSocket.dsh.spec.ts
+++ b/cli/src/backendSocket.dsh.spec.ts
@@ -56,9 +56,39 @@ describe('the DSH requests on the local socket', () => {
it('dsh_remove and dsh_install are refused on a daemon that cannot do them', async () => {
ask('dsh_remove', { requestId: 'rm-1', id: 'acme/thing' })
ask('dsh_install', { requestId: 'in-1', id: 'acme/thing' })
+ ask('dsh_update', { requestId: 'up-1', id: 'acme/thing' })
await vi.waitFor(() => expect(replies('dsh_install')).toHaveLength(1))
expect(replies('dsh_remove')).toEqual([expect.objectContaining({ requestId: 'rm-1', error: 'UNSUPPORTED_ON_REMOTE' })])
expect(replies('dsh_install')).toEqual([expect.objectContaining({ requestId: 'in-1', error: 'UNSUPPORTED_ON_REMOTE' })])
+ expect(replies('dsh_update')).toEqual([expect.objectContaining({ requestId: 'up-1', error: 'UNSUPPORTED_ON_REMOTE' })])
+ })
+
+ it('dsh_update validates identity, streams progress, and returns update failures', async () => {
+ const update = vi.fn<NonNullable<BackendSocket['onDshUpdate']>>(async (id, progress) => {
+ progress({ id: null, phase: 'clone' })
+ progress({ id, phase: 'done' })
+ return { ok: true, id }
+ })
+ socket.onDshUpdate = update
+ ask('dsh_update', { requestId: 'invalid', id: '../../etc' })
+ ask('dsh_update', { requestId: 'update', id: 'acme/thing', url: 'ignored', ref: 'ignored' })
+ await vi.waitFor(() => expect(replies('dsh_update')).toHaveLength(2))
+ expect(update).toHaveBeenCalledTimes(1)
+ expect(replies('dsh_update')).toEqual([
+ expect.objectContaining({ requestId: 'invalid', error: 'INVALID_DSH' }),
+ expect.objectContaining({ requestId: 'update', ok: true, id: 'acme/thing' }),
+ ])
+ expect(frames.filter(frame => frame.type === 'dsh_install_status').map(frame => frame.payload))
+ .toEqual([{ id: 'acme/thing', phase: 'clone' }, { id: 'acme/thing', phase: 'done' }])
+ update.mockResolvedValueOnce({ ok: false, error: 'LINKED_INSTALL', detail: 'Update the checkout' })
+ ask('dsh_update', { requestId: 'linked', id: 'acme/thing' })
+ await vi.waitFor(() => expect(replies('dsh_update')).toHaveLength(3))
+ expect(replies('dsh_update')[2]).toMatchObject({ error: 'LINKED_INSTALL', detail: 'Update the checkout' })
+ for (const error of [new Error('disk full'), 'closed']) {
+ update.mockRejectedValueOnce(error)
+ ask('dsh_update', { requestId: 'throws', id: 'acme/thing' })
+ await vi.waitFor(() => expect(replies('dsh_update').at(-1)).toMatchObject({ error: 'INTERNAL', detail: String(error instanceof Error ? error.message : error) }))
+ }
})
it('dsh_install: refuses a request with no usable id or url, before the daemon hears of it', async () => {
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index bd782b808..7a1e16fbf 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -374,6 +374,9 @@ export class BackendSocket {
/** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */
onDshInstall: ((input: { id?: string; url?: string; ref?: string }, progress: (p: DshInstallProgress) => void) =>
Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null
+ /** An explicit update follows the installed source and retains the previous package on failure. */
+ onDshUpdate: ((id: string, progress: (p: DshInstallProgress) => void) =>
+ Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null
/** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */
onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null
/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */
@@ -1597,6 +1600,16 @@ export class BackendSocket {
return
}
+ case 'dsh_update': {
+ if (!this.onDshUpdate) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const id = dshRemoveId(payload)
+ if (!id) { reply(type, requestId, { error: 'INVALID_DSH', detail: 'dsh_update needs an id' }); return }
+ void this.onDshUpdate(id, p => this.send({ type: 'dsh_install_status', payload: dshInstallStatus(p, { id }) }))
+ .then(result => reply(type, requestId, dshInstallReply(result)))
+ .catch(error => reply(type, requestId, { error: 'INTERNAL', detail: error instanceof Error ? error.message : String(error) }))
+ return
+ }
+
case 'dsh_install': {
// Clone, set up and doctor a harness on THIS machine. Long — minutes, for a toolchain — so
// it is detached from the ordered RPC chain like `engines_probe`, and progress travels as
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index adcb7ef6c..af196cdc9 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import { mutateDsh } from './dsh/service.js'
import { fingerprint as e2eeCoreFingerprint, b64d as e2eeCoreDecode } from './lib/e2ee/core.js'
import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'
/**
@@ -81,7 +82,7 @@ import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
import { installedDsh } from './dsh/installed.js'
import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'
import { catalogEntry, refreshDshRegistry } from './dsh/catalog.js'
-import { installDsh, resolveInstallSource, removeDsh } from './dsh/install.js'
+import { removeDsh } from './dsh/install.js'
import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'
import { materializeWorkspace } from './dsh/materialize.js'
import { dshLaunch } from './dsh/launch.js'
@@ -2215,55 +2216,8 @@ async function runForeground(session: AuthSession): Promise<void> {
backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)
backend.dshFrameProvider = dshFrameContext
backend.onDshRemove = (id) => removeDsh(id)
- backend.onDshInstall = async ({ id, url, ref }, progress) => {
- const catalog = new Map((await refreshDshRegistry(!!id && !catalogEntry(id))).map(entry => [entry.id, entry]))
- if (id && !catalog.has(id)) return { ok: false, error: 'INVALID_DSH', detail: `${id} is not in this machine's Store catalog` }
- const resolved = id ? resolveInstallSource(id) : url ? { source: url, ref } : null
- if (!resolved) return { ok: false, error: 'INVALID_DSH', detail: `${id ?? url} is not a known harness` }
- // NARRATE THE LINES, NOT ONLY THE PHASES. A toolchain setup is minutes of npm and uv output, and
- // a dialog that says "Setting up…" for all of it looks hung; the line the command is on is what
- // says it is alive and what it is doing. Throttled: a setup can print hundreds of lines a second
- // (`Updating files: 39%…` arrives as carriage returns on ONE line), and the window redraws on
- // each push. The doctor's own ok/miss/warn lines go out at once — they are the ones a person
- // reads, and there are seven of them.
- let last: import('./dsh/install.js').DshInstallProgress | null = null
- let pendingLine: string | null = null
- let timer: NodeJS.Timeout | null = null
- const flushLine = (): void => {
- timer = null
- if (last && pendingLine !== null && last.phase !== 'done' && last.phase !== 'failed') progress({ ...last, line: pendingLine })
- pendingLine = null
- }
- const result = await installDsh({
- source: resolved.source,
- expectedId: id,
- registry: dependencyId => catalog.get(dependencyId),
- ref: ref ?? resolved.ref,
- path: 'path' in resolved ? resolved.path : undefined,
- onProgress: (p) => {
- if (timer) { clearTimeout(timer); timer = null }
- pendingLine = null
- last = p
- progress(p)
- },
- onLine: (raw) => {
- console.log(`[dsh] install · ${raw}`)
- // The last carriage-return segment is the line as a terminal would show it.
- const line = raw.split('\r').filter((s) => s.trim()).pop()?.trim() ?? ''
- if (!line) return
- pendingLine = line.slice(0, 200)
- if (/^(ok|miss|warn)\s/.test(line)) { if (timer) clearTimeout(timer); flushLine(); return }
- if (!timer) timer = setTimeout(flushLine, 300)
- },
- })
- if (timer) { clearTimeout(timer); timer = null }
- if (!result.ok) {
- console.warn(`[dsh] install of ${id ?? url} failed · ${result.error} · ${result.detail}`)
- return { ok: false, error: result.error, detail: result.detail }
- }
- console.log(`[dsh] installed ${result.installed.id} at ${result.installed.dir}`)
- return { ok: true, id: result.installed.id }
- }
+ backend.onDshInstall = (input, progress) => mutateDsh(input, progress)
+ backend.onDshUpdate = (id, progress) => mutateDsh({ id, update: true }, progress)
backend.onAgentRename = (session, name) => { void terminals.setTitle(session, name) }
backend.onRuntimeProfileUpdate = (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel)
runtimeProfiles.onChanged = (sessionId) => {
diff --git a/cli/src/dsh/catalogPublisher.spec.ts b/cli/src/dsh/catalogPublisher.spec.ts
index 350a07aad..1efdccda6 100644
--- a/cli/src/dsh/catalogPublisher.spec.ts
+++ b/cli/src/dsh/catalogPublisher.spec.ts
@@ -20,6 +20,13 @@ function fixture() {
}
describe('Store publication', () => {
+ it('publishes package tree revisions, keeping the source commit separately', () => {
+ const revisionFor = vi.fn(() => 'b'.repeat(40))
+ const catalog = createStoreCatalog(fixture(), ref, { revisionFor })
+ expect(revisionFor).toHaveBeenCalledWith('store/agents/game')
+ expect(parseStoreCatalog(catalog).entries[0]).toMatchObject({ ref, revision: 'b'.repeat(40) })
+ expect(() => createStoreCatalog(fixture(), ref, { revisionFor: () => 'not a revision' })).toThrow(/invalid package revision/)
+ })
it('generates a runtime-valid catalog from all real packages, pinning built-ins to the source commit', () => {
const catalog = createStoreCatalog(fileURLToPath(new URL('../../../store', import.meta.url)), ref)
const parsed = parseStoreCatalog(catalog)
diff --git a/cli/src/dsh/command.spec.ts b/cli/src/dsh/command.spec.ts
index ddf9bcd05..616a9c74d 100644
--- a/cli/src/dsh/command.spec.ts
+++ b/cli/src/dsh/command.spec.ts
@@ -5,7 +5,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { env } from '../config/env.js'
-import { dshInstallDir, invalidateInstalledDsh, upsertInstalledRecord } from './installed.js'
+import { dshInstallDir, installedDsh, invalidateInstalledDsh, upsertInstalledRecord } from './installed.js'
import type { DshInstallOptions } from './install.js'
import { HARNESS_MONOREPO, resetBundledDshRegistry } from './registry.js'
@@ -102,8 +102,8 @@ describe('harness dsh', () => {
expect(await dshCommand('list', [])).toBe(0)
expect(out).toHaveLength(1)
expect(out[0].split('\n')).toEqual([
- ` ${'acme/pane'.padEnd(28)} ${'Thing'.padEnd(12)} ${'viewer'.padEnd(11)} tier 2 installed (linked) · ${dshInstallDir('acme/pane')}`,
- ` ${'acme/thing'.padEnd(28)} ${'Thing'.padEnd(12)} ${'on claude'.padEnd(11)} tier 2 installed · ${dshInstallDir('acme/thing')}`,
+ ` ${'acme/pane'.padEnd(28)} ${'Thing'.padEnd(12)} ${'viewer'.padEnd(11)} tier 2 installed (linked) @ ${installedDsh('acme/pane')!.commit!.slice(0, 8)} · ${dshInstallDir('acme/pane')}`,
+ ` ${'acme/thing'.padEnd(28)} ${'Thing'.padEnd(12)} ${'on claude'.padEnd(11)} tier 2 installed @ ${installedDsh('acme/thing')!.commit!.slice(0, 8)} · ${dshInstallDir('acme/thing')}`,
` ${'acme/broken'.padEnd(28)} ${'?'.padEnd(12)} ${''.padEnd(11)} ${''.padEnd(6)} BROKEN · ${join(root, 'gone')} is missing`,
` ${'autonomous/pane'.padEnd(28)} ${'Pane'.padEnd(12)} ${'viewer'.padEnd(11)} tier ? available · ${HARNESS_MONOREPO}/tree/main/store/viewers/pane`,
` ${'autonomous/typst'.padEnd(28)} ${'Typst'.padEnd(12)} ${'on claude'.padEnd(11)} tier 2 available · ${HARNESS_MONOREPO}/tree/main/store/agents/typst`,
@@ -167,6 +167,22 @@ describe('harness dsh', () => {
})
})
+ it('updates from the recorded source, reports the version, and rejects missing or invalid targets', async () => {
+ const repo = thing()
+ expect(await dshCommand('install', [repo])).toBe(0)
+ writeFileSync(join(repo, 'README.md'), 'new package version')
+ execFileSync('git', ['-C', repo, 'add', '-A'])
+ execFileSync('git', ['-C', repo, '-c', 'user.name=test', '-c', '[email protected]', 'commit', '-qm', 'updated'])
+ expect(await dshCommand('update', ['acme/thing'])).toBe(0)
+ expect(out.at(-1)).toMatch(/acme\/thing is up to date @ [a-f0-9]{8}. Workspaces preserved./)
+ expect(await dshCommand('update', ['acme/missing'])).toBe(1)
+ expect(err.at(-1)).toContain('NOT_INSTALLED')
+ for (const args of [[], ['../../etc'], ['acme/thing', 'acme/other']]) {
+ expect(await dshCommand('update', args)).toBe(1)
+ expect(err.at(-1)).toContain('harness dsh update <id>')
+ }
+ })
+
describe('doctor', () => {
it('runs the installed harness\'s doctor, by its id or an id it went by before', async () => {
await dshCommand('install', [thing({ formerly: ['acme/old-thing'], toolchain: { doctor: './doctor.sh' } }, { 'doctor.sh': '#!/bin/sh\necho "ok fine"\n' })])
diff --git a/cli/src/dsh/command.ts b/cli/src/dsh/command.ts
index fae48d6d3..9b2fb6b50 100644
--- a/cli/src/dsh/command.ts
+++ b/cli/src/dsh/command.ts
@@ -1,3 +1,4 @@
+import { updateDsh } from './update.js'
/**
* `harness dsh …` — the terminal face of domain-specific harnesses, for a server with no desktop
* and for the development loop (`--link` a checkout, iterate, no re-clone).
@@ -7,6 +8,7 @@ import { DSH_ID_RE, dshTier } from './manifest.js'
import { registrySourceUrl } from './registry.js'
import { catalogEntry, currentDshRegistry, refreshDshRegistry } from './catalog.js'
import { installDsh, removeDsh, resolveInstallSource, runDshDoctor } from './install.js'
+import { dshUpdateInfo } from './updates.js'
import { checkDsh, formatCheck } from './check.js'
export function dshUsage(): string {
@@ -17,6 +19,7 @@ export function dshUsage(): string {
--path installs one folder of that repo (store/agents/typst);
--link symlinks a local checkout instead of cloning it
harness dsh doctor <id> re-run the harness's own readiness check
+ harness dsh update <id> update a package, preserving its workspaces
harness dsh remove <id> uninstall (a --link install removes only the link)
harness dsh check <path> conformance check for a harness checkout (what the registry runs)`
}
@@ -39,7 +42,8 @@ export async function dshCommand(verb: string | undefined, rest: readonly string
const rows: string[] = []
for (const dsh of installed) {
seen.add(dsh.id)
- rows.push(` ${dsh.id.padEnd(28)} ${dsh.manifest.name.padEnd(12)} ${(dsh.manifest.kind === 'viewer' ? 'viewer' : `on ${dsh.manifest.engine}`).padEnd(11)} tier ${dshTier(dsh.manifest)} installed${dsh.linked ? ' (linked)' : ''} · ${dsh.dir}`)
+ const update = dshUpdateInfo(dsh, registry.find(entry => entry.id === dsh.id))
+ rows.push(` ${dsh.id.padEnd(28)} ${dsh.manifest.name.padEnd(12)} ${(dsh.manifest.kind === 'viewer' ? 'viewer' : `on ${dsh.manifest.engine}`).padEnd(11)} tier ${dshTier(dsh.manifest)} installed${dsh.linked ? ' (linked)' : ''}${dsh.commit ? ` @ ${dsh.commit.slice(0, 8)}` : ''}${update.updateAvailable ? ` · update available (${update.availableCommit!.slice(0, 8)})` : ''} · ${dsh.dir}`)
}
for (const row of broken) {
seen.add(row.id)
@@ -76,6 +80,17 @@ export async function dshCommand(verb: string | undefined, rest: readonly string
console.log(`Installed ${result.installed.id} (${result.installed.manifest.name}, ${result.installed.manifest.kind === 'viewer' ? 'a viewer package' : `runs on ${result.installed.manifest.engine}`}) at ${result.installed.dir}`)
return 0
}
+ case 'update': {
+ const id = args[0]
+ if (!id || !DSH_ID_RE.test(id) || args.length !== 1) { console.error(dshUsage()); return 1 }
+ const result = await updateDsh({ id,
+ onProgress: p => console.log(`[dsh] ${id} · ${p.phase}${p.detail ? ` · ${p.detail}` : ''}`),
+ onLine: line => console.log(` ${line}`),
+ })
+ if (!result.ok) { console.error(`harness dsh update failed · ${result.error} · ${result.detail}`); return 1 }
+ console.log(`${id} is up to date${result.installed.commit ? ` @ ${result.installed.commit.slice(0, 8)}` : ''}. Workspaces preserved.`)
+ return 0
+ }
case 'doctor': {
const id = args[0]
const dsh = id ? installedDsh(id) : undefined
diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.ts
index f41f811dd..11de62af9 100644
--- a/cli/src/dsh/install.ts
+++ b/cli/src/dsh/install.ts
@@ -22,6 +22,7 @@ import { PACKAGE_PATH_RE, type DshRegistryEntry } from './registry.js'
import { catalogEntry, refreshDshRegistry } from './catalog.js'
import { resolveDshCommand } from './materialize.js'
import { runDshCommand } from './shell.js'
+import { lockDsh, dshBusy } from './lock.js'
const execFileAsync = promisify(execFile)
@@ -81,9 +82,9 @@ export function resolveInstallSource(
return { source: idOrSource }
}
-async function gitHead(dir: string): Promise<string | null> {
+async function gitHead(dir: string, revision = 'HEAD'): Promise<string | null> {
try {
- const { stdout } = await execFileAsync('git', ['-C', dir, 'rev-parse', 'HEAD'], { timeout: 10_000 })
+ const { stdout } = await execFileAsync('git', ['-C', dir, 'rev-parse', revision], { timeout: 10_000 })
return stdout.trim() || null
} catch {
return null
@@ -114,12 +115,12 @@ function linkInstall(source: string): { ok: true; realDir: string; manifest: Dsh
return { ok: true, realDir, manifest: manifest.manifest }
}
-async function cloneInstall(
+export async function cloneInstall(
source: string,
ref: string | undefined,
path: string | undefined,
onLine: ((line: string) => void) | undefined,
-): Promise<{ ok: true; tmpDir: string; manifest: DshManifest; commit: string | null } | { ok: false; error: string; detail: string }> {
+): Promise<{ ok: true; tmpDir: string; manifest: DshManifest; commit: string | null; revision: string | null } | { ok: false; error: string; detail: string }> {
const root = dshRootDir()
mkdirSync(root, { recursive: true, mode: 0o700 })
const tmpDir = join(root, `.tmp-${randomUUID()}`)
@@ -129,12 +130,14 @@ async function cloneInstall(
}
if (path !== undefined && !PACKAGE_PATH_RE.test(path)) return fail('INVALID_SOURCE', `${path} is not a folder inside the repo`)
let commit: string | null
+ let revision: string | null
if (path === undefined) {
// `--progress` because stderr is not a tty here and git would otherwise stay silent until the end;
// streamed, not collected, so "Receiving objects: 39%" reaches the dialog while it is true.
const clone = await cloneRepo(source, ref, tmpDir, false, onLine)
if (!clone.ok) return fail('CLONE_FAILED', clone.detail)
commit = await gitHead(tmpDir)
+ revision = await gitHead(tmpDir, 'HEAD^{tree}')
} else {
// A package that is ONE FOLDER of a bigger repo — the built-in shelf is `store/*/*` of the Harness
// monorepo, whose other folders are the app, the CLI and the backend. A blob-less, sparse clone
@@ -151,12 +154,13 @@ async function cloneInstall(
try { isFolder = lstatSync(folder).isDirectory() } catch { isFolder = false }
if (!isFolder) return fail('CLONE_FAILED', `${source}${ref ? ` at ${ref}` : ''} has no folder ${path}`, repoDir)
commit = await gitHead(repoDir)
+ revision = await gitHead(repoDir, `HEAD:${path}`)
renameSync(folder, tmpDir)
rmSync(repoDir, { recursive: true, force: true })
}
const manifest = readDshManifest(tmpDir)
if (!manifest.ok) return fail('INVALID_MANIFEST', manifest.error)
- return { ok: true, tmpDir, manifest: manifest.manifest, commit }
+ return { ok: true, tmpDir, manifest: manifest.manifest, commit, revision }
}
/** How long one git command may take: a clone of a large repository over a slow link, not a hang. */
@@ -266,41 +270,61 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
let dir: string
let commit: string | null = null
let realDir: string
+ let revision: string | null = null
+ let unlock: (() => void) | null = null
+ let staged: string | null = null
- progress({ id: null, phase: 'clone', detail: opts.link ? `linking ${opts.source}` : `cloning ${opts.source}${opts.path ? ` · ${opts.path}` : ''}` })
- if (opts.link) {
- const linked = linkInstall(opts.source)
- if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail }); return linked }
- manifest = linked.manifest
- if (opts.expectedId && manifest.id !== opts.expectedId) return wrongId(manifest.id)
- realDir = linked.realDir
- dir = placeAt(manifest.id, { linkTo: realDir })
- commit = await gitHead(realDir)
- } else {
- const cloned = await cloneInstall(opts.source, opts.ref, opts.path, opts.onLine)
- if (!cloned.ok) { progress({ id: null, phase: 'failed', detail: cloned.detail }); return cloned }
- manifest = cloned.manifest
- if (opts.expectedId && manifest.id !== opts.expectedId) {
- rmSync(cloned.tmpDir, { recursive: true, force: true })
- return wrongId(manifest.id)
+ try {
+ progress({ id: null, phase: 'clone', detail: opts.link ? `linking ${opts.source}` : `cloning ${opts.source}${opts.path ? ` · ${opts.path}` : ''}` })
+ if (opts.link) {
+ const linked = linkInstall(opts.source)
+ if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail }); return linked }
+ manifest = linked.manifest
+ if (opts.expectedId && manifest.id !== opts.expectedId) return wrongId(manifest.id)
+ unlock = lockDsh(manifest.id)
+ if (!unlock) return dshBusy(manifest.id)
+ realDir = linked.realDir
+ dir = placeAt(manifest.id, { linkTo: realDir })
+ commit = await gitHead(realDir)
+ } else {
+ const cloned = await cloneInstall(opts.source, opts.ref, opts.path, opts.onLine)
+ if (!cloned.ok) { progress({ id: null, phase: 'failed', detail: cloned.detail }); return cloned }
+ staged = cloned.tmpDir
+ manifest = cloned.manifest
+ if (opts.expectedId && manifest.id !== opts.expectedId) {
+ rmSync(cloned.tmpDir, { recursive: true, force: true })
+ return wrongId(manifest.id)
+ }
+ unlock = lockDsh(manifest.id)
+ if (!unlock) return dshBusy(manifest.id)
+ commit = cloned.commit
+ revision = cloned.revision
+ dir = placeAt(manifest.id, { tmpDir: cloned.tmpDir })
+ realDir = realpathSync(dir)
}
- commit = cloned.commit
- dir = placeAt(manifest.id, { tmpDir: cloned.tmpDir })
- realDir = realpathSync(dir)
- }
- const record: InstalledDshRecord = {
- id: manifest.id,
- dir,
- source: opts.link ? resolve(opts.source) : opts.source,
- ref: opts.ref ?? null,
- ...(opts.link || !opts.path ? {} : { path: opts.path }),
- commit,
- linked: opts.link === true,
- installedAt: Date.now(),
+ const record: InstalledDshRecord = {
+ id: manifest.id,
+ dir,
+ source: opts.link ? resolve(opts.source) : opts.source,
+ ref: opts.ref ?? null,
+ ...(opts.link || !opts.path ? {} : { path: opts.path }),
+ commit,
+ revision,
+ linked: opts.link === true,
+ installedAt: Date.now(),
+ }
+ return await finishInstall({ ...record, manifest, realDir }, opts, true)
+ } finally {
+ if (staged) rmSync(staged, { recursive: true, force: true })
+ unlock?.()
}
- // Exactly what was just read and placed; resolving the record from disk again would read it twice.
- const resolved: InstalledDsh = { ...record, manifest, realDir }
+}
+
+/** Run at the permanent path: venvs and generated launchers often embed it. */
+export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOptions, recordDoctorFailure: boolean): Promise<DshInstallResult> {
+ const { manifest, realDir } = resolved
+ const progress = (p: DshInstallProgress): void => opts.onProgress?.(p)
const setupLines: string[] = []
if (manifest.toolchain?.setup) {
@@ -356,7 +380,10 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
const doctor = await runDshDoctor(resolved, opts.onLine)
// Recorded even when the doctor complains: the user can fix the machine and run the doctor again
// without re-cloning. The desktop reads the doctor's answer, not the index, before a create.
- upsertInstalledRecord(record)
+ if (doctor.ok || recordDoctorFailure) {
+ const { manifest: _manifest, realDir: _realDir, ...record } = resolved
+ upsertInstalledRecord(record)
+ }
if (!doctor.ok) {
const detail = `doctor failed · ${doctor.lines.filter((line) => line.startsWith('miss')).join(' · ') || doctor.lines.slice(-3).join(' · ')}`.slice(0, 2000)
progress({ id: manifest.id, phase: 'failed', detail })
@@ -369,18 +396,22 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
export function removeDsh(id: string): { ok: true } | { ok: false; error: string; detail: string } {
const record = readInstalledIndex().find((row) => row.id === id)
if (!record) return { ok: false, error: 'NOT_INSTALLED', detail: `${id} is not installed` }
+ const unlock = lockDsh(id)
+ if (!unlock) return dshBusy(id)
try {
- // A linked install is a symlink: remove the link, never the checkout it points at.
- let isLink = false
- try { isLink = lstatSync(record.dir).isSymbolicLink() } catch { isLink = false }
- if (isLink) rmSync(record.dir, { force: true })
- else if (existsSync(record.dir)) rmSync(record.dir, { recursive: true, force: true })
- } catch (error) {
- // rmSync throws only system errors (EACCES, EBUSY).
- return { ok: false, error: 'REMOVE_FAILED', detail: (error as Error).message }
- }
- removeInstalledRecord(id)
- return { ok: true }
+ try {
+ // A linked install is a symlink: remove the link, never the checkout it points at.
+ let isLink = false
+ try { isLink = lstatSync(record.dir).isSymbolicLink() } catch { isLink = false }
+ if (isLink) rmSync(record.dir, { force: true })
+ else if (existsSync(record.dir)) rmSync(record.dir, { recursive: true, force: true })
+ } catch (error) {
+ // rmSync throws only system errors (EACCES, EBUSY).
+ return { ok: false, error: 'REMOVE_FAILED', detail: (error as Error).message }
+ }
+ removeInstalledRecord(id)
+ return { ok: true }
+ } finally { unlock() }
}
export { installedDsh }
diff --git a/cli/src/dsh/installed.ts b/cli/src/dsh/installed.ts
index fa7211fae..f8a62a1d1 100644
--- a/cli/src/dsh/installed.ts
+++ b/cli/src/dsh/installed.ts
@@ -6,7 +6,8 @@
* and a row whose manifest no longer parses is reported broken rather than silently dropped, so a
* DSH that breaks on update is visible in `harness dsh list` instead of vanishing from the picker.
*/
-import { mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
+import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { env } from '../config/env.js'
import { DSH_ID_RE, readDshManifest, type DshManifest } from './manifest.js'
@@ -21,9 +22,12 @@ export interface InstalledDshRecord {
/** The folder of `source` that was installed, for a package that is one folder of a repo. */
path?: string | null
commit: string | null
+ /** Git tree of the package folder, independent of unrelated monorepo commits. */
+ revision?: string | null
/** True when `dir` is a symlink to a checkout — the development loop. */
linked: boolean
installedAt: number
+ updatedAt?: number
}
export interface InstalledDsh extends InstalledDshRecord {
@@ -79,7 +83,9 @@ export function readInstalledIndex(): InstalledDshRecord[] {
export function writeInstalledIndex(records: readonly InstalledDshRecord[]): void {
mkdirSync(dshRootDir(), { recursive: true, mode: 0o700 })
- writeFileSync(indexPath(), JSON.stringify(records, null, 2) + '\n', { mode: 0o600 })
+ const temporary = `${indexPath()}.${randomUUID()}.tmp`
+ writeFileSync(temporary, JSON.stringify(records, null, 2) + '\n', { mode: 0o600 })
+ renameSync(temporary, indexPath())
}
export function upsertInstalledRecord(record: InstalledDshRecord): void {
diff --git a/cli/src/dsh/lock.spec.ts b/cli/src/dsh/lock.spec.ts
new file mode 100644
index 000000000..9bb49a085
--- /dev/null
+++ b/cli/src/dsh/lock.spec.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, existsSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import { lockDsh } from './lock.js'
+
+const faults = vi.hoisted(() => ({ mkdir: false, write: false, race: false }))
+vi.mock('node:fs', async original => {
+ const fs = await original<typeof import('node:fs')>()
+ return { ...fs,
+ mkdirSync: (...args: Parameters<typeof fs.mkdirSync>) => {
+ if (faults.mkdir && String(args[0]).includes('/.lock-')) throw Object.assign(new Error('read only'), { code: 'EROFS' })
+ if (faults.race && String(args[0]).endsWith('.lock-acme_thing')) {
+ fs.mkdirSync(args[0], { recursive: true })
+ fs.writeFileSync(join(String(args[0]), 'pid'), '123456')
+ throw Object.assign(new Error('racing lock'), { code: 'EEXIST' })
+ }
+ return fs.mkdirSync(...args)
+ },
+ writeFileSync: (...args: Parameters<typeof fs.writeFileSync>) => {
+ if (faults.write && String(args[0]).endsWith('/pid')) throw new Error('disk full')
+ return fs.writeFileSync(...args)
+ },
+ }
+})
+
+describe('package mutation locks', () => {
+ let root: string
+ let saved: string
+ const id = 'acme/thing'
+ const owner = (pid?: string): string => {
+ const path = join(root, '.lock-acme_thing')
+ mkdirSync(path, { recursive: true })
+ if (pid !== undefined) writeFileSync(join(path, 'pid'), pid)
+ return path
+ }
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'dsh-lock-'))
+ saved = env.DSH_DIR
+ env.DSH_DIR = root
+ })
+ afterEach(() => {
+ faults.mkdir = faults.write = faults.race = false
+ vi.restoreAllMocks()
+ env.DSH_DIR = saved
+ rmSync(root, { recursive: true, force: true })
+ })
+
+ it('rejects invalid ids, excludes another owner, and releases for the next mutation', () => {
+ expect(lockDsh('../../escape')).toBeNull()
+ const release = lockDsh(id)!
+ expect(lockDsh(id)).toBeNull()
+ release()
+ expect(existsSync(join(root, '.lock-acme_thing'))).toBe(false)
+ lockDsh(id)!()
+ // These two valid package ids must never share a lock filename.
+ const first = lockDsh('acme--one/thing')!
+ const second = lockDsh('acme/one--thing')!
+ first(); second()
+ })
+
+ it('does not steal an incomplete owner record or another reaper', () => {
+ const path = owner()
+ expect(lockDsh(id)).toBeNull()
+ for (const pid of ['nonsense', '-1', '0']) {
+ writeFileSync(join(path, 'pid'), pid)
+ expect(lockDsh(id)).toBeNull()
+ }
+ mkdirSync(`${path}.reap`)
+ expect(lockDsh(id)).toBeNull()
+ })
+
+ it('recovers a dead owner and treats permission-denied process probes as live owners', () => {
+ const path = owner('123456')
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('not permitted'), { code: 'EPERM' }) })
+ expect(lockDsh(id)).toBeNull()
+ expect(existsSync(path)).toBe(true)
+ kill.mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }) })
+ const release = lockDsh(id)
+ expect(release).toBeTypeOf('function')
+ release!()
+ })
+
+ it('reports filesystem failures, removing a lock whose owner could not be saved', () => {
+ faults.mkdir = true
+ expect(() => lockDsh(id)).toThrow('read only')
+ faults.mkdir = false
+ faults.write = true
+ expect(() => lockDsh(id)).toThrow('disk full')
+ expect(existsSync(join(root, '.lock-acme_thing'))).toBe(false)
+ })
+
+ it('bounds recovery attempts when another process keeps changing the owner', () => {
+ faults.race = true
+ vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }) })
+ expect(lockDsh(id)).toBeNull()
+ })
+})
diff --git a/cli/src/dsh/lock.ts b/cli/src/dsh/lock.ts
new file mode 100644
index 000000000..20a2ea1a4
--- /dev/null
+++ b/cli/src/dsh/lock.ts
@@ -0,0 +1,42 @@
+/** A package mutation may also come from a standalone CLI while the daemon is installing it. */
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { dshRootDir } from './installed.js'
+import { DSH_ID_RE } from './manifest.js'
+
+export function lockDsh(id: string): (() => void) | null {
+ if (!DSH_ID_RE.test(id)) return null
+ const root = dshRootDir()
+ mkdirSync(root, { recursive: true, mode: 0o700 })
+ const path = join(root, `.lock-${id.replace('/', '_')}`)
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ mkdirSync(path, { mode: 0o700 })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
+ // Only one contender may reap a dead owner. Re-read under this guard so a second
+ // contender never removes the live lock the first one just acquired.
+ const reaper = `${path}.reap`
+ try { mkdirSync(reaper, { mode: 0o700 }) } catch { return null }
+ try {
+ const pid = Number(readFileSync(join(path, 'pid'), 'utf8'))
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null
+ try { process.kill(pid, 0); return null } catch (cause) {
+ if ((cause as NodeJS.ErrnoException).code !== 'ESRCH') return null
+ }
+ rmSync(path, { recursive: true, force: true })
+ continue
+ } catch { return null } finally { rmSync(reaper, { recursive: true, force: true }) }
+ }
+ try { writeFileSync(join(path, 'pid'), String(process.pid), { mode: 0o600 }) } catch (error) {
+ rmSync(path, { recursive: true, force: true })
+ throw error
+ }
+ return () => rmSync(path, { recursive: true, force: true })
+ }
+ return null
+}
+
+export function dshBusy(id: string): { ok: false; error: string; detail: string } {
+ return { ok: false, error: 'DSH_BUSY', detail: `${id} is already being installed, updated or removed. Try again when it finishes.` }
+}
diff --git a/cli/src/dsh/registry.ts b/cli/src/dsh/registry.ts
index fd3b7d32f..ecd3f4bcf 100644
--- a/cli/src/dsh/registry.ts
+++ b/cli/src/dsh/registry.ts
@@ -51,6 +51,8 @@ export const DshRegistryEntrySchema = z.strictObject({
author: z.string().min(1).max(80).optional(),
repo: z.string().min(1).max(2048),
ref: z.string().min(1).max(200).optional(),
+ /** Git tree of this package at ref; avoids updates caused by other monorepo folders. */
+ revision: z.string().regex(/^[a-f0-9]{40}$/i).optional(),
/**
* The folder inside `repo` that is the package, when the package is not the whole repo — every
* built-in package lives at `store/agents/<name>` or `store/viewers/<name>` of the Harness monorepo.
diff --git a/cli/src/dsh/service.ts b/cli/src/dsh/service.ts
new file mode 100644
index 000000000..6111a8296
--- /dev/null
+++ b/cli/src/dsh/service.ts
@@ -0,0 +1,55 @@
+/** Shared daemon installation/update handler, including the progress sent to desktop clients. */
+import { installDsh, resolveInstallSource } from './install.js'
+import { updateDsh } from './update.js'
+import { catalogEntry, refreshDshRegistry } from './catalog.js'
+
+export const mutateDsh = async ({ id, url, ref, update }: { id?: string; url?: string; ref?: string; update?: boolean }, progress: (p: import('./install.js').DshInstallProgress) => void): Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }> => {
+ const catalog = new Map((await refreshDshRegistry(update || (!!id && !catalogEntry(id)))).map(entry => [entry.id, entry]))
+ if (!update && id && !catalog.has(id)) return { ok: false, error: 'INVALID_DSH', detail: `${id} is not in this machine's Store catalog` }
+ const resolved = update ? { source: '' } : id ? resolveInstallSource(id) : url ? { source: url, ref } : null
+ if (!resolved) return { ok: false, error: 'INVALID_DSH', detail: `${id ?? url} is not a known harness` }
+ // NARRATE THE LINES, NOT ONLY THE PHASES. A toolchain setup is minutes of npm and uv output, and
+ // a dialog that says "Setting up…" for all of it looks hung; the line the command is on is what
+ // says it is alive and what it is doing. Throttled: a setup can print hundreds of lines a second
+ // (`Updating files: 39%…` arrives as carriage returns on ONE line), and the window redraws on
+ // each push. The doctor's own ok/miss/warn lines go out at once — they are the ones a person
+ // reads, and there are seven of them.
+ let last: import('./install.js').DshInstallProgress | null = null
+ let pendingLine: string | null = null
+ let timer: NodeJS.Timeout | null = null
+ const flushLine = (): void => {
+ timer = null
+ if (last && pendingLine !== null && last.phase !== 'done' && last.phase !== 'failed') progress({ ...last, line: pendingLine })
+ pendingLine = null
+ }
+ const options: import('./install.js').DshInstallOptions = {
+ source: resolved.source,
+ expectedId: id,
+ registry: dependencyId => catalog.get(dependencyId),
+ ref: ref ?? resolved.ref,
+ path: 'path' in resolved ? resolved.path : undefined,
+ onProgress: (p) => {
+ if (timer) { clearTimeout(timer); timer = null }
+ pendingLine = null
+ last = p
+ progress(p)
+ },
+ onLine: (raw) => {
+ console.log(`[dsh] ${update ? 'update' : 'install'} · ${raw}`)
+ // The last carriage-return segment is the line as a terminal would show it.
+ const line = raw.split('\r').filter((s) => s.trim()).pop()?.trim() ?? ''
+ if (!line) return
+ pendingLine = line.slice(0, 200)
+ if (/^(ok|miss|warn)\s/.test(line)) { if (timer) clearTimeout(timer); flushLine(); return }
+ if (!timer) timer = setTimeout(flushLine, 300)
+ },
+ }
+ const result = update ? await updateDsh({ ...options, id: id! }) : await installDsh(options)
+ if (timer) { clearTimeout(timer); timer = null }
+ if (!result.ok) {
+ console.warn(`[dsh] ${update ? 'update' : 'install'} of ${id ?? url} failed · ${result.error} · ${result.detail}`)
+ return { ok: false, error: result.error, detail: result.detail }
+ }
+ console.log(`[dsh] installed ${result.installed.id} at ${result.installed.dir}`)
+ return { ok: true, id: result.installed.id }
+}
diff --git a/cli/src/dsh/update.spec.ts b/cli/src/dsh/update.spec.ts
new file mode 100644
index 000000000..ef2760f7e
--- /dev/null
+++ b/cli/src/dsh/update.spec.ts
@@ -0,0 +1,277 @@
+import { updateDsh } from './update.js'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'node:child_process'
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import { dshInstallDir, installedDsh, invalidateInstalledDsh, readInstalledIndex, upsertInstalledRecord } from './installed.js'
+import { installDsh, removeDsh, type DshInstallProgress } from './install.js'
+import { materializeWorkspace } from './materialize.js'
+import { dshUpdateInfo } from './updates.js'
+import { type DshRegistryEntry } from './registry.js'
+import { dshListRows } from './wire.js'
+
+const faults = vi.hoisted(() => ({ cleanup: false, place: false }))
+vi.mock('node:fs', async original => {
+ const fs = await original<typeof import('node:fs')>()
+ return { ...fs,
+ renameSync: (...args: Parameters<typeof fs.renameSync>) => {
+ if (faults.place && String(args[0]).includes('/.tmp-') && String(args[1]).endsWith('/acme/thing')) throw new Error('disk full while placing update')
+ return fs.renameSync(...args)
+ },
+ rmSync: (...args: Parameters<typeof fs.rmSync>) => {
+ if (faults.cleanup && String(args[0]).includes('/.previous-')) throw new Error('backup is busy')
+ return fs.rmSync(...args)
+ },
+ }
+})
+
+describe('package updates', () => {
+ let root: string
+ let savedRoot: string
+ const id = 'acme/thing'
+ const manifest = { spec: 1, id, name: 'Thing', engine: 'claude',
+ agent: { instructions: 'AGENTS.md', skills: ['skills'] },
+ workspace: { template: 'template', marker: 'project.txt' },
+ toolchain: { setup: './setup.sh', doctor: './doctor.sh' } }
+ const git = (repo: string, ...args: string[]): string => execFileSync('git', ['-C', repo, ...args], {
+ encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_NAME: 'test', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'test', GIT_COMMITTER_EMAIL: '[email protected]' },
+ }).trim()
+ const write = (dir: string, files: Record<string, string>): void => {
+ for (const [name, body] of Object.entries(files)) {
+ mkdirSync(join(dir, name, '..'), { recursive: true })
+ writeFileSync(join(dir, name), body, { mode: name.endsWith('.sh') ? 0o755 : 0o644 })
+ }
+ }
+ const commit = (repo: string): string => { git(repo, 'add', '-A'); git(repo, 'commit', '-qm', 'package version'); return git(repo, 'rev-parse', 'HEAD') }
+ const create = (path?: string): string => {
+ const repo = join(root, 'repo')
+ const dir = path ? join(repo, path) : repo
+ write(dir, {
+ 'harness.json': JSON.stringify(manifest), 'AGENTS.md': '# Original instructions\n',
+ 'skills/task/SKILL.md': '# Original skill\n', 'template/project.txt': 'template\n',
+ 'setup.sh': '#!/bin/sh\npwd > setup-path\n', 'doctor.sh': '#!/bin/sh\ntest -f setup-path\n',
+ })
+ git(repo, 'init', '-q', '-b', 'main'); commit(repo)
+ return repo
+ }
+ const catalog = (repo: string, ref: string, path?: string): DshRegistryEntry => ({
+ id, name: 'Thing', engine: 'claude', repo, ref, path,
+ revision: git(repo, 'rev-parse', path ? `${ref}:${path}` : `${ref}^{tree}`),
+ })
+ const update = (entry?: DshRegistryEntry, progress?: DshInstallProgress[]) => updateDsh({ id,
+ registry: candidate => candidate === id ? entry : undefined, onProgress: p => progress?.push(p) })
+ beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-update-')))
+ const shell = join(root, 'test-shell')
+ writeFileSync(shell, '#!/bin/sh\nexec /bin/sh -c "$2"\n', { mode: 0o755 })
+ vi.stubEnv('SHELL', shell)
+ savedRoot = env.DSH_DIR
+ env.DSH_DIR = join(root, 'installed')
+ invalidateInstalledDsh()
+ })
+ afterEach(() => {
+ faults.cleanup = false
+ faults.place = false
+ vi.unstubAllEnvs()
+ env.DSH_DIR = savedRoot
+ invalidateInstalledDsh()
+ rmSync(root, { recursive: true, force: true })
+ })
+
+ it('refreshes the default catalog and treats the same recorded commit as a no-op for legacy installs', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const [record] = readInstalledIndex()
+ delete record.revision
+ upsertInstalledRecord(record)
+ const lines: string[] = []
+ expect((await updateDsh({ id, onLine: line => lines.push(line) })).ok).toBe(true)
+ expect(lines).toContain(`${id} is already up to date`)
+ })
+
+ it('repairs a missing installed directory and a record with unknown commit/ref', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const [record] = readInstalledIndex()
+ upsertInstalledRecord({ ...record, commit: null, revision: null })
+ rmSync(record.dir, { recursive: true })
+ expect((await update()).ok).toBe(true)
+ expect(installedDsh(id)?.commit).toBe(git(repo, 'rev-parse', 'HEAD'))
+ })
+
+ it('rejects a kind change, but updates viewer packages independently', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const viewer = { spec: 1, id, kind: 'viewer', name: 'Viewer', viewer: { command: './viewer.sh', url: 'http://127.0.0.1:${port}/' } }
+ write(repo, { 'harness.json': JSON.stringify(viewer) })
+ expect(await update(catalog(repo, commit(repo)))).toMatchObject({ ok: false, error: 'PACKAGE_KIND_MISMATCH' })
+ removeDsh(id)
+ await installDsh({ source: repo })
+ write(repo, { 'harness.json': JSON.stringify({ ...viewer, name: 'Updated viewer' }) })
+ expect((await update(catalog(repo, commit(repo)))).ok).toBe(true)
+ expect(installedDsh(id)?.manifest.name).toBe('Updated viewer')
+ })
+
+ it('refuses a symlink even if its installed record incorrectly calls it a clone', async () => {
+ const repo = create()
+ await installDsh({ source: repo, link: true })
+ const [record] = readInstalledIndex()
+ upsertInstalledRecord({ ...record, linked: false })
+ write(repo, { 'AGENTS.md': '# Changed checkout' })
+ expect(await update(catalog(repo, commit(repo)))).toMatchObject({ ok: false, error: 'LINKED_INSTALL' })
+ expect(lstatSync(record.dir).isSymbolicLink()).toBe(true)
+ })
+
+ it('restores the old package if moving the new files fails and retains a busy backup after success', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const before = readInstalledIndex()
+ write(repo, { 'AGENTS.md': '# Updated' })
+ const entry = catalog(repo, commit(repo))
+ faults.place = true
+ expect(await update(entry)).toMatchObject({ ok: false, error: 'UPDATE_FAILED', detail: 'disk full while placing update' })
+ expect(readInstalledIndex()).toEqual(before)
+ expect(readFileSync(join(dshInstallDir(id), 'AGENTS.md'), 'utf8')).toBe('# Original instructions\n')
+ faults.place = false
+ faults.cleanup = true
+ const lines: string[] = []
+ expect((await updateDsh({ id, registry: () => entry, onLine: line => lines.push(line) })).ok).toBe(true)
+ expect(lines.some(line => line.startsWith('Previous package retained at'))).toBe(true)
+ expect(installedDsh(id)?.commit).toBe(entry.ref)
+ })
+
+ it('reports non-Error failures and releases its lock', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const result = await updateDsh({ id, registry: () => { throw 'connection closed' } })
+ expect(result).toMatchObject({ ok: false, error: 'UPDATE_FAILED', detail: 'connection closed' })
+ expect((await update()).ok).toBe(true)
+ })
+
+ for (const path of [undefined, 'store/agents/thing']) {
+ it(`updates ${path ?? 'a whole repo'} at the catalog commit, preserving workspace files and skill links`, async () => {
+ const repo = create(path)
+ expect((await installDsh({ source: repo, ref: 'main', path })).ok).toBe(true)
+ const before = installedDsh(id)!
+ const workspace = join(root, 'workspace')
+ mkdirSync(workspace)
+ await materializeWorkspace(before, workspace)
+ write(workspace, { 'project.txt': 'my finished work\n', 'AGENTS.md': 'my custom instructions\n', '.harness/verdict.json': '{"ready":true}', 'notes.md': 'my notes' })
+ const skill = join(workspace, '.claude', 'skills', 'task')
+ const link = readlinkSync(skill)
+ const dir = path ? join(repo, path) : repo
+ write(dir, { 'skills/task/SKILL.md': '# Updated skill\n', 'AGENTS.md': '# New instructions\n', 'template/project.txt': 'new template\n' })
+ const ref = commit(repo)
+ const entry = catalog(repo, ref, path)
+ expect(dshListRows([before], [entry])[0]).toMatchObject({ installedCommit: before.commit, availableCommit: ref, updateAvailable: true })
+ write(dir, { 'skills/task/SKILL.md': '# Unpublished skill\n' }); commit(repo)
+ const phases: DshInstallProgress[] = []
+ const result = await update(entry, phases)
+ expect(result.ok, JSON.stringify(result)).toBe(true)
+ const after = installedDsh(id)!
+ expect(after).toMatchObject({ commit: ref, revision: entry.revision, dir: before.dir, installedAt: before.installedAt, updatedAt: expect.any(Number) })
+ expect(readFileSync(join(after.dir, 'setup-path'), 'utf8').trim()).toBe(after.dir)
+ expect(readFileSync(join(workspace, 'project.txt'), 'utf8')).toBe('my finished work\n')
+ expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toBe('my custom instructions\n')
+ expect(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8')).toBe('{"ready":true}')
+ expect(readFileSync(join(workspace, 'notes.md'), 'utf8')).toBe('my notes')
+ expect(readlinkSync(skill)).toBe(link)
+ expect(readFileSync(join(skill, 'SKILL.md'), 'utf8')).toBe('# Updated skill\n')
+ expect(dshUpdateInfo(after, entry).updateAvailable).toBe(false)
+ expect(phases.map(p => p.phase)).toEqual(['clone', 'setup', 'doctor', 'done'])
+ expect(readdirSync(env.DSH_DIR).filter(name => name.startsWith('.'))).toEqual([])
+ })
+ }
+
+ for (const failure of ['setup', 'doctor']) {
+ it(`restores the complete old package and index when ${failure} fails, then supports retry`, async () => {
+ const repo = create()
+ await installDsh({ source: repo, ref: 'main' })
+ const before = readInstalledIndex()
+ write(dshInstallDir(id), { 'local-cache': 'keep me' })
+ write(repo, { [`${failure}.sh`]: '#!/bin/sh\necho "miss broken update"\nexit 1\n', 'AGENTS.md': '# Bad version' })
+ const entry = catalog(repo, commit(repo))
+ expect(await update(entry)).toMatchObject({ ok: false, error: `${failure.toUpperCase()}_FAILED` })
+ expect(readInstalledIndex()).toEqual(before)
+ expect(readFileSync(join(dshInstallDir(id), 'AGENTS.md'), 'utf8')).toBe('# Original instructions\n')
+ expect(readFileSync(join(dshInstallDir(id), 'local-cache'), 'utf8')).toBe('keep me')
+ write(repo, { [`${failure}.sh`]: '#!/bin/sh\npwd > setup-path\necho "ok fixed"\n' })
+ expect((await update(catalog(repo, commit(repo)))).ok).toBe(true)
+ })
+ }
+
+ it('uses the recorded source/ref for an unlisted install and does not redirect a fork with the same id', async () => {
+ const repo = create()
+ await installDsh({ source: repo, ref: 'main' })
+ write(repo, { 'AGENTS.md': '# New version\n' })
+ const ref = commit(repo)
+ const unrelated = { ...catalog(repo, ref), repo: join(root, 'different-source') }
+ expect(dshUpdateInfo(installedDsh(id)!, unrelated).updateAvailable).toBe(false)
+ expect((await update(unrelated)).ok).toBe(true)
+ expect(installedDsh(id)?.commit).toBe(ref)
+ })
+
+ it('skips unchanged package content even when another folder changed in the monorepo', async () => {
+ const path = 'store/agents/thing'
+ const repo = create(path)
+ await installDsh({ source: repo, path, ref: 'main' })
+ const before = readInstalledIndex()
+ write(repo, { 'unrelated.txt': 'new app version' })
+ const entry = catalog(repo, commit(repo), path)
+ expect(dshUpdateInfo(installedDsh(id)!, entry).updateAvailable).toBe(false)
+ const phases: DshInstallProgress[] = []
+ expect((await update(entry, phases)).ok).toBe(true)
+ expect(phases.map(p => p.phase)).toEqual(['clone', 'done'])
+ expect(readInstalledIndex()).toEqual(before)
+ })
+
+ it('handles older records with no revision and refuses to change a linked checkout', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const [record] = readInstalledIndex()
+ delete record.revision
+ upsertInstalledRecord(record)
+ write(repo, { 'AGENTS.md': '# Updated' })
+ const entry = catalog(repo, commit(repo))
+ expect(dshUpdateInfo(record, entry).updateAvailable).toBe(true)
+ expect((await update(entry)).ok).toBe(true)
+ expect(installedDsh(id)?.revision).toBe(entry.revision)
+ await installDsh({ source: repo, link: true })
+ expect(dshUpdateInfo(installedDsh(id)!, entry).updateAvailable).toBe(false)
+ expect(await update(entry)).toMatchObject({ ok: false, error: 'LINKED_INSTALL' })
+ expect(lstatSync(dshInstallDir(id)).isSymbolicLink()).toBe(true)
+ expect(readFileSync(join(repo, 'AGENTS.md'), 'utf8')).toBe('# Updated')
+ })
+
+ it('leaves the installation intact after a clone failure or wrong package identity', async () => {
+ expect(await update()).toMatchObject({ ok: false, error: 'NOT_INSTALLED' })
+ const repo = create()
+ await installDsh({ source: repo })
+ const before = readInstalledIndex()
+ expect(await update({ ...catalog(repo, git(repo, 'rev-parse', 'HEAD')), ref: 'no-such-ref' })).toMatchObject({ ok: false, error: 'CLONE_FAILED' })
+ write(repo, { 'harness.json': JSON.stringify({ ...manifest, id: 'acme/other' }) })
+ expect(await update(catalog(repo, commit(repo)))).toMatchObject({ ok: false, error: 'PACKAGE_ID_MISMATCH' })
+ expect(readInstalledIndex()).toEqual(before)
+ expect(installedDsh(id)?.manifest.id).toBe(id)
+ })
+
+ it('blocks concurrent updates, installs and removal until the update finishes', async () => {
+ const repo = create()
+ await installDsh({ source: repo })
+ const gate = join(root, 'release')
+ write(repo, { 'setup.sh': `#!/bin/sh\necho waiting\nwhile [ ! -f '${gate}' ]; do sleep 0.05; done\npwd > setup-path\n` })
+ const entry = catalog(repo, commit(repo))
+ let waiting = false
+ const pending = updateDsh({ id, registry: () => entry, onLine: line => { if (line === 'waiting') waiting = true } })
+ try {
+ await vi.waitFor(() => expect(waiting).toBe(true), { timeout: 5000 })
+ expect(removeDsh(id)).toMatchObject({ ok: false, error: 'DSH_BUSY' })
+ expect(await update(entry)).toMatchObject({ ok: false, error: 'DSH_BUSY' })
+ expect(await installDsh({ source: repo })).toMatchObject({ ok: false, error: 'DSH_BUSY' })
+ } finally { writeFileSync(gate, '') }
+ expect((await pending).ok).toBe(true)
+ expect(existsSync(join(dshInstallDir(id), 'harness.json'))).toBe(true)
+ })
+})
diff --git a/cli/src/dsh/update.ts b/cli/src/dsh/update.ts
new file mode 100644
index 000000000..fb7e4132c
--- /dev/null
+++ b/cli/src/dsh/update.ts
@@ -0,0 +1,94 @@
+import { existsSync, lstatSync, mkdirSync, realpathSync, renameSync, rmSync } from 'node:fs'
+import { randomUUID } from 'node:crypto'
+import { dirname, join } from 'node:path'
+import { dshRootDir, invalidateInstalledDsh, readInstalledIndex, resolveInstalled, isBrokenDsh, type InstalledDsh } from './installed.js'
+import { catalogEntry, refreshDshRegistry } from './catalog.js'
+import { cloneInstall, finishInstall, type DshInstallOptions, type DshInstallResult } from './install.js'
+import { lockDsh, dshBusy } from './lock.js'
+import { samePackageSource } from './updates.js'
+
+export interface DshUpdateOptions {
+ id: string
+ registry?: DshInstallOptions['registry']
+ onProgress?: DshInstallOptions['onProgress']
+ onLine?: DshInstallOptions['onLine']
+ setupTimeoutMs?: number
+}
+
+/** Replace only the package, retaining the old files and index until the new doctor passes. */
+export async function updateDsh(opts: DshUpdateOptions): Promise<DshInstallResult> {
+ const result = await updatePackage(opts)
+ opts.onProgress?.({ id: opts.id, phase: result.ok ? 'done' : 'failed', ...(!result.ok ? { detail: result.detail } : {}) })
+ return result
+}
+
+async function updatePackage(opts: DshUpdateOptions): Promise<DshInstallResult> {
+ const record = readInstalledIndex().find(row => row.id === opts.id)
+ if (!record) return { ok: false, error: 'NOT_INSTALLED', detail: `${opts.id} is not installed` }
+ if (record.linked) return { ok: false, error: 'LINKED_INSTALL', detail: `${opts.id} is linked to a checkout. Update that checkout directly.` }
+ const unlock = lockDsh(opts.id)
+ if (!unlock) return dshBusy(opts.id)
+ let staged: string | null = null
+ let backup: string | null = null
+ let placed = false
+ let committed = false
+ try {
+ if (!opts.registry) await refreshDshRegistry(true)
+ const catalog = (opts.registry ?? catalogEntry)(opts.id)
+ // A catalog entry with the same id cannot redirect someone's private fork or another folder.
+ const entry = catalog && samePackageSource(record, catalog) ? catalog : undefined
+ const ref = entry?.ref ?? record.ref ?? undefined
+ const path = record.path ?? undefined
+ opts.onProgress?.({ id: opts.id, phase: 'clone', detail: `fetching ${record.source}` })
+ const cloned = await cloneInstall(record.source, ref, path, opts.onLine)
+ if (!cloned.ok) return cloned
+ staged = cloned.tmpDir
+ if (cloned.manifest.id !== record.id) {
+ return { ok: false, error: 'PACKAGE_ID_MISMATCH', detail: `Expected ${record.id}, but the update declares ${cloned.manifest.id}` }
+ }
+ const previous = resolveInstalled(record)
+ if (!isBrokenDsh(previous)) {
+ if ((previous.manifest.kind ?? 'agent') !== (cloned.manifest.kind ?? 'agent')) {
+ return { ok: false, error: 'PACKAGE_KIND_MISMATCH', detail: `The update changes ${record.id} from an agent to a viewer or vice versa` }
+ }
+ if ((record.revision && record.revision === cloned.revision) || (record.commit && record.commit === cloned.commit)) {
+ opts.onLine?.(`${record.id} is already up to date`)
+ return { ok: true, installed: previous, doctor: { ok: true, lines: [] }, setupLines: [] }
+ }
+ }
+ if (existsSync(record.dir)) {
+ // Do not follow a checkout link even if an older/corrupt record calls it a clone.
+ if (lstatSync(record.dir).isSymbolicLink()) return { ok: false, error: 'LINKED_INSTALL', detail: `${record.id} is linked to a checkout. Update that checkout directly.` }
+ backup = join(dshRootDir(), `.previous-${randomUUID()}`)
+ renameSync(record.dir, backup)
+ }
+ mkdirSync(dirname(record.dir), { recursive: true, mode: 0o700 })
+ renameSync(staged, record.dir)
+ placed = true
+ const installed: InstalledDsh = { ...record, ref: ref ?? null, commit: cloned.commit, revision: cloned.revision,
+ updatedAt: Date.now(), manifest: cloned.manifest, realDir: realpathSync(record.dir) }
+ const result = await finishInstall(installed, {
+ ...opts, source: record.source,
+ onProgress: p => { if (p.phase !== 'done' && p.phase !== 'failed') opts.onProgress?.(p) },
+ }, false)
+ committed = result.ok
+ return result
+ } catch (error) {
+ return { ok: false, error: 'UPDATE_FAILED', detail: error instanceof Error ? error.message : String(error) }
+ } finally {
+ try {
+ if (!committed) {
+ if (placed) rmSync(record.dir, { recursive: true, force: true })
+ if (backup) renameSync(backup, record.dir)
+ } else if (backup) {
+ // Cleanup cannot turn a successfully committed update into a reported failure.
+ try { rmSync(backup, { recursive: true, force: true }) } catch { opts.onLine?.(`Previous package retained at ${backup}`) }
+ }
+ if (staged) rmSync(staged, { recursive: true, force: true })
+ } finally {
+ invalidateInstalledDsh()
+ unlock()
+ }
+ }
+}
+
diff --git a/cli/src/dsh/updates.ts b/cli/src/dsh/updates.ts
new file mode 100644
index 000000000..de6f17a03
--- /dev/null
+++ b/cli/src/dsh/updates.ts
@@ -0,0 +1,22 @@
+/** Version facts only: reading the Store never fetches or executes package code. */
+import type { InstalledDshRecord } from './installed.js'
+import type { DshRegistryEntry } from './registry.js'
+
+export const GIT_REVISION_RE = /^[a-f0-9]{40}$/i
+
+export function samePackageSource(installed: InstalledDshRecord, entry: DshRegistryEntry): boolean {
+ const normalize = (source: string): string => source.replace(/\/$/, '').replace(/\.git$/, '')
+ return normalize(installed.source) === normalize(entry.repo) && (installed.path ?? '') === (entry.path ?? '')
+}
+
+export function dshUpdateInfo(installed: InstalledDshRecord, entry?: DshRegistryEntry): {
+ installedCommit: string | null; availableCommit: string | null; updateAvailable: boolean
+} {
+ const availableCommit = entry && samePackageSource(installed, entry) && entry.ref && GIT_REVISION_RE.test(entry.ref)
+ ? entry.ref : null
+ const changed = installed.revision && entry?.revision
+ ? installed.revision !== entry.revision
+ : installed.commit !== availableCommit
+ return { installedCommit: installed.commit, availableCommit,
+ updateAvailable: !installed.linked && availableCommit !== null && changed }
+}
diff --git a/cli/src/dsh/wire.spec.ts b/cli/src/dsh/wire.spec.ts
index a780a8c82..93dd0a1eb 100644
--- a/cli/src/dsh/wire.spec.ts
+++ b/cli/src/dsh/wire.spec.ts
@@ -34,6 +34,7 @@ describe('dshListRows', () => {
expect(rows).toEqual([
{
id: 'autonomous/typst', kind: 'agent', name: 'Typst (local)', description: null, category: null, author: null, engine: 'claude',
+ installedCommit: null, availableCommit: null, updateAvailable: false,
installed: true, linked: true, viewer: true, viewerUse: 'autonomous/doc-viewer', tier: 2,
verified: true, repo: `${HARNESS_MONOREPO}/tree/main/store/agents/typst`, homepage: 'https://typst.example.com',
upstream: 'https://example.com/typst', license: 'MIT', screenshots: ['https://example.com/1.png'],
@@ -41,6 +42,7 @@ describe('dshListRows', () => {
},
{
id: 'acme/private', kind: 'viewer', name: 'Private', description: null, category: null, author: null, engine: null,
+ installedCommit: null, availableCommit: null, updateAvailable: false,
installed: true, linked: false, viewer: true, viewerUse: null, tier: 2,
verified: false, repo: null, homepage: null, upstream: null, license: null, screenshots: [], examples: [],
},
diff --git a/cli/src/dsh/wire.ts b/cli/src/dsh/wire.ts
index 43d9fcfd3..c8c602240 100644
--- a/cli/src/dsh/wire.ts
+++ b/cli/src/dsh/wire.ts
@@ -8,6 +8,7 @@ import { listInstalledDsh, type InstalledDsh } from './installed.js'
import { DSH_ID_RE, dshTier, viewerUse } from './manifest.js'
import { registrySourceUrl, type DshRegistryEntry } from './registry.js'
import { currentDshRegistry } from './catalog.js'
+import { dshUpdateInfo } from './updates.js'
/**
* `dsh_list`: the harnesses installed on this machine, then what the registry offers that is not.
@@ -50,6 +51,7 @@ export function dshListRows(
viewerUse: viewerUse(entry.manifest),
tier: dshTier(entry.manifest),
...facts(entry.id),
+ ...dshUpdateInfo(entry, byId.get(entry.id)),
})
}
for (const entry of registry) {
diff --git a/desktop/lib/core/dsh_catalog.dart b/desktop/lib/core/dsh_catalog.dart
index 4e95f2012..7c85d89bd 100644
--- a/desktop/lib/core/dsh_catalog.dart
+++ b/desktop/lib/core/dsh_catalog.dart
@@ -65,6 +65,9 @@ class DshEntry {
this.screenshots = const [],
this.examples = const [],
this.linked = false,
+ this.installedCommit,
+ this.availableCommit,
+ this.updateAvailable = false,
});
/// `owner/name` — the install directory on the machine and the wire id.
@@ -115,6 +118,10 @@ class DshEntry {
/// Installed as a link to a checkout (`--link`) rather than a clone: a
/// developer's own working copy, which Remove would only unlink.
final bool linked;
+ final String? installedCommit;
+ final String? availableCommit;
+ final bool updateAvailable;
+ bool get hasUpdate => installed && !linked && updateAvailable;
static DshEntry? fromJson(Object? raw) {
if (raw is! Map) return null;
@@ -153,6 +160,9 @@ class DshEntry {
.toList(growable: false)
: const [],
linked: raw['linked'] == true,
+ installedCommit: _commit(raw['installedCommit']),
+ availableCommit: _commit(raw['availableCommit']),
+ updateAvailable: raw['updateAvailable'] == true,
name: name is String && name.trim().isNotEmpty
? name.trim().substring(0, name.trim().length.clamp(0, 40))
: id.substring(id.indexOf('/') + 1),
@@ -198,6 +208,9 @@ class DshEntry {
? raw.trim().substring(0, raw.trim().length.clamp(0, max))
: null;
+ static String? _commit(Object? raw) =>
+ raw is String && RegExp(r'^[a-fA-F0-9]{40}$').hasMatch(raw) ? raw : null;
+
static bool _validId(String id) =>
id.length <= 129 &&
RegExp(r'^[a-z0-9][a-z0-9-]{0,63}/[a-z0-9][a-z0-9-]{0,63}$').hasMatch(id);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 351114ecb..35f4e5ef8 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -291,6 +291,7 @@ class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
late ApiClient api;
+
/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
/// site reads the same in both.
@@ -501,11 +502,9 @@ class AppNotifier extends ChangeNotifier {
final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;
return target == null ||
target.panes.length < maxPanes ||
- target.panes.any(
- (p) =>
- p.machineId == entry.machineId &&
- p.agentId == entry.agentId,
- );
+ target.panes.any(
+ (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,
+ );
}
bool _canReopenSwarm(ClosedSwarm saved) {
@@ -2493,7 +2492,8 @@ class AppNotifier extends ChangeNotifier {
final updater = desktopUpdater ?? DesktopUpdater();
final staged = await updater.downloadAndStage(info);
if (staged == null) {
- updateError = 'Could not download and verify OpenHarness ${info.version}.';
+ updateError =
+ 'Could not download and verify OpenHarness ${info.version}.';
return false;
}
final applied = await updater.applyStaged(staged, selfPid: pid);
@@ -3559,7 +3559,10 @@ class AppNotifier extends ChangeNotifier {
if (decision == null) return;
// The dialog may list the machines, and the person may have moved the choice.
machineId = decision.machineId;
- final error = await _startLocalModelAgent(machineId, prompt: decision.prompt);
+ final error = await _startLocalModelAgent(
+ machineId,
+ prompt: decision.prompt,
+ );
if (error != null) {
_lastError = error;
_lastErrorRetryable = false;
@@ -3591,7 +3594,10 @@ class AppNotifier extends ChangeNotifier {
/// before this dialog had buttons.
///
/// Null on success, else the sentence for the person.
- Future<String?> _startLocalModelAgent(String machineId, {String? prompt}) async {
+ Future<String?> _startLocalModelAgent(
+ String machineId, {
+ String? prompt,
+ }) async {
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
final home = await _homeFolderOf(machine);
@@ -3959,10 +3965,22 @@ class AppNotifier extends ChangeNotifier {
/// narrates progress through `dsh_install_status` pushes, which land in
/// [MachineDsh.installs] for the dialog's status line. Null on success, else
/// a sentence for the person who clicked.
- Future<String?> installDsh(String machineId, String id) async {
+ Future<String?> installDsh(String machineId, String id) =>
+ _installOrUpdateDsh(machineId, id, update: false);
+
+ Future<String?> updateDsh(String machineId, String id) =>
+ _installOrUpdateDsh(machineId, id, update: true);
+
+ Future<String?> _installOrUpdateDsh(
+ String machineId,
+ String id, {
+ required bool update,
+ }) async {
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
final machineName = machine.machine.displayName;
+ final action = update ? 'Update' : 'Install';
+ final verb = update ? 'update' : 'install';
// A new run every time the button is pressed: a retry after a failure is
// its own attempt, with its own clock.
machine.dsh.runs.remove(id);
@@ -3970,9 +3988,9 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
try {
final result = await _conn(machineId).request(
- 'dsh_install',
+ update ? 'dsh_update' : 'dsh_install',
payload: {'id': id},
- timeout: const Duration(minutes: 10),
+ timeout: const Duration(minutes: 90),
);
if (result['ok'] != true) {
final detail = result['detail'];
@@ -3981,26 +3999,26 @@ class AppNotifier extends ChangeNotifier {
id,
detail is String && detail.isNotEmpty
? detail
- : 'Install failed on $machineName',
+ : '$action failed on $machineName',
);
}
} on WsRequestFailure catch (failure) {
return _finishInstall(machine, id, switch (failure.code) {
'UNSUPPORTED' || 'UNSUPPORTED_ON_REMOTE' =>
- 'Update the harness CLI on $machineName to install harnesses',
+ 'Update the harness CLI on $machineName to $verb harnesses',
_ =>
failure.detail?.isNotEmpty == true
? failure.detail!
- : 'Install failed on $machineName (${failure.code})',
+ : '$action failed on $machineName (${failure.code})',
});
} on WsRequestTimeout {
return _finishInstall(
machine,
id,
- '$machineName is still installing. Try again in a few minutes.',
+ '$machineName is still ${update ? 'updating' : 'installing'}. Try again in a few minutes.',
);
} catch (_) {
- return _finishInstall(machine, id, 'Install failed on $machineName');
+ return _finishInstall(machine, id, '$action failed on $machineName');
}
machine.dsh.applyInstall(DshInstallProgress(id: id, phase: 'done'));
notifyListeners();
diff --git a/desktop/lib/store/store_discover.dart b/desktop/lib/store/store_discover.dart
index 48e3075e7..a45677eab 100644
--- a/desktop/lib/store/store_discover.dart
+++ b/desktop/lib/store/store_discover.dart
@@ -595,6 +595,8 @@ class _ProductRow extends StatelessWidget {
child: Text(
entry.isViewerPackage
? 'View'
+ : entry.hasUpdate
+ ? 'Update'
: installed
? 'Open'
: 'Get',
diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dart
index 57242304f..4e1d43357 100644
--- a/desktop/lib/store/store_screen.dart
+++ b/desktop/lib/store/store_screen.dart
@@ -294,7 +294,9 @@ class _StoreTabState extends State<StoreTab> {
void _takeAction(DshEntry entry) {
final local = widget.notifier.localMachineState;
- if (local == null || !_installedOnMachine(local, entry.id)) {
+ if (local == null ||
+ !_installedOnMachine(local, entry.id) ||
+ local.dsh[entry.id]?.hasUpdate == true) {
_openPage(entry.id);
return;
}
@@ -764,6 +766,21 @@ class _ProductPageState extends State<_ProductPage> {
if (failure != null) _say(failure);
}
+ Future<void> _update(String machineId) async {
+ final local = widget.notifier.localMachineState;
+ if (local == null ||
+ local.machine.machineId != machineId ||
+ local.dsh[widget.entry.id]?.hasUpdate != true ||
+ !_busy.add(machineId)) {
+ return;
+ }
+ setState(() {});
+ final failure = await widget.notifier.updateDsh(machineId, widget.entry.id);
+ _busy.remove(machineId);
+ if (mounted) setState(() {});
+ if (failure != null) _say(failure);
+ }
+
Future<void> _remove(String machineId, String machineName) async {
if (widget.notifier.localMachineState?.machine.machineId != machineId) {
return;
@@ -839,6 +856,7 @@ class _ProductPageState extends State<_ProductPage> {
final page = widget.store.reviews[_key];
final local = widget.notifier.localMachineState;
final localInstalled = _installedOnMachine(local, entry.id);
+ final hasUpdate = local?.dsh[entry.id]?.hasUpdate == true;
final base = entry.engine.isNotEmpty
? entry.engine
: (knownHarnessBase[entry.id] ?? '');
@@ -870,7 +888,8 @@ class _ProductPageState extends State<_ProductPage> {
// A viewer package is never opened on its own: once it is here there is
// nothing more to press, and Remove sits in the line beneath.
final showAction =
- local != null && !(entry.isViewerPackage && localInstalled);
+ local != null &&
+ (hasUpdate || !(entry.isViewerPackage && localInstalled));
return LayoutBuilder(
builder: (context, constraints) {
@@ -1017,7 +1036,9 @@ class _ProductPageState extends State<_ProductPage> {
(!localInstalled &&
!_canGetOnMachine(local, entry))
? null
- : () => localInstalled
+ : () => hasUpdate
+ ? _update(local.machine.machineId)
+ : localInstalled
? _open(local.machine.machineId)
: _get(local.machine.machineId),
style: FilledButton.styleFrom(
@@ -1034,6 +1055,8 @@ class _ProductPageState extends State<_ProductPage> {
child: Text(
installing || busy
? 'Working…'
+ : hasUpdate
+ ? 'Update'
: localInstalled
? 'Open'
: failed
@@ -1042,6 +1065,24 @@ class _ProductPageState extends State<_ProductPage> {
),
),
),
+ if (hasUpdate) ...[
+ const SizedBox(height: 10),
+ Text(
+ 'Your projects and files are kept.',
+ style: TextStyle(
+ fontSize: 12.5,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ if (!entry.isViewerPackage)
+ TextButton(
+ key: const ValueKey('store-open-current'),
+ onPressed: busy || installing
+ ? null
+ : () => _open(local!.machine.machineId),
+ child: const Text('Open'),
+ ),
+ ],
const SizedBox(height: 14),
Center(
child: local == null
@@ -1217,10 +1258,14 @@ class _InstallLine extends StatelessWidget {
} else if (run != null && run.failed) {
status =
run.log.where((line) => line.startsWith('miss')).lastOrNull ??
- 'Install failed';
+ (installed
+ ? 'Update failed · previous version kept'
+ : 'Install failed');
} else if (installed) {
status = row?.linked == true
? 'Installed · linked to a checkout'
+ : row?.hasUpdate == true
+ ? 'Update available'
: 'Installed';
} else if (state.needsLink) {
// Why a machine cannot take this package right now, when it cannot. An
@@ -1268,6 +1313,13 @@ class _InstallLine extends StatelessWidget {
: grid.AppPalette.textSecondary,
),
),
+ if (installed && row?.installedCommit != null)
+ Tooltip(
+ message: row?.availableCommit == null
+ ? 'Installed version: ${row!.installedCommit}'
+ : 'Installed: ${row!.installedCommit}\nAvailable: ${row.availableCommit}',
+ child: Text(row.installedCommit!.substring(0, 8), style: faint),
+ ),
if (installed && !installing && !busy) ...[
Text('·', style: faint),
_QuietLink(
diff --git a/desktop/lib/store/store_viewers.dart b/desktop/lib/store/store_viewers.dart
index da95e66cd..03c231fdc 100644
--- a/desktop/lib/store/store_viewers.dart
+++ b/desktop/lib/store/store_viewers.dart
@@ -91,6 +91,11 @@ class StoreViewers extends StatelessWidget {
),
),
),
+ TextButton(
+ key: ValueKey('store-viewer-action:${viewer.id}'),
+ onPressed: () => onOpenAgent(viewer.id),
+ child: Text(viewer.hasUpdate ? 'Update' : 'View'),
+ ),
],
),
if (viewer.description?.isNotEmpty == true) ...[
diff --git a/desktop/test/dsh_catalog_test.dart b/desktop/test/dsh_catalog_test.dart
index 2954cc7dd..13f556c37 100644
--- a/desktop/test/dsh_catalog_test.dart
+++ b/desktop/test/dsh_catalog_test.dart
@@ -46,6 +46,70 @@ const _circuit = {
};
void main() {
+ test('update versions are optional, validated, and offered only for installed clones', () {
+ final old = DshEntry.fromJson(_circuit)!;
+ expect(old.installedCommit, isNull);
+ expect(old.hasUpdate, isFalse);
+ final version = {
+ ..._circuit,
+ 'installed': true,
+ 'installedCommit': 'a' * 40,
+ 'availableCommit': 'b' * 40,
+ 'updateAvailable': true,
+ };
+ final entry = DshEntry.fromJson(version)!;
+ expect(entry.installedCommit, 'a' * 40);
+ expect(entry.availableCommit, 'b' * 40);
+ expect(entry.hasUpdate, isTrue);
+ expect(DshEntry.fromJson({...version, 'linked': true})!.hasUpdate, isFalse);
+ expect(
+ DshEntry.fromJson({...version, 'installed': false})!.hasUpdate,
+ isFalse,
+ );
+ expect(
+ DshEntry.fromJson({...version, 'updateAvailable': 'yes'})!.hasUpdate,
+ isFalse,
+ );
+ expect(
+ DshEntry.fromJson({...version, 'installedCommit': 'main'})!
+ .installedCommit,
+ isNull,
+ );
+ expect(
+ DshEntry.fromJson({...version, 'availableCommit': 123})!.availableCommit,
+ isNull,
+ );
+ });
+
+ test(
+ 'updates use their own request and refresh the installed version',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ connection.answer = (type, payload) async => type == 'dsh_update'
+ ? {'ok': true}
+ : {
+ 'dsh': [
+ {
+ ..._circuit,
+ 'installed': true,
+ 'installedCommit': 'b' * 40,
+ 'updateAvailable': false,
+ },
+ ],
+ };
+ expect(await app.updateDsh('m', _circuit['id']! as String), isNull);
+ expect(connection.calls.map((call) => call.$1), [
+ 'dsh_update',
+ 'dsh_list',
+ ]);
+ expect(
+ app.stateOf('m')!.dsh[_circuit['id']! as String]!.installedCommit,
+ 'b' * 40,
+ );
+ },
+ );
_authorAndKindTests();
_productPageTests();
_installRunTests();
@@ -299,34 +363,28 @@ void _installRunTests() {
expect(done.inProgress, isFalse);
});
- test(
- 'a push is read defensively: ids, phases, and lines without control characters',
- () {
- expect(DshInstallProgress.fromJson(null), isNull);
- expect(DshInstallProgress.fromJson({'id': '', 'phase': 'setup'}), isNull);
- expect(DshInstallProgress.fromJson({'id': 'a/b', 'phase': ''}), isNull);
- expect(DshInstallProgress.fromJson({'id': 1, 'phase': 'setup'}), isNull);
- final escape = String.fromCharCode(27);
- final bell = String.fromCharCode(7);
- final push = DshInstallProgress.fromJson({
- 'id': 'a/b',
- 'phase': 'setup',
- 'detail': ' ',
- 'line': '$escape[32madded$bell ${'n' * 300}',
- })!;
- expect(push.detail, isNull);
- expect(push.line, hasLength(200));
- expect(push.line, startsWith('[32madded n'));
- expect(
- DshInstallProgress.fromJson({
- 'id': 'a/b',
- 'phase': 'setup',
- 'line': 3,
- })!.line,
- isNull,
- );
- },
- );
+ test('a push is read defensively: ids, phases, and lines without control characters', () {
+ expect(DshInstallProgress.fromJson(null), isNull);
+ expect(DshInstallProgress.fromJson({'id': '', 'phase': 'setup'}), isNull);
+ expect(DshInstallProgress.fromJson({'id': 'a/b', 'phase': ''}), isNull);
+ expect(DshInstallProgress.fromJson({'id': 1, 'phase': 'setup'}), isNull);
+ final escape = String.fromCharCode(27);
+ final bell = String.fromCharCode(7);
+ final push = DshInstallProgress.fromJson({
+ 'id': 'a/b',
+ 'phase': 'setup',
+ 'detail': ' ',
+ 'line': '$escape[32madded$bell ${'n' * 300}',
+ })!;
+ expect(push.detail, isNull);
+ expect(push.line, hasLength(200));
+ expect(push.line, startsWith('[32madded n'));
+ expect(
+ DshInstallProgress.fromJson({'id': 'a/b', 'phase': 'setup', 'line': 3})!
+ .line,
+ isNull,
+ );
+ });
test(
'a run keeps its phases in order, a bounded log, and how long each took',
@@ -337,7 +395,11 @@ void _installRunTests() {
expect(run.inProgress, isTrue);
expect(run.took('clone'), isNull);
run.apply(
- const DshInstallProgress(id: 'a/b', phase: 'clone', detail: 'Resolving'),
+ const DshInstallProgress(
+ id: 'a/b',
+ phase: 'clone',
+ detail: 'Resolving',
+ ),
now: t0,
);
run.apply(
diff --git a/desktop/test/store_page_test.dart b/desktop/test/store_page_test.dart
index 196ba89c3..8c9d5c52f 100644
--- a/desktop/test/store_page_test.dart
+++ b/desktop/test/store_page_test.dart
@@ -66,6 +66,8 @@ class _Notifier extends AppNotifier {
final installs = <(String, String)>[];
final removals = <(String, String)>[];
+ final updates = <(String, String)>[];
+ Completer<String?>? updateGate;
Completer<String?>? installGate;
Completer<String?>? removeGate;
int probes = 0;
@@ -92,6 +94,12 @@ class _Notifier extends AppNotifier {
return removeGate?.future;
}
+ @override
+ Future<String?> updateDsh(String machineId, String id) async {
+ updates.add((machineId, id));
+ return updateGate?.future;
+ }
+
void changed() => notifyListeners();
MachineState machine(
@@ -239,6 +247,127 @@ StoreReview _review(
);
void main() {
+ for (final viewer in [false, true]) {
+ testWidgets(
+ 'updates ${viewer ? 'viewers' : 'harnesses'} locally, blocks double clicks and allows retry',
+ (tester) async {
+ const id = 'acme/updateable';
+ final (app, _) = await _open(
+ tester,
+ initialHarness: id,
+ seed: (app) {
+ app.machine(
+ 'machine-1',
+ local: true,
+ dsh: [
+ DshEntry(
+ id: id,
+ name: 'Updateable',
+ engine: viewer ? '' : 'claude',
+ kind: viewer ? 'viewer' : 'agent',
+ installed: true,
+ updateAvailable: true,
+ installedCommit: 'a' * 40,
+ availableCommit: 'b' * 40,
+ ),
+ ],
+ );
+ },
+ );
+ expect(
+ _in('store-primary-action', find.text('Update')),
+ findsOneWidget,
+ );
+ expect(find.text('Your projects and files are kept.'), findsOneWidget);
+ expect(find.text('aaaaaaaa'), findsOneWidget);
+ expect(
+ _key('store-open-current'),
+ viewer ? findsNothing : findsOneWidget,
+ );
+ app.updateGate = Completer<String?>();
+ await tester.tap(_key('store-primary-action'));
+ await tester.pump();
+ await tester.tap(_key('store-primary-action'));
+ expect(app.updates, [('machine-1', id)]);
+ expect(app.installs, isEmpty);
+ expect(_key('store-remove:machine-1'), findsNothing);
+ app.updateGate!.complete('Update failed; previous version kept');
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Update failed; previous version kept'),
+ findsOneWidget,
+ );
+ expect(
+ _in('store-primary-action', find.text('Update')),
+ findsOneWidget,
+ );
+ app.updateGate = null;
+ await tester.tap(_key('store-primary-action'));
+ await tester.pumpAndSettle();
+ expect(app.updates, [('machine-1', id), ('machine-1', id)]);
+ app.machineStates['machine-1']!.dsh.replace([
+ DshEntry(
+ id: id,
+ name: 'Updateable',
+ engine: viewer ? '' : 'claude',
+ kind: viewer ? 'viewer' : 'agent',
+ installed: true,
+ installedCommit: 'b' * 40,
+ ),
+ ]);
+ app.changed();
+ await tester.pumpAndSettle();
+ expect(find.text('Update available'), findsNothing);
+ expect(find.text('bbbbbbbb'), findsOneWidget);
+ expect(
+ _key('store-primary-action'),
+ viewer ? findsNothing : findsOneWidget,
+ );
+ },
+ );
+ }
+
+ testWidgets(
+ 'an Update on a shelf opens its page and a linked checkout offers Open',
+ (tester) async {
+ const entry = DshEntry(
+ id: 'acme/updateable',
+ name: 'Updateable',
+ engine: 'claude',
+ installed: true,
+ updateAvailable: true,
+ );
+ final (app, _) = await _open(
+ tester,
+ seed: (app) {
+ app.machine('machine-1', local: true, dsh: const [entry]);
+ },
+ );
+ await tester.enterText(_key('store-search'), 'Updateable');
+ await tester.pumpAndSettle();
+ expect(
+ _in('store-action:${entry.id}', find.text('Update')),
+ findsOneWidget,
+ );
+ await tester.tap(_key('store-action:${entry.id}'));
+ await tester.pumpAndSettle();
+ expect(_key('store-page:${entry.id}'), findsOneWidget);
+ expect(app.updates, isEmpty);
+ app.machineStates['machine-1']!.dsh.replace(const [
+ DshEntry(
+ id: 'acme/updateable',
+ name: 'Updateable',
+ engine: 'claude',
+ installed: true,
+ linked: true,
+ updateAvailable: true,
+ ),
+ ]);
+ app.changed();
+ await tester.pumpAndSettle();
+ expect(_in('store-primary-action', find.text('Open')), findsOneWidget);
+ },
+ );
// Real glyph widths: the review dialog's buttons are laid out against Arial,
// not against Ahem's squares, which overflow a row no person would see.
setUpAll(loadRealFonts);
diff --git a/desktop/test/store_update_e2e_test.dart b/desktop/test/store_update_e2e_test.dart
new file mode 100644
index 000000000..cfcf68225
--- /dev/null
+++ b/desktop/test/store_update_e2e_test.dart
@@ -0,0 +1,219 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/store/store_screen.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// Real Store button → AppNotifier → WsConn → BackendSocket → update/setup/doctor.
+/// Needs only the companion CLI dependencies; no accounts, model, or installed harness is used.
+void main() {
+ final cliRoot = Platform.environment['DSH_UPDATE_CLI_ROOT'];
+ if (cliRoot == null) {
+ test(
+ 'Store updates end to end',
+ () {},
+ skip: 'Set DSH_UPDATE_CLI_ROOT to the companion CLI checkout.',
+ );
+ return;
+ }
+
+ testWidgets(
+ 'failed release rolls back; retry updates the harness and viewer while preserving the project',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 1800);
+ addTearDown(tester.view.reset);
+ late Directory fixture;
+ late Process daemon;
+ late AppNotifier app;
+ late WsConn connection;
+ final diagnostics = StringBuffer();
+ const id = 'acme/thing';
+ const viewer = 'acme/pane';
+ await tester.runAsync(() async {
+ fixture = await Directory.systemTemp.createTemp('harness-update-e2e-');
+ daemon = await Process.start(
+ 'node',
+ ['--import', 'tsx', 'scripts/smoke-dsh-updates.ts', fixture.path],
+ workingDirectory: cliRoot,
+ environment: {
+ 'HARNESS_DSH_UPDATE_SMOKE': '1',
+ 'ADAPTER_DATA_DIR': '${fixture.path}/data',
+ 'ADAPTER_RUNTIME_DIR': '${fixture.path}/runtime',
+ 'DSH_DIR': '${fixture.path}/installed',
+ 'HARNESS_STORE_CATALOG_URL': 'http://127.0.0.1:9/catalog.json',
+ },
+ );
+ daemon.stderr.transform(utf8.decoder).listen(diagnostics.write);
+ final port = Completer<int>();
+ daemon.stdout
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen(
+ (line) {
+ diagnostics.writeln(line);
+ try {
+ final message = jsonDecode(line);
+ if (message is Map &&
+ message['port'] is int &&
+ !port.isCompleted)
+ port.complete(message['port'] as int);
+ } on FormatException {
+ /* Progress also goes to stdout. */
+ }
+ },
+ onDone: () {
+ if (!port.isCompleted)
+ port.completeError(
+ StateError('Daemon did not start: $diagnostics'),
+ );
+ },
+ );
+ final localPort = await port.future.timeout(
+ const Duration(seconds: 60),
+ );
+ final ready = Completer<void>();
+ connection = WsConn(
+ wsBaseUrl: '',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: fail,
+ onEvent: (event) => unawaited(app.handleEventForTest('m', event)),
+ onStatus: (status) {
+ if (status == ConnectionStatus.connected && !ready.isCompleted)
+ ready.complete();
+ },
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: Uri.parse('ws://127.0.0.1:$localPort'),
+ );
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!
+ ..localOnly = true
+ ..nodeOnline = true;
+ await connection.connect();
+ await ready.future.timeout(const Duration(seconds: 10));
+ await app.probeDsh('m', force: true);
+ });
+ addTearDown(() async {
+ app.dispose();
+ await connection.close();
+ await daemon.stdin.close();
+ await daemon.exitCode.timeout(
+ const Duration(seconds: 10),
+ onTimeout: () {
+ daemon.kill();
+ return -1;
+ },
+ );
+ await fixture.delete(recursive: true);
+ });
+
+ Future<void> open(String packageId) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: StoreTab(
+ key: ValueKey(packageId),
+ notifier: app,
+ initialHarness: packageId,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> waitUntil(bool Function() done) async {
+ await tester.runAsync(() async {
+ final deadline = DateTime.now().add(const Duration(seconds: 30));
+ while (!done()) {
+ if (DateTime.now().isAfter(deadline))
+ fail('Update did not finish: $diagnostics');
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ }
+ });
+ await tester.pumpAndSettle();
+ }
+
+ final catalog = app.stateOf('m')!.dsh;
+ final original = catalog[id]!.installedCommit;
+ await open(id);
+ final action = find.byKey(const ValueKey('store-primary-action'));
+ expect(
+ find.descendant(of: action, matching: find.text('Update')),
+ findsOneWidget,
+ );
+ await tester.tap(action);
+ await tester.pump();
+ expect(catalog.runs[id]!.inProgress, isTrue);
+ await waitUntil(() => catalog.runs[id]!.failed);
+ expect(catalog[id]!.installedCommit, original);
+ expect(catalog[id]!.hasUpdate, isTrue);
+ final afterFailure = await tester.runAsync(
+ () => connection.request('smoke_reopen'),
+ );
+ expect(afterFailure!['preview'], 'my finished project');
+ expect(afterFailure['skill'], 'skill version 1');
+
+ await tester.runAsync(() async {
+ await connection.request('smoke_publish');
+ await app.probeDsh('m', force: true);
+ });
+ await tester.pumpAndSettle();
+ await tester.tap(action);
+ await waitUntil(() => !catalog[id]!.hasUpdate);
+ expect(catalog[id]!.installedCommit, isNot(original));
+ expect(
+ find.descendant(of: action, matching: find.text('Open')),
+ findsOneWidget,
+ );
+ final reopened = await tester.runAsync(
+ () => connection.request('smoke_reopen'),
+ );
+ expect(reopened!['preview'], 'my finished project');
+ expect(reopened['instructions'], 'my custom instructions');
+ expect(reopened['skill'], 'skill version 3');
+ expect(reopened['verdict'], {'ready': true, 'summary': 'finished'});
+
+ await tester.runAsync(() async {
+ await connection.request(
+ 'smoke_publish',
+ payload: {'viewerOnly': true},
+ );
+ await app.probeDsh('m', force: true);
+ });
+ expect(
+ catalog[id]!.hasUpdate,
+ isFalse,
+ reason: 'An unrelated viewer commit does not update the harness',
+ );
+ expect(catalog[viewer]!.hasUpdate, isTrue);
+ await open(viewer);
+ expect(
+ find.descendant(of: action, matching: find.text('Update')),
+ findsOneWidget,
+ );
+ await tester.tap(action);
+ await waitUntil(() => !catalog[viewer]!.hasUpdate);
+ final withNewViewer = await tester.runAsync(
+ () => connection.request('smoke_reopen'),
+ );
+ expect(withNewViewer!['preview'], 'my finished project');
+ expect(
+ action,
+ findsNothing,
+ reason: 'An installed viewer has no standalone Open action',
+ );
+ expect(tester.takeException(), isNull);
+ },
+ timeout: const Timeout(Duration(minutes: 3)),
+ );
+}
diff --git a/docs/plans/2026-09-17-002-harness-updates.md b/docs/plans/2026-09-17-002-harness-updates.md
new file mode 100644
index 000000000..3f0fbff08
--- /dev/null
+++ b/docs/plans/2026-09-17-002-harness-updates.md
@@ -0,0 +1,20 @@
+# Harness package updates
+
+Add explicit updates through `harness dsh update <id>` and the desktop Store. The daemon reports the
+installed and available commits; catalog entries may also carry a package tree revision so publishing
+an unrelated monorepo change does not offer every package an update.
+
+Updates follow the installed repository and package path. Matching catalog entries supply the
+published ref; other installations use their recorded ref. Linked development checkouts are left to
+their owner. Shared viewers can be updated independently from their Store pages.
+
+Fetch and validate the package before replacing anything. Keep the previous package while running
+setup and doctor at the permanent installation path (virtual environments can embed that path).
+Restore it on failure and write the new installed record only after success. Serialize mutations of
+each package across CLI and daemon processes. Do not materialize or migrate workspaces during an
+update: their files, instructions, session identity and stable skill links remain in place.
+
+Verification: real local git repositories for whole-repo and subfolder updates, no-op updates,
+rollback, linked installs, source identity, concurrent mutations and workspace preservation; wire and
+CLI tests; desktop parsing and Store interaction tests; CLI typecheck/full suite and Flutter analysis
+and relevant widget tests. Setup scripts' external side effects cannot be rolled back.
diff --git a/store/tools/catalog.mjs b/store/tools/catalog.mjs
index eb058df0d..ea3c467a1 100644
--- a/store/tools/catalog.mjs
+++ b/store/tools/catalog.mjs
@@ -12,7 +12,7 @@ const ID=/^[a-z0-9][a-z0-9-]{0,63}\/[a-z0-9][a-z0-9-]{0,63}$/;
const PACKAGE_PATH=/^(?!\/)(?!.*\/$)(?!.*\/\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))[A-Za-z0-9._\-/]+$/;
const LIMITS={id:160,name:40,description:300,category:24,author:80,repo:2048,ref:200,path:512,homepage:2048,upstream:2048,license:40,viewerUse:160};
-export function createStoreCatalog(storeDir, ref) {
+export function createStoreCatalog(storeDir, ref, {revisionFor}={}) {
if (!/^[a-f0-9]{40}$/i.test(ref)) throw new Error('Publish from a complete git commit SHA');
const entries=readDshRegistry(storeDir,{strict:true}).sort((a,b)=>a.id.localeCompare(b.id));
const byId=new Map();
@@ -31,7 +31,8 @@ export function createStoreCatalog(storeDir, ref) {
if(entry.screenshots!==undefined){if(!Array.isArray(entry.screenshots)||entry.screenshots.length>8)throw new Error(`${entry.id}: invalid screenshots`);for(const shot of entry.screenshots){if(typeof shot!=='string'||shot.length>2048)throw new Error(`${entry.id}: invalid screenshot`);new URL(shot);}}
const builtIn=entry.repo.replace(/\.git$/,'')===MONOREPO&&entry.path===`store/${entry.kind==='viewer'?'viewers':'agents'}/${entry.id.slice('autonomous/'.length)}`&&entry.id.startsWith('autonomous/');
if(entry.id.startsWith('autonomous/')&&!builtIn)throw new Error(`${entry.id}: autonomous IDs belong to built-in packages`);
- if(builtIn)entry.ref=ref;
+ if(builtIn){entry.ref=ref;const revision=revisionFor?.(entry.path);if(revision!==undefined)entry.revision=revision;}
+ if(entry.revision!==undefined&&!/^[a-f0-9]{40}$/i.test(entry.revision))throw new Error(`${entry.id}: invalid package revision`);
entry.verified=builtIn;
byId.set(entry.id,entry);
}
@@ -65,7 +66,7 @@ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){
const args=process.argv.slice(2),value=flag=>args[args.indexOf(flag)+1];
const storeDir=resolve(args.includes('--store')?value('--store'):fileURLToPath(new URL('..',import.meta.url)));
const ref=args.includes('--ref')?value('--ref'):execFileSync('git',['-C',storeDir,'rev-parse','HEAD'],{encoding:'utf8'}).trim();
- const catalog=createStoreCatalog(storeDir,ref);
+ const catalog=createStoreCatalog(storeDir,ref,{revisionFor:path=>execFileSync('git',['-C',storeDir,'rev-parse',`${ref}:${path}`],{encoding:'utf8'}).trim()});
if(args.includes('--output'))writeFileSync(value('--output'),JSON.stringify(catalog,null,2)+'\n');
if(args.includes('--publish'))console.log(await publishStoreCatalog(catalog,{token:process.env.GITHUB_TOKEN,repository:process.env.GITHUB_REPOSITORY||'autonomous-ai/openharness'}));
else console.log(`Catalog valid: ${catalog.entries.length} packages at ${ref}`);