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.

Merge batch 11-06 k0345: #3269 (#3272)

0xken154dc41f833931
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 50b24e4f7..6e86bee2c 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -29,7 +29,7 @@ vi.mock('../lib/buddyGuard.js', async original => {
import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import type { attachedFiles as attachedFilesType } from './attachments.js'
-import { backend, writeJournal, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmListedFor, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
+import { backend, writeJournal, removeStaleJournalTemps, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmListedFor, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
import { ADDED_MAX } from './deliveryContext.js'
import { SWITCH_ADOPT_MS, SWITCH_HOLD_MS } from './leadSwitch.js'
import { TerminalHost } from './terminal.js'
@@ -1327,6 +1327,30 @@ describe('Super Tab native delivery handoff', () => {
expect(readdirSync(dirname(file)).sort()).toEqual(['host-machine-1.json', 'host-machine-1.json.next'])
})
+ // Task #3514 follow-up (River): a save that crashed between its write and its rename leaves its own temporary file; the
+ // host removes those as it starts, but never one a live process may still be saving through.
+ it('removes its own leftover temporary journal files as it starts, never a live process\'s or another file\'s', () => {
+ const t = setup()
+ const file = hostJournalFile(t.dir, 'machine-1'), folder = dirname(file), base = basename(file)
+ mkdirSync(folder, { recursive: true })
+ const dead = 2 ** 22 + 12_345
+ const left = [`${base}.${dead}.${randomUUID()}.next`, `${base}.${process.pid}.${randomUUID()}.next`]
+ // A live process's, the old fixed name, another machine's (even one a dead process left) and other files: never removed.
+ const kept = [`${base}.${process.ppid}.${randomUUID()}.next`, `${base}.next`, `host-machine-2.json.${dead}.${randomUUID()}.next`,
+ 'observers-machine-1.json.next']
+ for (const name of [...left, ...kept]) writeFileSync(join(folder, name), 'x')
+ expect(() => process.kill(dead, 0)).toThrow()
+ t.open()
+ const now = readdirSync(folder)
+ for (const name of left) expect(now).not.toContain(name)
+ for (const name of kept) expect(now).toContain(name)
+ // The live journal stays, as the host read it.
+ expect(now).toContain(base)
+ expect(t.saved()).toMatchObject({ machineId: 'machine-1' })
+ // The same as one call, which the host makes once.
+ expect(removeStaleJournalTemps(file)).toEqual([])
+ })
+
it('does not type again after a crash between submission and its native acknowledgement', async () => {
const t = setup(), first = t.open()
await first.tick(); first.stop()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index c6128670e..f9a2ded0b 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -14,7 +14,7 @@ import { CommandRetries, permanentRefusal } from './retries.js'
import { NativeRecorder, nativeJournalFile } from './native.js'
import { attachedFiles, attachmentsOf, formatSize, type FilesInFlight, type Relink } from './attachments.js'
import { createHash, randomUUID } from 'node:crypto'
-import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { readdir, readFile } from 'node:fs/promises'
import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'
import { BUDDY_HOME_MANIFEST, BUDDY_HOMES, buddyHomeDue, buddyHomeHoldsLost, buddyHomeRefreshing, pruneBuddyHome, refreshBuddyHome, removeBuddyHome, stopBuddyHomeRefresh } from './buddyHome.js'
@@ -451,6 +451,28 @@ export const BUDDY_SESSION_GONE_MS = 60_000
* idle time counts from the wake, so a Mac that slept through 30 minutes never ends a working session as it wakes (security
* review 1 of #2345). */
export const BUDDY_SESSION_SLEEP_GAP_MS = 2 * 60_000
+/** The temporary files saves of [file] left behind (writeJournal names them `<file>.<pid>.<uuid>.next`): those of this
+ * process, which saves synchronously, so none is in flight as its host starts, and those of a process no longer running.
+ * Never a live process's, which may be saving through it now, nor any other file. Removes them; their names. */
+export function removeStaleJournalTemps(file: string): string[] {
+ const folder = dirname(file), base = basename(file)
+ if (!existsSync(folder)) return []
+ const removed: string[] = []
+ for (const name of readdirSync(folder)) {
+ const match = name.startsWith(`${base}.`) ? /^(\d+)\.[0-9a-f-]{36}\.next$/.exec(name.slice(base.length + 1)) : null
+ if (!match) continue
+ const pid = Number(match[1])
+ if (pid !== process.pid && running(pid)) continue
+ rmSync(join(folder, name), { force: true })
+ removed.push(name)
+ }
+ return removed
+}
+/** Whether process [pid] is running: signal 0 checks without signalling; EPERM is a running process of another user. */
+function running(pid: number): boolean {
+ try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }
+}
+
/** Saves [journal] whole, through a temporary file of its own: a fixed `.next` name let another writer's save move it away
* first, and every save then failed (task #3514: Mac 3's Team host, 11-06, ENOENT on the rename). A save that fails leaves
* no temporary file behind. */
@@ -682,6 +704,11 @@ export class SuperTabHost {
post: (tabId, agentId, operationId, command) => backend(core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId, asAgentId: agentId, command }),
transcript: harnessId => core.agents.byAgent(harnessId)?.transcriptPath, tokens: conversationTokens })
this.sources = options.sources ?? { feed: new HostFeed(core, machineId, { now: this.now }), reads: new SwarmReads(core) }
+ // A save that crashed between its write and its rename left its temporary file behind (writeJournal): gone as the host starts.
+ try {
+ const removed = removeStaleJournalTemps(this.file)
+ if (removed.length) this.log(`Removed ${removed.length} leftover temporary journal ${removed.length === 1 ? 'file' : 'files'}.`)
+ } catch (error) { this.log(`Leftover temporary journal files: ${error instanceof Error ? error.message : String(error)}`) }
this.journal = { version: 1, machineId, entries: {} }
if (existsSync(this.file)) {
const raw = readFileSync(this.file, 'utf8')