Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(relay): hosted join — E_JOIN_BUSY, no forget while joining, writable bookmarks dir (R39)

review1fdad45769a2
diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.ts
index c60b23620..d32cb6ea7 100644
--- a/src/main/remote/hosted-join.test.ts
+++ b/src/main/remote/hosted-join.test.ts
@@ -276,7 +276,9 @@ describe('joinHostedTeam', () => {
'bad-token': 'E_JOIN_REFUSED',
network: 'E_JOIN_NETWORK',
revoked: 'E_JOIN_REVOKED',
- 'key-locked': 'E_JOIN_KEY_LOCKED'
+ 'key-locked': 'E_JOIN_KEY_LOCKED',
+ // Another join of OURS for the same team is running: says nothing about the team (R39).
+ busy: 'E_JOIN_BUSY'
}
for (const [kind, codeName] of Object.entries(expected) as Array<[HostedJoinFailure, string]>) {
const e = new HostedJoinError(kind)
@@ -488,7 +490,9 @@ describe('R38: never mint a device token the joiner cannot keep', () => {
await vi.waitFor(() => expect(calls).toEqual(['device']))
// A boot reconnect racing a manual connect (or a double click): refused, with a code that stops a retry loop.
const dup = await connectHostedTeam(codeText, deps, io('b')).catch((e: Error) => e)
- expect(joinErrorCode((dup as Error).message)).toBe('E_JOIN_REFUSED')
+ // Its own code (R39): the renderer must never read "another attempt of yours is running" as a
+ // verdict about the team, and it never retries it.
+ expect(joinErrorCode((dup as Error).message)).toBe('E_JOIN_BUSY')
expect((dup as Error).message).toMatch(/already joining this team/i)
release()
expect(await first).toBe('a')
@@ -498,6 +502,45 @@ describe('R38: never mint a device token the joiner cannot keep', () => {
expect(calls.filter((c) => c === 'device')).toHaveLength(1)
})
+ it('R39: forgetting a team is refused while a join for it is still running (its persist would undo it)', async () => {
+ const s = setup()
+ let release!: () => void
+ const gate = new Promise<void>((r) => { release = r })
+ const minted: string[] = []
+ const gated = (async (url: string) => {
+ if (url.endsWith('/v1/relay/device')) {
+ minted.push('device')
+ await gate
+ return new Response(JSON.stringify({ deviceToken: 'DT', hostId: 'H', exp: 1 }), { status: 200 })
+ }
+ return new Response(JSON.stringify({ pairingToken: 'PT', hostId: 'H', relayEndpoint: 'wss://r', exp: 1 }), { status: 200 })
+ }) as unknown as typeof fetch
+ const running = joinHostedTeam(codeText, { ...s.deps, fetch: gated }, events().ev)
+ await vi.waitFor(() => expect(minted).toEqual(['device']))
+ const refused = await removeHostedBookmark(code.hostId, s.store, s.state).catch((e: Error) => e)
+ expect(refused).toBeInstanceOf(Error)
+ expect((refused as Error).message).toMatch(/still joining/i)
+ release()
+ await running
+ // The join's own persist landed, and nothing was removed out from under it.
+ expect((await s.store.list()).map((b) => b.hostId)).toEqual([code.hostId])
+ // Once it finished, forgetting works — token and bookmark both.
+ await removeHostedBookmark(code.hostId, s.store, s.state)
+ expect(await s.store.list()).toEqual([])
+ })
+
+ it('R39: a bookmarks directory no write could land in refuses the join before any mint', async () => {
+ const s = setup()
+ const locked = new BookmarkStore(s.store.file, {
+ access: async () => { throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }) }
+ })
+ const err = await joinHostedTeam(codeText, { ...s.deps, bookmarks: locked }, events().ev).catch((e: Error) => e)
+ expect(joinErrorCode((err as Error).message)).toBe('E_JOIN_REFUSED')
+ expect((err as Error).message).toContain(s.store.file)
+ expect(s.api.count('device')).toBe(0)
+ expect(s.api.count('join')).toBe(0)
+ })
+
it('revoked forgets the in-memory token: the next attempt mints fresh', async () => {
const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [[403, {}], JOIN_OK] } })
await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'revoked' })
diff --git a/src/main/remote/hosted-join.ts b/src/main/remote/hosted-join.ts
index 947621be9..0928acfd4 100644
--- a/src/main/remote/hosted-join.ts
+++ b/src/main/remote/hosted-join.ts
@@ -44,7 +44,7 @@ import type { JoinErrorCode } from '../../shared/relay-join-errors'
/** What a hosted join hands the relay client: never a pin store. */
export type HostedConnectOptions = Omit<ConnectRelayClientOptions, 'pins' | 'transport'>
-export type HostedJoinFailure = 'invalid-code' | 'rate-limited' | 'refused' | 'network' | 'bad-token' | 'revoked' | 'key-locked'
+export type HostedJoinFailure = 'invalid-code' | 'rate-limited' | 'refused' | 'network' | 'bad-token' | 'revoked' | 'key-locked' | 'busy'
/** Each failure's stable code. `bad-token` is a refusal: a token the service will not accept even
* freshly minted cannot be fixed by retrying, which would only spend damped mints. */
@@ -55,7 +55,8 @@ const CODES: Record<HostedJoinFailure, JoinErrorCode> = {
'bad-token': 'E_JOIN_REFUSED',
network: 'E_JOIN_NETWORK',
revoked: 'E_JOIN_REVOKED',
- 'key-locked': 'E_JOIN_KEY_LOCKED'
+ 'key-locked': 'E_JOIN_KEY_LOCKED',
+ busy: 'E_JOIN_BUSY'
}
const MESSAGES: Record<HostedJoinFailure, string> = {
@@ -65,7 +66,8 @@ const MESSAGES: Record<HostedJoinFailure, string> = {
network: 'Could not reach the nodeterm service. Check the connection and try again.',
'bad-token': "The nodeterm service did not accept this device's token for that team.",
revoked: "This device's relay access was revoked.",
- 'key-locked': 'This device identity could not be loaded.'
+ 'key-locked': 'This device identity could not be loaded.',
+ busy: 'Already joining this team; wait for that attempt to finish.'
}
/** A join that did not reach the relay. `kind` says why; the message is `[<code>] <for the human>`,
@@ -115,12 +117,17 @@ export function createHostedJoinState(): HostedJoinState {
export const hostedJoinState: HostedJoinState = createHostedJoinState()
/** Forget a team: its in-memory token first (so it is gone even if the file refuses the write), then
- * its bookmark. */
+ * its bookmark. Refused — nothing forgotten — while a join for that team is still minting or joining:
+ * that join persists its bookmark (and caches its token) on its way to the relay, which would bring
+ * back exactly what was just forgotten, device token included. */
export function removeHostedBookmark(
hostId: string,
bookmarks: Pick<BookmarkStore, 'remove'>,
state: HostedJoinState = hostedJoinState
): Promise<void> {
+ if (state.inflight.has(hostId)) {
+ return Promise.reject(new Error('Still joining this team; forget it once that attempt finishes.'))
+ }
state.tokens.forget(hostId)
return bookmarks.remove(hostId)
}
@@ -164,11 +171,10 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:
const state = deps.state ?? hostedJoinState
// One join per team at a time, from the first line to the moment the relay client exists. A second
// one (a boot reconnect racing a manual connect, a double click) would mint a second token, and
- // its pending request would replace the first at the host. Refused, with a code that stops a
- // retry loop: the attempt already running is the one that should finish.
- if (state.inflight.has(code.hostId)) {
- throw new HostedJoinError('refused', 'Already joining this team; wait for that attempt to finish.')
- }
+ // its pending request would replace the first at the host. Refused, with a code of its own that
+ // stops a retry loop and says nothing about the team: the attempt already running is the one that
+ // should finish.
+ if (state.inflight.has(code.hostId)) throw new HostedJoinError('busy')
state.inflight.add(code.hostId)
try {
return await joinWithCode(code, deps, ev, state)
diff --git a/src/main/remote/relay-bookmarks.test.ts b/src/main/remote/relay-bookmarks.test.ts
index 3e092f47e..6864ccefd 100644
--- a/src/main/remote/relay-bookmarks.test.ts
+++ b/src/main/remote/relay-bookmarks.test.ts
@@ -66,6 +66,32 @@ describe('relay bookmarks', () => {
expect((err as Error).message).not.toContain('SECRET')
})
+ it('R39: a directory no write could land in is refused for writes, and the refusal names why', async () => {
+ // A readable file on a read-only mount: the read succeeds, every write would fail. The probe a
+ // join runs before minting must see that, or each launch spends a device mint it cannot keep.
+ const file = tmpFile()
+ fs.writeFileSync(file, JSON.stringify([b]))
+ const seen: Array<[string, number]> = []
+ const s = new BookmarkStore(file, {
+ access: async (p, mode) => {
+ seen.push([p, mode])
+ throw Object.assign(new Error('EROFS: read-only file system'), { code: 'EROFS' })
+ }
+ })
+ const err = await s.readForWrite().catch((e: Error) => e)
+ expect(err).toBeInstanceOf(Error)
+ expect((err as Error).message).toMatch(/EROFS/)
+ expect(seen).toEqual([[path.dirname(file), fs.constants.W_OK]])
+ await expect(s.upsert({ ...b, hostId: 'H2' })).rejects.toThrow(/EROFS/)
+ // Display is unaffected: reading is still fine.
+ expect(await s.list()).toEqual([b])
+ })
+
+ it('R39: the directory check passes on an ordinary writable directory (the default seam)', async () => {
+ const s = new BookmarkStore(tmpFile())
+ expect(await s.readForWrite()).toEqual([])
+ })
+
it.skipIf(process.platform === 'win32')('an unreadable file (not a missing one) is refused for writes', async () => {
// A directory where the file should be: reading it fails with EISDIR, which is not absence.
const file = tmpFile()
diff --git a/src/main/remote/relay-bookmarks.ts b/src/main/remote/relay-bookmarks.ts
index 3a517d14b..e69c813d7 100644
--- a/src/main/remote/relay-bookmarks.ts
+++ b/src/main/remote/relay-bookmarks.ts
@@ -9,7 +9,8 @@
// what lets a reconnect confirm our half without a SAS dialog — but only for the exact host key it
// was recorded against (see hosted-join.ts). It deliberately does NOT live in the desktop's
// approved-devices store, which counts paired phones.
-import { promises as fs } from 'node:fs'
+import { constants as fsConstants, promises as fs } from 'node:fs'
+import { dirname } from 'node:path'
import { writeFileAtomic } from '../../core/fs-atomic'
export interface RelayBookmark {
@@ -48,8 +49,16 @@ export class BookmarkStore {
// (a join persisting its token while an earlier join records its approval) never lose each other.
private tail: Promise<unknown> = Promise.resolve()
- /** @param file the bookmarks file; public so a refusal can name it (a path, never contents). */
- constructor(readonly file: string) {}
+ private readonly access: (p: string, mode: number) => Promise<void>
+
+ /** @param file the bookmarks file; public so a refusal can name it (a path, never contents).
+ * @param io.access test seam for the directory check (`fs.access`). */
+ constructor(
+ readonly file: string,
+ io: { access?: (p: string, mode: number) => Promise<void> } = {}
+ ) {
+ this.access = io.access ?? ((p, mode) => fs.access(p, mode))
+ }
/** The bookmarks on disk, for DISPLAY. A missing or unreadable file reads as none; malformed
* entries are dropped. Reading never writes. Never build a write on this: see `readForWrite`. */
@@ -67,8 +76,18 @@ export class BookmarkStore {
* or does not parse, or holds an entry this build does not understand, rejects: rewriting it from
* a guess would silently drop other teams' device tokens and approvals (unknown trust state is
* never overwritten). The refusal names the file, never its contents: they hold tokens.
+ *
+ * It also refuses when no write could LAND: a readable file in a directory this process cannot
+ * write to (a read-only mount, a root-owned data dir) reads fine and then fails every rename. A
+ * join probes this before minting, so such a directory must answer here, not after a device mint
+ * that nothing could keep (every launch would otherwise spend one of the team's damped mints).
*/
async readForWrite(): Promise<RelayBookmark[]> {
+ try {
+ await this.access(dirname(this.file), fsConstants.W_OK)
+ } catch (err) {
+ throw new Error(`relay bookmarks directory is not writable (${(err as NodeJS.ErrnoException)?.code ?? 'unknown error'}); not writing to it`)
+ }
let raw: string
try {
raw = await fs.readFile(this.file, 'utf-8')
diff --git a/src/shared/relay-join-errors.test.ts b/src/shared/relay-join-errors.test.ts
index 7ef64acab..a36d22c4b 100644
--- a/src/shared/relay-join-errors.test.ts
+++ b/src/shared/relay-join-errors.test.ts
@@ -23,4 +23,10 @@ describe('hosted join error codes', () => {
expect(JOIN_ERROR_CODES.filter(joinErrorRetries)).toEqual(['E_JOIN_NETWORK'])
expect(joinErrorRetries(null)).toBe(false)
})
+
+ it('E_JOIN_BUSY is a code of its own (another attempt of ours is running), and it never retries', () => {
+ expect(JOIN_ERROR_CODES).toContain('E_JOIN_BUSY')
+ expect(joinErrorCode('[E_JOIN_BUSY] Already joining this team; wait for that attempt to finish.')).toBe('E_JOIN_BUSY')
+ expect(joinErrorRetries('E_JOIN_BUSY')).toBe(false)
+ })
})
diff --git a/src/shared/relay-join-errors.ts b/src/shared/relay-join-errors.ts
index 5fdfb2136..2cbfb7f71 100644
--- a/src/shared/relay-join-errors.ts
+++ b/src/shared/relay-join-errors.ts
@@ -6,6 +6,8 @@
// code with `joinErrorCode` and decides whether trying again can help: only a network failure can.
// Every other code needs a human (a new code, an unlocked keyring, an owner) or a new day, and
// retrying it would at best repeat the refusal and at worst spend damped device-token mints.
+// `E_JOIN_BUSY` says nothing about the team at all: another join of OURS for the same team is still
+// running, and it is the one that should finish.
export const JOIN_ERROR_CODES = [
'E_JOIN_REVOKED',
@@ -13,7 +15,8 @@ export const JOIN_ERROR_CODES = [
'E_JOIN_RATE',
'E_JOIN_BAD_CODE',
'E_JOIN_NETWORK',
- 'E_JOIN_KEY_LOCKED'
+ 'E_JOIN_KEY_LOCKED',
+ 'E_JOIN_BUSY'
] as const
export type JoinErrorCode = (typeof JOIN_ERROR_CODES)[number]