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.

feat(renderer): hosted team approval dialog, invite code, pinned reconnect, viewer banner

review09cc4646ee29
diff --git a/src/core/relay/access-policy.guard.test.ts b/src/core/relay/access-policy.guard.test.ts
index 92f25659b..294db4dbe 100644
--- a/src/core/relay/access-policy.guard.test.ts
+++ b/src/core/relay/access-policy.guard.test.ts
@@ -5,10 +5,13 @@ import fs from 'node:fs'
import path from 'node:path'
import { IPC } from '../../shared/ipc'
import { VIEW, COMMENT, EDITOR_ONLY, VIEW_EVENTS } from './access-policy'
+import { HOSTED_VIEW_METHODS, HOSTED_COMMENT_METHODS } from '../../shared/hosted-access'
+import type { HostedRole } from '../../shared/types'
+import type { TeamRole } from './team-store'
const ROOT = path.resolve(__dirname, '../../..')
const read = (p: string) => fs.readFileSync(path.join(ROOT, p), 'utf8').replace(/\r\n/g, '\n')
-const BUILDERS = ['buildRealApi', 'buildFilesApi', 'buildGitHubApi', 'buildAgentApi', 'buildCanvasApi', 'buildPresenceApi', 'buildClaudeApi']
+const BUILDERS = ['buildRealApi', 'buildFilesApi', 'buildGitHubApi', 'buildAgentApi', 'buildCanvasApi', 'buildPresenceApi', 'buildClaudeApi', 'buildHostedApi']
function body(src: string, fn: string): string {
const start = src.indexOf(`export function ${fn}(`)
@@ -46,4 +49,15 @@ describe('access-policy guard', () => {
.filter((v) => !Object.hasOwn(VIEW, v) && !Object.hasOwn(COMMENT, v) && !EDITOR_ONLY.has(v))
expect(undecided, `classify these in access-policy.ts: ${undecided.join(', ')}`).toEqual([])
})
+ it('the renderer\'s mirror names exactly the host\'s viewer and commenter channels', () => {
+ // A channel the host opens to viewers that the mirror does not name silently disappears from a
+ // viewer's tab (refused locally); one the mirror names that the host does not is refused anyway.
+ expect([...HOSTED_VIEW_METHODS].sort()).toEqual(Object.keys(VIEW).sort())
+ expect([...HOSTED_COMMENT_METHODS].sort()).toEqual(Object.keys(COMMENT).sort())
+ })
+ it('the renderer\'s role names are the team store\'s', () => {
+ const toShared = (r: TeamRole): HostedRole => r
+ const toCore = (r: HostedRole): TeamRole => r
+ expect([toShared('viewer'), toCore('owner')]).toEqual(['viewer', 'owner'])
+ })
})
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index d14475cdc..6173056a1 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -288,6 +288,17 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
// Canvas edits and the one presence cast VIEW does not list.
IPC.canvasMut,
IPC.presenceDino,
+ // The hosted team verbs (renderer `buildHostedApi`). INTERCEPTED by hosted-service.ts before this
+ // table is ever consulted, which judges each caller itself (`self`: any member; the rest: owners
+ // only) — so this table never decides them. Listed so the guard sees a decision, not a gap. Their
+ // events reach owners only (hosted-service `tellOwners`), never through VIEW_EVENTS.
+ IPC.relayHostedSelf,
+ IPC.relayHostedPending,
+ IPC.relayHostedInviteCode,
+ IPC.relayHostedApprove,
+ IPC.relayHostedDeny,
+ IPC.relayHostedPeerPending,
+ IPC.relayHostedPendingClosed,
// Server→client events (see the doc comment): what a non-editor receives is VIEW_EVENTS.
IPC.workspaceMigrated,
IPC.workspaceCorruptRecovered,
diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.ts
index 03f8cf204..9ce7e2aea 100644
--- a/src/core/relay/hosted-service.ts
+++ b/src/core/relay/hosted-service.ts
@@ -39,6 +39,7 @@ import { createHostedScheduler, type Listener, type SchedulerStatus } from './ho
import { encodeJoinCode } from './join-code'
import type { KeyPair } from './e2ee'
import type { UiSink } from '../ui-sink-registry'
+import type { HostedPending as SharedHostedPending, HostedPendingClosedReason } from '../../shared/types'
/** An unanswered join request is refused after ten minutes. */
export const PENDING_TTL_MS = 600_000
@@ -56,10 +57,12 @@ const JOIN_LABEL_MAX = 60
const NOT_A_MEMBER = 'You are not a member of this team.'
-export interface HostedPending { pendingId: string; sas: string; peerKeyB64: string; since: number }
+/** A device waiting for an owner. The renderer's type IS this one (one definition, in shared). */
+export type HostedPending = SharedHostedPending
/** Why a pending request stopped being pending, as told to owners on `relay:hosted:pending-closed`.
- * `replaced`: the same device connected again, and its newer request took this one's place. */
-export type PendingClosedReason = 'approved' | 'denied' | 'expired' | 'replaced' | 'gone'
+ * `replaced`: the same device connected again, and its newer request took this one's place. Shared
+ * with the renderer, so a reason added here without its owner-dialog handling fails to compile there. */
+export type PendingClosedReason = HostedPendingClosedReason
/** `stopped`: a `stop()` landed after this `start()` was called and before it finished; it wins. */
export type HostedStartResult = 'started' | 'no-team' | 'host-key-unreadable' | 'stopped'
/** `not-running`: the key was rotated on a service that was not hosting, and hosting stays off. */
diff --git a/src/core/relay/join-code.ts b/src/core/relay/join-code.ts
index 38954ebbf..34a032979 100644
--- a/src/core/relay/join-code.ts
+++ b/src/core/relay/join-code.ts
@@ -3,9 +3,12 @@
// The host key inside is what authenticates the host to the joiner, and the hostId must derive
// from it, so a code cannot point a teammate at a different room than the key it carries.
import { hostIdFromPublicKeyB64 } from './relay-id'
+// The prefix is shared with the renderer (which cannot import this file); one definition.
+import { JOIN_CODE_PREFIX as PREFIX, isJoinCode } from '../../shared/relay-join-code'
+
+export { isJoinCode }
export interface JoinCode { v: 1; relayEndpoint: string; hostId: string; hostPublicKeyB64: string; hostDeviceId: string; label: string }
-const PREFIX = 'nodeterm://join?code='
/** A relay endpoint we will dial: `wss:` anywhere, plaintext `ws:` only to loopback. Applied to a
* code's endpoint AND to the one the join API hands back, so neither can send a client token over
@@ -22,10 +25,6 @@ export function encodeJoinCode(c: JoinCode): string {
return PREFIX + Buffer.from(JSON.stringify(c), 'utf-8').toString('base64url')
}
-export function isJoinCode(s: string): boolean {
- return s.trim().startsWith(PREFIX)
-}
-
export function decodeJoinCode(s: string): JoinCode | null {
const t = s.trim()
if (!t.startsWith(PREFIX)) return null
diff --git a/src/renderer/bridge/hosted-gate.ts b/src/renderer/bridge/hosted-gate.ts
new file mode 100644
index 000000000..f6dc85098
--- /dev/null
+++ b/src/renderer/bridge/hosted-gate.ts
@@ -0,0 +1,44 @@
+// The RpcClient a hosted team's relay tab talks through: it sends only what the tab's ROLE may send.
+//
+// A Viewer or Commenter's tab would otherwise send the host everything an editor's does — the
+// autosave, every canvas edit, keystrokes, and a handful of editor-only probes components make on
+// mount — and the host refuses each one (E_ROLE). Nothing is gained by the round trip, and a tab
+// that opens into a wall of refusals is noise on both ends. So a call the role may not make is
+// answered HERE, in the host's own words and with its code (`hostedRoleRefusal`), and a cast is
+// dropped: every caller behaves exactly as it would have on the host's refusal.
+//
+// This is a mirror, never the boundary — the host enforces roles on every message whatever this
+// sends (src/core/relay/access-policy.ts). Until the role is known it is the LOWEST one: the tab
+// learns it before anything mounts (relay-tab `openRelayTab`), and fail-closed is the direction a
+// wrong guess must err in. Only a relay tab joined by a hosted team's code is built with this; a
+// Team Access relay tab keeps the plain RpcClient. See docs/hosted-team-relay.md.
+import { hostedMayCall, hostedRoleRefusal } from '../../shared/hosted-access'
+import type { HostedRole } from '../../shared/types'
+import type { FrameTransport } from './frame-transport'
+import { RpcClient } from './ws-bridge'
+
+export class RoleGatedRpcClient extends RpcClient {
+ constructor(
+ transport: FrameTransport,
+ private readonly role: () => HostedRole | null
+ ) {
+ super(transport)
+ }
+
+ override request(method: string, ...args: unknown[]): Promise<unknown> {
+ const role = this.role()
+ if (!hostedMayCall(role, method)) {
+ const refused = Promise.reject(hostedRoleRefusal(role))
+ // Some callers fire and forget (`void client.request(...)`, e.g. the read-on-view ack): the
+ // refusal must not surface as an unhandled rejection. Anyone who awaits it still gets it.
+ refused.catch(() => {})
+ return refused
+ }
+ return super.request(method, ...args)
+ }
+
+ override cast(method: string, ...args: unknown[]): void {
+ if (!hostedMayCall(this.role(), method)) return
+ super.cast(method, ...args)
+ }
+}
diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.ts
index ee224c6f5..c29ac8473 100644
--- a/src/renderer/bridge/relay-api.test.ts
+++ b/src/renderer/bridge/relay-api.test.ts
@@ -157,3 +157,128 @@ describe('buildRelayApi', () => {
expect(_check).toBeTruthy()
})
})
+
+describe('buildRelayApi — hosted team tabs', () => {
+ let saved: unknown
+ beforeEach(() => {
+ saved = (globalThis as Record<string, unknown>).window
+ ;(globalThis as Record<string, unknown>).window = { nodeTerminal: fakeLocalApi().local }
+ })
+ afterEach(() => {
+ ;(globalThis as Record<string, unknown>).window = saved
+ })
+
+ const methods = (t: FakeTransport): string[] => t.sent.map((f) => JSON.parse(f).method as string)
+ const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))
+
+ it('a Team Access relay tab (no hosted option) takes the OLD path: no hosted api, nothing gated', async () => {
+ const t = new FakeTransport()
+ const handle = buildRelayApi('conn-1', t)
+ expect('hosted' in handle.api).toBe(false)
+ expect(handle.setHostedRole).toBeUndefined()
+ // Editor-only calls still go on the wire exactly as before.
+ handle.api.pty.write('s1', 'ls\r')
+ void handle.api.workspace.save({ version: 2, activeProjectId: '', projects: [] })
+ handle.api.canvas.mutate('p1', { op: 'remove', id: 'n1' } as never)
+ expect(methods(t)).toEqual([IPC.ptyWrite, IPC.workspaceSave, IPC.canvasMut])
+ })
+
+ it('a hosted tab has the hosted verbs, sent as ordinary requests', () => {
+ const t = new FakeTransport()
+ const { api } = buildRelayApi('conn-1', t, { hosted: true })
+ expect(api.hosted).toBeTruthy()
+ void api.hosted!.self()
+ void api.hosted!.pending()
+ void api.hosted!.inviteCode()
+ void api.hosted!.approve('p1', 'editor')
+ void api.hosted!.deny('p2')
+ expect(t.sent.map((f) => JSON.parse(f))).toMatchObject([
+ { t: 'req', method: IPC.relayHostedSelf },
+ { t: 'req', method: IPC.relayHostedPending },
+ { t: 'req', method: IPC.relayHostedInviteCode },
+ { t: 'req', method: IPC.relayHostedApprove, args: ['p1', 'editor'] },
+ { t: 'req', method: IPC.relayHostedDeny, args: ['p2'] }
+ ])
+ })
+
+ it('hosted events reach the subscribers, including ones pushed before anyone subscribed', () => {
+ const t = new FakeTransport()
+ const { api } = buildRelayApi('conn-1', t, { hosted: true })
+ const pending = { pendingId: 'x', sas: '1 2', peerKeyB64: 'K', since: 1 }
+ // An owner replay frame that lands before the tab has subscribed (R25): held, then delivered.
+ t.emit(JSON.stringify({ t: 'ev', channel: IPC.relayHostedPeerPending, args: [pending] }))
+ const seen: unknown[] = []
+ api.hosted!.onPeerPending((p) => seen.push(p))
+ api.hosted!.onPendingClosed((p) => seen.push(p))
+ t.emit(JSON.stringify({ t: 'ev', channel: IPC.relayHostedPendingClosed, args: [{ pendingId: 'x', reason: 'denied' }] }))
+ expect(seen).toEqual([pending, { pendingId: 'x', reason: 'denied' }])
+ })
+
+ it('before the role is known, a hosted tab sends only what a viewer may (fail closed)', async () => {
+ const t = new FakeTransport()
+ const { api } = buildRelayApi('conn-1', t, { hosted: true })
+ api.pty.write('s1', 'rm -rf /\r')
+ api.canvas.mutate('p1', { op: 'remove', id: 'n1' } as never)
+ const save = api.workspace.save({ version: 2, activeProjectId: '', projects: [] })
+ await expect(save).rejects.toMatchObject({ code: 'E_ROLE' })
+ void api.workspace.load()
+ void api.hosted!.self()
+ expect(methods(t)).toEqual([IPC.workspaceLoad, IPC.relayHostedSelf])
+ })
+
+ it('a viewer never sends the autosave, canvas edits, typing or the editor-only probes', async () => {
+ const t = new FakeTransport()
+ const handle = buildRelayApi('conn-1', t, { hosted: true })
+ handle.setHostedRole!('viewer')
+ const { api } = handle
+ api.pty.write('s1', 'x')
+ api.pty.recycle('n1')
+ api.canvas.mutate('p1', { op: 'remove', id: 'n1' } as never)
+ api.presence.chat('hi')
+ const refusals = await Promise.allSettled([
+ api.workspace.save({ version: 2, activeProjectId: '', projects: [] }),
+ api.claude.cliCaps(),
+ api.git.worktreeList('/repo')
+ ])
+ await flush()
+ // Only the viewer-safe calls below reach the wire.
+ void api.pty.create({ persistKey: 'n1', cols: 80, rows: 24 } as never)
+ api.presence.cursor({ x: 1, y: 2 } as never)
+ void api.hosted!.approve('p1', 'viewer') // judged by the host itself
+ expect(methods(t)).toEqual([IPC.ptyCreate, IPC.presenceCursor, IPC.relayHostedApprove])
+ expect(refusals[0]).toMatchObject({ status: 'rejected', reason: { code: 'E_ROLE' } })
+ })
+
+ it('a local refusal is never an UNHANDLED rejection (fire-and-forget callers like ackDone stay quiet)', async () => {
+ const t = new FakeTransport()
+ const handle = buildRelayApi('conn-1', t, { hosted: true })
+ handle.setHostedRole!('viewer')
+ const unhandled: unknown[] = []
+ const onUnhandled = (reason: unknown): void => { unhandled.push(reason) }
+ process.on('unhandledRejection', onUnhandled)
+ try {
+ handle.api.ackDone('n1') // `void client.request(...)` inside: nobody catches it
+ await flush()
+ await flush()
+ } finally {
+ process.off('unhandledRejection', onUnhandled)
+ }
+ expect(unhandled).toEqual([])
+ expect(t.sent).toEqual([])
+ // A caller that does await it still sees the refusal.
+ await expect(handle.api.workspace.save({ version: 2, activeProjectId: '', projects: [] })).rejects.toMatchObject({ code: 'E_ROLE' })
+ })
+
+ it('a commenter may also chat; an editor sends everything', () => {
+ const t = new FakeTransport()
+ const handle = buildRelayApi('conn-1', t, { hosted: true })
+ handle.setHostedRole!('commenter')
+ handle.api.presence.chat('hi')
+ handle.api.pty.write('s1', 'x')
+ expect(methods(t)).toEqual([IPC.presenceChat])
+ handle.setHostedRole!('editor')
+ handle.api.pty.write('s1', 'x')
+ handle.api.canvas.mutate('p1', { op: 'remove', id: 'n1' } as never)
+ expect(methods(t)).toEqual([IPC.presenceChat, IPC.ptyWrite, IPC.canvasMut])
+ })
+})
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 45c24dcd1..f97b216c2 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -30,10 +30,12 @@
// calls `buildRelayApi` while the approval dialog is still open, THEN awaits `ready()`. Building
// it after approval already fired leaves `ready()` pending forever and the api never comes up.
-import type { NodeTerminalApi } from '../../shared/types'
+import type { HostedRole, NodeTerminalApi } from '../../shared/types'
import { type FrameTransport, RelayFrameTransport } from './frame-transport'
+import { RoleGatedRpcClient } from './hosted-gate'
import {
RpcClient,
+ buildHostedApi,
buildRealApi,
buildFilesApi,
buildAgentApi,
@@ -55,6 +57,16 @@ export interface RelayApiHandle {
ready(): Promise<void>
/** Tear the connection down: close the relay socket for this connectionId. */
close(): void
+ /** HOSTED tabs only: tell the role gate which role the host gave this device (the tab asks
+ * `hosted.self()` before anything mounts). Absent on every other relay tab. */
+ setHostedRole?(role: HostedRole): void
+}
+
+/** How to build a relay tab's api. */
+export interface RelayApiOptions {
+ /** A relay tab joined by a hosted team's `nodeterm://join` code: it gets `api.hosted` and a role
+ * gate on everything it sends. Absent/false = a Team Access relay tab, built exactly as before. */
+ hosted?: boolean
}
/**
@@ -62,11 +74,19 @@ export interface RelayApiHandle {
* nothing and a `RelayFrameTransport(connectionId)` is constructed here (which is what registers the
* one-shot `onApproved` listener; see gotcha 2).
*/
-export function buildRelayApi(connectionId: string, transport?: FrameTransport): RelayApiHandle {
+export function buildRelayApi(
+ connectionId: string,
+ transport?: FrameTransport,
+ opts?: RelayApiOptions
+): RelayApiHandle {
// The LOCAL preload — this is a desktop-only path (relay hosting/joining is Electron), so
// `window.nodeTerminal` is the full real preload, not the browser stub surface.
const local = (window as unknown as { nodeTerminal: NodeTerminalApi }).nodeTerminal
- const client = new RpcClient(transport ?? new RelayFrameTransport(connectionId))
+ const carrier = transport ?? new RelayFrameTransport(connectionId)
+ // A hosted tab's role, once the host has said it. Unknown = the lowest role (hosted-gate.ts).
+ let hostedRole: HostedRole | null = null
+ const hosted = opts?.hosted === true
+ const client = hosted ? new RoleGatedRpcClient(carrier, () => hostedRole) : new RpcClient(carrier)
const real = buildRealApi(client) // { pty, workspace, settings, userDataDir }
const files = buildFilesApi(client) // { fs, git, files, context }
@@ -164,12 +184,18 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
sendHostChatReply: stub.sendHostChatReply,
// Messaging rides the same decision: the browser client is never a sender (constraint 5 of
// the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).
- agentMessage: stub.agentMessage
+ agentMessage: stub.agentMessage,
+
+ // The hosted team verbs — ONLY on a tab joined by a hosted team's code. A Team Access relay
+ // tab's host answers none of them, so there the key is absent altogether (never `undefined`),
+ // and every `api.hosted` check in the renderer takes its old path.
+ ...(hosted ? buildHostedApi(client) : {})
} satisfies NodeTerminalApi
return {
api,
ready: () => client.ready(),
- close: () => local.relayClient.disconnect(connectionId)
+ close: () => local.relayClient.disconnect(connectionId),
+ ...(hosted ? { setHostedRole: (role: HostedRole) => { hostedRole = role } } : {})
}
}
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index b1d4e5f18..23214cc88 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -208,3 +208,20 @@ describe('buildClaudeAccountsApi', () => {
await expect(s.codexAccounts.remove('a1')).rejects.toMatchObject({ code: E_UNSUPPORTED })
})
})
+
+/**
+ * The hosted team verbs belong to a RELAY tab joined by a hosted team's code, never to a Server
+ * Edition browser tab: a browser never joins a relay host (its `relayHosted` stub answers no
+ * bookmarks), and the server it is served from does not answer `relay:hosted:*` to its own browser
+ * (hosted-service intercepts them for relay peers only). So installWsBridge must not spread
+ * `buildHostedApi` — its api has no `hosted` key, and every `api.hosted` check in the renderer takes
+ * its old path there. installWsBridge needs a socket + DOM to run, so this is pinned by source text.
+ */
+describe('buildHostedApi and the Server Edition', () => {
+ it('is never spread into the browser\'s window.nodeTerminal', () => {
+ const src = readFileSync(join(__dirname, 'ws-bridge.ts'), 'utf8')
+ const install = src.slice(src.indexOf('export async function installWsBridge'))
+ expect(install).not.toContain('buildHostedApi')
+ expect(install).not.toMatch(/\bhosted\s*:/)
+ })
+})
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 6b5fb11bf..448f1a0a5 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -31,6 +31,9 @@ import {
type ClaudeCliCaps,
type GrokApi,
type GrokCliCaps,
+ type HostedPending,
+ type HostedSelf,
+ type HostedSessionApi,
type ClaudeSkillShareResult,
type ClaudeSessionCopyResult,
type CodexApi,
@@ -744,6 +747,27 @@ export function buildPresenceApi(client: RpcClient): Pick<NodeTerminalApi, 'pres
return { presence }
}
+/**
+ * Build the hosted-team verbs of ONE relay session (`NodeTerminalApi.hosted`). Only a relay tab
+ * joined by a `nodeterm://join` code spreads this (relay-api.ts, `{ hosted: true }`): a Server
+ * Edition browser never joins a relay host, and a Team Access relay tab (desktop to desktop) talks
+ * to a host that answers none of these, so both leave `hosted` absent. The host core answers every
+ * request itself (src/core/relay/hosted-service.ts) and judges the caller's role: `self` is open to
+ * any member, the rest are owner-only. `peer-pending` / `pending-closed` reach connected OWNERS only.
+ */
+export function buildHostedApi(client: RpcClient): Required<Pick<NodeTerminalApi, 'hosted'>> {
+ const hosted: HostedSessionApi = {
+ self: () => client.request(IPC.relayHostedSelf) as Promise<HostedSelf>,
+ pending: () => client.request(IPC.relayHostedPending) as Promise<HostedPending[]>,
+ inviteCode: () => client.request(IPC.relayHostedInviteCode) as Promise<string | null>,
+ approve: (pendingId, role) => client.request(IPC.relayHostedApprove, pendingId, role) as Promise<boolean>,
+ deny: (pendingId) => client.request(IPC.relayHostedDeny, pendingId) as Promise<boolean>,
+ onPeerPending: (listener) => client.subscribe(IPC.relayHostedPeerPending, listener as Listener),
+ onPendingClosed: (listener) => client.subscribe(IPC.relayHostedPendingClosed, listener as Listener)
+ }
+ return { hosted }
+}
+
/**
* Build the `speech` namespace over an RpcClient — a REAL implementation (the server registers
* `registerSpeechIpc` too; see `src/core/speech/register-ipc.ts`), not a stub. The one wire
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 19447fa0b..a2dda5f15 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -480,6 +480,14 @@ import {
reconnectRelayTab,
type RelayTab,
} from '../session/relay-tab'
+import { HostedApprovalDialog } from '../components/HostedApprovalDialog'
+import { isJoinCode } from '@shared/relay-join-code'
+import { createHostedJoiner, type HostedJoiner, type HostedMountOutcome } from '../lib/hostedJoin'
+import { HOSTED_APPROVAL_WAIT_MS, isReadOnlyRole, stripIpcPrefix, viewerBannerText, waitingForOwnerText } from '../lib/hostedTeam'
+import { answerHostedRequest, type HostedAnswer } from '../lib/hostedOwner'
+import { headRequest, type QueuedRequest } from '../lib/hostedPendingQueue'
+import { useHostedPending } from '../state/hostedPending'
+import { hostedInfoFor, isHostedReadOnly, useHostedTeams } from '../state/hostedTeams'
import { buildContextLinkNote, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'
import {
launchesToFire,
@@ -535,6 +543,7 @@ import type {
ClaudeSessionCopyResult,
CanvasNodeState,
ClosedSessionEntry,
+ HostedSessionApi,
NodeKind,
PendingLaunch,
Project,
@@ -700,6 +709,9 @@ function noticeDwellMs(text: string): number {
return Math.min(NOTICE_MAX_MS, NOTICE_MS + text.length * 25)
}
+/** React Flow props for a hosted team tab whose role is below Editor. */
+const HOSTED_READ_ONLY_FLOW = { nodesDraggable: false, nodesConnectable: false } as const
+
/** The confirm dialogs, named so their setters can be wrapped in a synchronous open-guard (see
* `confirmFlags`): ONE confirm at a time, decided at call time rather than at the next render. */
interface ConfirmState {
@@ -1320,7 +1332,10 @@ export function Canvas() {
if (tab.projectId === projectId) relayTabsRef.current.delete(connectionId)
}
const s = sessionForProject(projectId)
- if (s.source === 'relay') disposeSession(s.id)
+ if (s.source === 'relay') {
+ disposeSession(s.id)
+ useHostedTeams.getState().forget(s.id) // a no-op for a Team Access relay tab
+ }
}, [])
const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)
// "Connect over SSH…" project-creation dialog (from the Welcome screen).
@@ -1343,6 +1358,23 @@ export function Canvas() {
const sshPassphraseRequest = sshPassphraseQueue[0] ?? null
// A client has finished the handshake and is awaiting this host's approval (carries the SAS).
const [pendingPeer, setPendingPeerState] = useState<PendingPeerState | null>(null)
+ // Devices asking to join a hosted team this device OWNS (lib/hostedPendingQueue.ts, fed per owner
+ // tab by relay-tab's owner subscription): the oldest is on screen, the rest wait their turn. Empty
+ // for anyone who owns no hosted team, so nothing renders.
+ const hostedHead = useHostedPending((st) => headRequest(st.queue))
+ const hostedMore = useHostedPending((st) => Math.max(0, st.queue.items.length - 1))
+ const hostedPendingNotice = useHostedPending((st) => st.notice)
+ useEffect(() => {
+ if (hostedPendingNotice) setNotice({ kind: 'info', text: hostedPendingNotice.text })
+ }, [hostedPendingNotice])
+ const answerHosted = useCallback((item: QueuedRequest, answer: HostedAnswer) => {
+ // Off the queue at once (the dialog closes; the host's own close follows), then say only what
+ // did not land.
+ useHostedPending.getState().settle(item.pending.pendingId)
+ void answerHostedRequest(item, answer).then((line) => {
+ if (line) setNotice(line)
+ })
+ }, [])
const [confirm, setConfirmState] = useState<ConfirmState | null>(null)
// The closed-session entry whose transcript is on screen (issue #531), or null. A SNAPSHOT of
// the ledger row, not a reference into the store: reading it needs only the pointer it carries.
@@ -1690,6 +1722,10 @@ export function Canvas() {
// `usePresence(sel)` hook) is the PERF CONTRACT: a peer's 20 Hz cursor never re-renders Canvas.
const activeSession = sessionForProject(activeProjectId || '')
const activePresence = presenceForProject(activeProjectId || '')
+ // The active tab's hosted team, when it is one (undefined for every other tab). A role below Editor
+ // makes the canvas read-only in the UI; the host enforces the role either way.
+ const activeHosted = useHostedTeams((st) => st.bySession[activeSession.id])
+ const hostedReadOnly = isReadOnlyRole(activeHosted?.role)
// "Has projects" = at least one OPEN (non-closed) tab. With only closed projects left, the
// welcome screen shows (and lists them under "Recently closed" for reopening).
const hasProjects = useProjects((s) => s.projects.some((p) => !p.closed))
@@ -2791,6 +2827,8 @@ export function Canvas() {
(next: ProjectKanban) => {
const id = useProjects.getState().activeProjectId
if (!id) return
+ // A hosted Viewer/Commenter's board is the host's to change: a move here would only diverge.
+ if (isHostedReadOnly(sessionForProject(id).id)) return
// The board BEFORE this change — read fresh at callback entry (a stale closed-over value
// would misattribute the diff). Same lazy-default as the KanbanView render.
const prev = useProjects.getState().getProject(id)?.kanban ?? seedBoard
@@ -3347,7 +3385,8 @@ export function Canvas() {
activeSession.api.canvas.mutate(projectId, m)
return true
},
- { src, shouldPublish: () => hasPeersRef.current }
+ // A hosted Viewer/Commenter publishes nothing: the host refuses canvas:mut for them (R5).
+ { src, shouldPublish: () => hasPeersRef.current && !isHostedReadOnly(activeSession.id) }
)
publisherRef.current = pub
return () => {
@@ -4136,15 +4175,20 @@ export function Canvas() {
// `reconnectProjectId` (Stage 4 Task 7): when reconnecting an offline tab, bind the fresh session
// to the EXISTING project id (reuse the tab, clear its "unavailable" grey) instead of adding a new
// one — so a socket drop → greyed reconnectable tab, never a duplicate.
+ // `hosted` (a hosted team's join code): build the tab with its hosted api, wait up to the host's
+ // own ten-minute pending window for an owner, switch to it only when asked, and hand a failure
+ // back to the caller (the hosted joiner decides whether to retry or say so) instead of alerting.
+ // Absent = a pairing offer, exactly as before. Resolves with the outcome only for `hosted`.
const mountRemoteMirror = useCallback(
(
connectionId: string,
label = 'Remote host',
reconnectProjectId?: string,
- staleSessionId?: string
- ) => {
- if (relayTabsRef.current.has(connectionId)) return
- void openRelayTab(connectionId, label, {
+ staleSessionId?: string,
+ hosted?: { activate: boolean }
+ ): Promise<HostedMountOutcome | null> => {
+ if (relayTabsRef.current.has(connectionId)) return Promise.resolve(null)
+ return openRelayTab(connectionId, label, {
relayClient: window.nodeTerminal.relayClient,
addProject: reconnectProjectId
? () => ({ id: reconnectProjectId }) // reconnect: reuse the existing tab, don't spawn one
@@ -4155,18 +4199,27 @@ export function Canvas() {
? undefined
: (p) => useProjects.getState().adoptProject(p),
setActiveProject: (id) => useProjects.getState().setActive(id),
+ ...(hosted ? { hosted: true, timeoutMs: HOSTED_APPROVAL_WAIT_MS, activate: hosted.activate } : {}),
})
- .then((tab) => {
+ .then((tab): HostedMountOutcome | null => {
relayTabsRef.current.set(connectionId, tab)
if (reconnectProjectId) {
// The fresh session is now bound to the tab (openRelayTab rebound the SAME project id),
// so it is finally safe to drop the stale offline session it replaced. Disposing only
// AFTER a successful rebind is what keeps a FAILED reconnect reconnectable: if approval
// never lands, the offline session stays bound and the tab stays greyed-clickable.
- if (staleSessionId) disposeSession(staleSessionId)
+ if (staleSessionId) {
+ disposeSession(staleSessionId)
+ if (hosted) useHostedTeams.getState().forget(staleSessionId)
+ }
// Back online: un-grey the reused tab.
useProjects.getState().setProjectUnavailable(reconnectProjectId, false)
}
+ // A background (unrequested) reconnect did not switch tabs — but if its tab is the one on
+ // screen, the active session must follow the rebind (disposing the stale one reset it).
+ if (hosted && !hosted.activate && useProjects.getState().activeProjectId === tab.projectId) {
+ setActiveSession(tab.sessionId)
+ }
// A host/relay drop AFTER approval is INVOLUNTARY (not a user close): grey the tab to
// "unavailable" and take its session offline (presence teardown runs once) — but KEEP the
// project so a click can reconnect it in place. See relay-tab `handleRelayDrop`.
@@ -4177,11 +4230,15 @@ export function Canvas() {
setProjectUnavailable: (id, v) => useProjects.getState().setProjectUnavailable(id, v),
})
})
+ return hosted ? { projectId: tab.projectId } : null
})
- .catch((err) => {
+ .catch((err): HostedMountOutcome | null => {
// A user who declined the SAS triggered this close themselves — don't cry error.
- if (cancelledConnsRef.current.delete(connectionId)) return
+ const declined = cancelledConnsRef.current.delete(connectionId)
+ if (hosted) return { error: err, declined }
+ if (declined) return null
window.alert(`Remote session did not open: ${(err as Error).message}`)
+ return null
})
},
[]
@@ -4193,28 +4250,90 @@ export function Canvas() {
// relay-api.ts gotcha 2). Shared by the first connect and the Task 7 reconnect (which passes the
// existing project id so the fresh session rebinds the SAME tab).
const confirmAndMount = useCallback(
- (connectionId: string, label: string, reconnectProjectId?: string, staleSessionId?: string) => {
+ (
+ connectionId: string,
+ label: string,
+ reconnectProjectId?: string,
+ staleSessionId?: string,
+ hosted?: { activate: boolean }
+ ): Promise<HostedMountOutcome | null> => {
const unSas = window.nodeTerminal.relayClient.onSas(connectionId, (sas) => {
unSas()
- if (sas && window.confirm(`Verify this code matches the one shown on the host:\n\n${sas}`)) {
+ // A hosted team's owner is not at a host screen: they read the same code in their approval
+ // dialog, so the joiner reads it to them (a call, a chat).
+ const question = hosted
+ ? `Read this code to an owner of ${label || 'the team'} (call or chat) — they see the same code before approving this device:\n\n${sas}`
+ : `Verify this code matches the one shown on the host:\n\n${sas}`
+ if (sas && window.confirm(question)) {
window.nodeTerminal.relayClient.confirm(connectionId)
+ // A first join waits for an owner — up to ten minutes. Say so rather than hang silently.
+ if (hosted) setNotice({ kind: 'info', text: waitingForOwnerText(label), sticky: true })
} else {
// Deliberate decline: mark it so the bootstrap's close-reject isn't surfaced as an error.
cancelledConnsRef.current.add(connectionId)
window.nodeTerminal.relayClient.disconnect(connectionId)
}
})
- mountRemoteMirror(connectionId, label, reconnectProjectId, staleSessionId)
+ return mountRemoteMirror(connectionId, label, reconnectProjectId, staleSessionId, hosted)
},
[mountRemoteMirror]
)
+ // Hosted teams (a Server Edition hosting over the relay, joined by a `nodeterm://join` code): the
+ // ONE owner of every (re)join — boot, a dropped tab, a click on a greyed tab, a pasted code — so a
+ // team never has two attempts or two connections at once (lib/hostedJoin.ts). Created once; it
+ // reconnects every approved bookmark at boot. The Server Edition's `relayHosted` answers no
+ // bookmarks, so there it does nothing.
+ const hostedJoinerRef = useRef<HostedJoiner | null>(null)
+ useEffect(() => {
+ const joiner = createHostedJoiner({
+ connect: (code) => window.nodeTerminal.relayClient.connect(code),
+ onClosed: (id, listener) => window.nodeTerminal.relayClient.onClosed(id, listener),
+ disconnect: (id) => window.nodeTerminal.relayClient.disconnect(id),
+ bookmarks: async () => (await window.nodeTerminal.relayHosted?.bookmarks()) ?? [],
+ removeBookmark: (hostId) => window.nodeTerminal.relayHosted.removeBookmark(hostId),
+ mount: (connectionId, req) => {
+ const bound = req.reconnectProjectId ? sessionForProject(req.reconnectProjectId) : null
+ return confirmAndMount(
+ connectionId,
+ req.label || 'Hosted team',
+ req.reconnectProjectId,
+ bound?.source === 'relay' ? bound.id : undefined,
+ // Only a reconnect the user asked for takes the screen (or one with nothing on it).
+ { activate: req.manual || !useProjects.getState().activeProjectId }
+ )
+ .then((o): HostedMountOutcome => o ?? { error: new Error('That connection is already open.'), declined: true })
+ .finally(() => setNotice((n) => (n?.text === waitingForOwnerText(req.label || 'Hosted team') ? null : n)))
+ },
+ tabOpen: (projectId) => {
+ const p = useProjects.getState().getProject(projectId)
+ return !!p && !p.closed
+ },
+ notify: (n) => setNotice(n),
+ promptForCode: (label) => promptDialog({ message: `Paste a fresh invite code for ${label || 'the team'}:` }),
+ setTimer: (fn, ms) => setTimeout(fn, ms),
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>)
+ })
+ hostedJoinerRef.current = joiner
+ void joiner.bootReconnect()
+ return () => {
+ hostedJoinerRef.current = null
+ joiner.dispose()
+ }
+ }, [confirmAndMount])
+
// Connect to a host from an already-collected pairing offer: open the relay socket, then run the
// shared SAS-compare + mount flow. The SINGLE place `relayClient.connect` + `confirmAndMount` live,
// so every entry (dock/palette prompt below, and the Settings/tab-menu dialogs via the
// `nodeterm:open-remote-terminal` event) reuses it instead of re-implementing the SAS handshake.
const connectOffer = useCallback(
async (offer: string) => {
+ // A hosted team's join code goes through its team's one attempt owner (never a second
+ // connect for the same team). A pairing offer takes the path below, unchanged.
+ if (isJoinCode(offer) && hostedJoinerRef.current) {
+ hostedJoinerRef.current.joinWithCode(offer)
+ return
+ }
try {
const connectionId = await window.nodeTerminal.relayClient.connect(offer)
confirmAndMount(connectionId, 'Remote host')
@@ -4240,11 +4359,21 @@ export function Canvas() {
// path), so a cancelled/failed reconnect leaves the offline tab still bound and reconnectable.
const reconnectRelay = useCallback(
(projectId: string) => {
+ // A hosted team's tab reconnects from its bookmark: no code to paste.
+ if (hostedJoinerRef.current?.reconnectTab(projectId)) return
const label = useProjects.getState().getProject(projectId)?.name ?? 'Remote host'
const bound = sessionForProject(projectId)
const staleSessionId = bound.source === 'relay' ? bound.id : undefined
void reconnectRelayTab(projectId, {
- promptForOffer: () => promptDialog({ message: "Paste the host's new pairing code:" }),
+ promptForOffer: async () => {
+ const offer = await promptDialog({ message: "Paste the host's new pairing code:" })
+ // A join code pasted here reconnects THIS tab through its team's attempt owner.
+ if (offer && isJoinCode(offer) && hostedJoinerRef.current) {
+ hostedJoinerRef.current.joinWithCode(offer, projectId)
+ return null
+ }
+ return offer
+ },
connect: (offer) => window.nodeTerminal.relayClient.connect(offer),
mount: (connectionId, projId) => confirmAndMount(connectionId, label, projId, staleSessionId),
onError: (message) => window.alert(`Could not reconnect: ${message}`),
@@ -14349,6 +14478,68 @@ export function Canvas() {
[transcriptHits, openTranscriptHit, now]
)
+ // Hosted team palette entries: the owner's invite code, and one "forget" row per joined team. The
+ // bookmarks are read each time the palette opens — a join, a forget or a revocation may have
+ // changed them since. The Server Edition answers none (a browser tab never joins a relay host).
+ const [hostedBookmarks, setHostedBookmarks] = useState<Array<{ hostId: string; label: string }>>([])
+ useEffect(() => {
+ if (!paletteOpen) return
+ let live = true
+ Promise.resolve(window.nodeTerminal.relayHosted?.bookmarks())
+ .then((list) => {
+ if (live) setHostedBookmarks(Array.isArray(list) ? list : [])
+ })
+ .catch(() => {})
+ return () => {
+ live = false
+ }
+ }, [paletteOpen])
+
+ const copyHostedInviteCode = useCallback((hosted: HostedSessionApi) => {
+ hosted.inviteCode().then(
+ (code) => {
+ if (!code) {
+ setNotice({ kind: 'error', text: 'This team has no invite code to hand out right now.' })
+ return
+ }
+ window.nodeTerminal.clipboard.writeText(code)
+ setNotice({
+ kind: 'info',
+ text: 'Team invite code copied. Anyone with it can ask to join; an owner still approves each device.'
+ })
+ },
+ (err: unknown) =>
+ setNotice({
+ kind: 'error',
+ text: `Could not read the invite code: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}`
+ })
+ )
+ }, [])
+
+ // Forgetting a team drops this device's bookmark (its saved join details) and stops its boot
+ // reconnect. It changes nothing on the team's host. Refused while that team is connecting: main
+ // would refuse it too (its join's own save would bring the bookmark back).
+ const forgetHostedTeam = useCallback((b: { hostId: string; label: string }) => {
+ const joiner = hostedJoinerRef.current
+ if (!joiner) return
+ const team = b.label || 'this team'
+ if (joiner.connecting(b.hostId)) {
+ setNotice({ kind: 'info', text: `Still connecting to ${team}; forget it once that finishes.` })
+ return
+ }
+ setConfirm({
+ message:
+ `Forget ${team}? This device stops reconnecting to it and forgets its saved join details. ` +
+ `Nothing changes on the team's host; to rejoin, paste its invite code again.`,
+ confirmLabel: 'Forget',
+ danger: true,
+ onConfirm: () => {
+ setConfirm(null)
+ void joiner.forget(b.hostId, b.label)
+ }
+ })
+ }, [setConfirm])
+
const buildCommands = useCallback((): Command[] => {
const disabled = useSettings.getState().settings.disabledAgents
const activeProject = useProjects.getState().getProject(activeProjectId)
@@ -14457,6 +14648,31 @@ export function Canvas() {
icon: <IconRemote />,
run: () => void connectRemote()
},
+ // Hosted team rows. Both are absent unless they apply, so every other palette is unchanged.
+ ...((): Command[] => {
+ const session = sessionForProject(useProjects.getState().activeProjectId ?? '')
+ const hosted = session.api.hosted
+ return hosted && hostedInfoFor(session.id)?.role === 'owner'
+ ? [
+ {
+ id: 'hosted-invite-code',
+ label: 'Copy team invite code',
+ hint: 'hosted team invite join share',
+ icon: <IconRemote />,
+ run: () => copyHostedInviteCode(hosted)
+ }
+ ]
+ : []
+ })(),
+ ...hostedBookmarks.map(
+ (b): Command => ({
+ id: `hosted-forget-${b.hostId}`,
+ label: `Forget hosted team: ${b.label || 'unnamed team'}`,
+ hint: 'hosted team bookmark leave remove',
+ icon: <IconRemote />,
+ run: () => forgetHostedTeam(b)
+ })
+ ),
{
id: 'focus-node',
label: 'Focus node',
@@ -14612,7 +14828,10 @@ export function Canvas() {
hasArrangeableNodes,
saveCanvasLayout,
restoreCanvasLayout,
- toggleFocusMode
+ toggleFocusMode,
+ hostedBookmarks,
+ copyHostedInviteCode,
+ forgetHostedTeam
])
// Build the palette's command list only when its inputs change — the inline `buildCommands()`
@@ -14663,6 +14882,14 @@ export function Canvas() {
setSettingsOpen(true)
}}
/>
+ {activeHosted && hostedReadOnly && (
+ <div className="announce-banner announce-banner--info" role="status">
+ <span className="announce-banner__dot" />
+ <div className="announce-banner__content">
+ <span className="announce-banner__body">{viewerBannerText(activeHosted.role, activeHosted.teamLabel)}</span>
+ </div>
+ </div>
+ )}
{migrationNote && (
<div className="announce-banner announce-banner--info">
<span className="announce-banner__dot" />
@@ -15041,6 +15268,9 @@ export function Canvas() {
panActivationKeyCode={null}
snapToGrid={settings.snapToGrid}
snapGrid={[settings.gridSize, settings.gridSize]}
+ // A hosted team's Viewer/Commenter cannot move or wire nodes (the host would refuse the
+ // edit anyway). Spread, so every other tab passes nothing new to React Flow.
+ {...(hostedReadOnly ? HOSTED_READ_ONLY_FLOW : {})}
>
{showCanvasDots(settings.canvasDots) && (
<Background
@@ -15463,6 +15693,20 @@ export function Canvas() {
/>
)}
+ {hostedHead && (
+ // A remote device asked to join a hosted team this device owns. Enter never approves it
+ // and Deny holds the focus (components/HostedApprovalDialog). Keyed by request, so the next
+ // one in the queue opens fresh (role back to Viewer, the arm delay again).
+ <HostedApprovalDialog
+ key={hostedHead.pending.pendingId}
+ pending={hostedHead.pending}
+ teamLabel={hostedHead.teamLabel}
+ more={hostedMore}
+ onApprove={(_id, role) => answerHosted(hostedHead, { kind: 'approve', role })}
+ onDeny={() => answerHosted(hostedHead, { kind: 'deny' })}
+ />
+ )}
+
{pendingPeer && (
<ConfirmDialog
// ConsentNotice → describeGrant: the human reads WHAT they grant ("<peer> will be able to
diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.ts
new file mode 100644
index 000000000..70d8d14d2
--- /dev/null
+++ b/src/renderer/canvas/hosted-team.source.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the hosted-team glue in Canvas.tsx — the same class of test as
+ * `control-cold-open.source.test.ts`, for the same reason: the glue lives inside a 15,000-line
+ * component with no render harness. Every BEHAVIOUR is proven against the real modules elsewhere:
+ * the attempt owner (`lib/hostedAttempts.test.ts`), the joiner's boot / drop / click / paste /
+ * forget paths (`lib/hostedJoin.test.ts`), the approval queue and the owner subscription
+ * (`lib/hostedPendingQueue.test.ts`, `lib/hostedOwner.test.ts`, `session/relay-tab.test.ts`), the
+ * role gate and the legacy relay api (`bridge/relay-api.test.ts`), the dialog
+ * (`components/HostedApprovalDialog.test.tsx`).
+ *
+ * What only a source read can pin is that Canvas CALLS them, and — the rule this feature rests on —
+ * that a Team Access relay tab and a local tab still take their old path: every hosted branch sits
+ * behind a join code, a hosted api or a hosted role. See docs/hosted-team-relay.md.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+function between(start: string, end: string): string {
+ const a = src.indexOf(start)
+ expect(a, start).toBeGreaterThan(-1)
+ const b = src.indexOf(end, a + start.length)
+ expect(b, end).toBeGreaterThan(a)
+ return src.slice(a, b)
+}
+
+describe('hosted team glue in Canvas', () => {
+ it('a pairing offer keeps its old connect path; only a join code is handed to the hosted joiner', () => {
+ const body = between('const connectOffer = useCallback(', '[confirmAndMount]')
+ const divert = body.indexOf('if (isJoinCode(offer) && hostedJoinerRef.current) {')
+ const legacy = body.indexOf("await window.nodeTerminal.relayClient.connect(offer)")
+ expect(divert).toBeGreaterThan(-1)
+ expect(legacy).toBeGreaterThan(divert)
+ expect(body).toContain("confirmAndMount(connectionId, 'Remote host')") // no hosted options
+ })
+
+ it('a greyed tab asks the joiner first, and a non-hosted tab falls through to the pairing prompt', () => {
+ const body = between('const reconnectRelay = useCallback(', 'onError: (message)')
+ expect(body.indexOf('if (hostedJoinerRef.current?.reconnectTab(projectId)) return')).toBeLessThan(
+ body.indexOf('void reconnectRelayTab(projectId, {')
+ )
+ expect(body).toContain(`promptDialog({ message: "Paste the host's new pairing code:" })`)
+ })
+
+ it('the relay tab is built with hosted options, a long approval wait and no alert ONLY when hosted', () => {
+ const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')
+ expect(body).toContain('...(hosted ? { hosted: true, timeoutMs: HOSTED_APPROVAL_WAIT_MS, activate: hosted.activate } : {})')
+ expect(body).toContain('if (hosted) return { error: err, declined }')
+ expect(body).toContain("window.alert(`Remote session did not open: ${(err as Error).message}`)")
+ })
+
+ it('the joiner is created once and reconnects the approved bookmarks at boot', () => {
+ const body = between('const hostedJoinerRef = useRef<HostedJoiner | null>(null)', '}, [confirmAndMount])')
+ expect(body).toContain('createHostedJoiner({')
+ expect(body).toContain('void joiner.bootReconnect()')
+ expect(body).toContain('joiner.dispose()')
+ })
+
+ it('a read-only role never publishes canvas edits, and the rule is false for every non-hosted tab', () => {
+ expect(src).toContain('shouldPublish: () => hasPeersRef.current && !isHostedReadOnly(activeSession.id)')
+ })
+
+ it('the canvas turns read-only only for a hosted Viewer/Commenter (a spread: nothing new otherwise)', () => {
+ expect(src).toContain('{...(hostedReadOnly ? HOSTED_READ_ONLY_FLOW : {})}')
+ expect(src).toContain('const hostedReadOnly = isReadOnlyRole(activeHosted?.role)')
+ expect(src).toContain('{activeHosted && hostedReadOnly && (')
+ })
+
+ it('the owner dialog shows the queue head, one request at a time', () => {
+ const body = between('{hostedHead && (', '{pendingPeer && (')
+ expect(body).toContain('<HostedApprovalDialog')
+ expect(body).toContain('key={hostedHead.pending.pendingId}')
+ })
+})
diff --git a/src/renderer/components/HostedApprovalDialog.test.tsx b/src/renderer/components/HostedApprovalDialog.test.tsx
new file mode 100644
index 000000000..9d9ebb332
--- /dev/null
+++ b/src/renderer/components/HostedApprovalDialog.test.tsx
@@ -0,0 +1,144 @@
+// @vitest-environment jsdom
+//
+// The owner's answer to a device asking to join a hosted team. A REMOTE device raises this dialog
+// under the owner's hands, so what is asserted is safety-shaped: the least role is the default, the
+// SAS and key fingerprint are on screen, Enter never approves, a held key never answers a queue of
+// requests, and only a click on Allow grants anything. (No @testing-library in this repo: plain
+// react-dom + act, like the other component tests.)
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { HostedApprovalDialog } from './HostedApprovalDialog'
+import { CONFIRM_ARM_MS } from './confirm-key'
+import { openDialogCount, pushDialog, popDialog, resetDialogStack } from './dialog-stack'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+let root: Root
+let host: HTMLDivElement
+beforeEach(() => {
+ resetDialogStack()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ vi.useRealTimers()
+})
+
+const pending = (over: Partial<{ pendingId: string; sas: string; peerKeyB64: string; since: number }> = {}) => ({
+ pendingId: 'p',
+ sas: '123 456',
+ peerKeyB64: 'AAAABBBBCCCC',
+ since: 0,
+ ...over
+})
+
+function mount(props: Partial<Parameters<typeof HostedApprovalDialog>[0]> = {}) {
+ const onApprove = vi.fn()
+ const onDeny = vi.fn()
+ act(() => {
+ root.render(<HostedApprovalDialog pending={pending()} teamLabel="box" onApprove={onApprove} onDeny={onDeny} {...props} />)
+ })
+ return { onApprove, onDeny }
+}
+
+const text = () => document.body.textContent ?? ''
+const byText = (t: string) => [...document.querySelectorAll('button, strong, p, span, div')].find((e) => e.textContent === t) as HTMLElement | undefined
+const roleSelect = () => document.querySelector('select[aria-label="Role"]') as HTMLSelectElement
+const button = (label: string) => [...document.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLButtonElement
+const key = (target: EventTarget, init: KeyboardEventInit) => {
+ const e = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+ act(() => { target.dispatchEvent(e) })
+ return e
+}
+
+describe('HostedApprovalDialog', () => {
+ it('defaults to Viewer, shows SAS + fingerprint, and approves with the chosen role', () => {
+ const { onApprove } = mount()
+ expect(byText('123 456')).toBeTruthy()
+ expect(text()).toMatch(/AAAA·BBBB/)
+ expect(roleSelect().value).toBe('viewer')
+ act(() => {
+ roleSelect().value = 'editor'
+ roleSelect().dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ expect(text()).toMatch(/run commands on box/i)
+ act(() => button('Allow').click())
+ expect(onApprove).toHaveBeenCalledWith('p', 'editor')
+ })
+
+ it('says what each role grants; the least role never mentions running commands', () => {
+ mount()
+ expect(text()).toMatch(/Can watch the shared project and its terminals/)
+ expect(text()).not.toMatch(/run commands/i)
+ for (const [role, re] of [['commenter', /comment on cards/], ['owner', /approving, removing and changing roles.*run commands on box/]] as const) {
+ act(() => {
+ roleSelect().value = role
+ roleSelect().dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ expect(text()).toMatch(re)
+ }
+ })
+
+ it('Enter does not approve (a remote device raised this dialog)', () => {
+ vi.useFakeTimers()
+ const { onApprove, onDeny } = mount()
+ vi.advanceTimersByTime(CONFIRM_ARM_MS + 10)
+ key(document.body, { key: 'Enter' })
+ // …not even aimed inside the dialog, on the Allow button itself, or on the role picker.
+ const allow = button('Allow')
+ allow.focus()
+ const onAllow = key(allow, { key: 'Enter' })
+ expect(onAllow.defaultPrevented).toBe(true) // the browser's own button activation is blocked too
+ key(roleSelect(), { key: 'Enter' })
+ expect(onApprove).not.toHaveBeenCalled()
+ expect(onDeny).not.toHaveBeenCalled()
+ })
+
+ it('Deny is the focused button and answers with this request\'s id; Allow never takes focus', () => {
+ const { onDeny, onApprove } = mount({ pending: pending({ pendingId: 'req-7' }) })
+ expect(document.activeElement).toBe(button('Deny'))
+ act(() => button('Deny').click())
+ expect(onDeny).toHaveBeenCalledWith('req-7')
+ expect(onApprove).not.toHaveBeenCalled()
+ })
+
+ it('Escape declines — but never a held key or one already in flight when the dialog appeared', () => {
+ vi.useFakeTimers()
+ const { onDeny } = mount()
+ key(document.body, { key: 'Escape' }) // arrived before the dialog was armed
+ vi.advanceTimersByTime(CONFIRM_ARM_MS + 10)
+ key(document.body, { key: 'Escape', repeat: true }) // a held key must not deny a whole queue
+ expect(onDeny).not.toHaveBeenCalled()
+ key(document.body, { key: 'Escape' })
+ expect(onDeny).toHaveBeenCalledWith('p')
+ })
+
+ it('registers on the dialog stack, and a dialog above it owns the keys', () => {
+ vi.useFakeTimers()
+ const { onDeny } = mount()
+ expect(openDialogCount()).toBe(1)
+ vi.advanceTimersByTime(CONFIRM_ARM_MS + 10)
+ pushDialog('above')
+ key(document.body, { key: 'Escape' })
+ expect(onDeny).not.toHaveBeenCalled()
+ popDialog('above')
+ act(() => root.render(<></>))
+ expect(openDialogCount()).toBe(0)
+ })
+
+ it('says how many more requests are waiting behind this one', () => {
+ mount({ more: 2 })
+ expect(text()).toMatch(/2 more requests are waiting/)
+ })
+
+ it('renders what the host sent as text, never markup', () => {
+ mount({ teamLabel: '<img src=x onerror=alert(1)>', pending: pending({ sas: '<b>1</b>' }) })
+ expect(document.querySelector('img')).toBeNull()
+ expect(document.querySelector('b')).toBeNull()
+ expect(text()).toContain('<img src=x onerror=alert(1)>')
+ })
+})
diff --git a/src/renderer/components/HostedApprovalDialog.tsx b/src/renderer/components/HostedApprovalDialog.tsx
new file mode 100644
index 000000000..47585ff88
--- /dev/null
+++ b/src/renderer/components/HostedApprovalDialog.tsx
@@ -0,0 +1,100 @@
+// A device's first join of a hosted team: an OWNER compares the SAS with the person joining (out of
+// band — a call, a chat) and picks the role it gets. Default Viewer, the least privilege.
+//
+// A REMOTE device raised this under the owner's hands, so it follows the Team Access dialog's rules
+// and adds two of its own (components/confirm-key):
+// - Enter NEVER approves — not from the window, not aimed at the dialog, not the browser's own
+// activation of a focused button. Only a click on Allow grants anything.
+// - Escape declines, like every dialog here, but only once the dialog is armed and never on a
+// held key: requests queue (up to 16), and one key held down must not deny a line of teammates.
+// - The focus lands on Deny, the safe answer, never on Allow.
+// Built on ConfirmDialog's classes and the dialog stack, so z-order and Escape ownership match every
+// other dialog. See docs/hosted-team-relay.md.
+import { useEffect, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
+import type { HostedPending, HostedRole } from '@shared/types'
+import { keyFingerprint } from '../lib/hostedTeam'
+import { CONFIRM_ARM_MS } from './confirm-key'
+import { useDialogStack } from './dialog-stack'
+
+const ROLE_COPY: Record<HostedRole, string> = {
+ viewer: 'Can watch the shared project and its terminals, including anything printed in them.',
+ commenter: 'Can watch, and comment on cards and in cursor chat.',
+ editor: 'Can type into terminals, edit files and run git — the same as SSH access',
+ owner: 'Editor access, plus approving, removing and changing roles'
+}
+
+export function HostedApprovalDialog(props: {
+ pending: HostedPending
+ teamLabel: string
+ /** Requests waiting behind this one. */
+ more?: number
+ onApprove(pendingId: string, role: HostedRole): void
+ onDeny(pendingId: string): void
+}): React.JSX.Element {
+ const { pending, teamLabel, more = 0, onApprove, onDeny } = props
+ const [role, setRole] = useState<HostedRole>('viewer')
+ const isTop = useDialogStack()
+ // Set on the first render, not in an effect: a key already on its way when the dialog appeared is
+ // measured against the moment it appeared.
+ const mountedAtRef = useRef(Date.now())
+ const denyRef = useRef(onDeny)
+ denyRef.current = onDeny
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key !== 'Escape' || !isTop()) return
+ e.preventDefault()
+ if (e.repeat || Date.now() - mountedAtRef.current < CONFIRM_ARM_MS) return
+ denyRef.current(pending.pendingId)
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [isTop, pending.pendingId])
+
+ const team = teamLabel.trim() || 'this team'
+ const grant =
+ role === 'editor' || role === 'owner' ? `${ROLE_COPY[role]} — they can run commands on ${team}.` : ROLE_COPY[role]
+
+ return createPortal(
+ <div className="confirm-overlay" role="dialog" aria-modal="true" aria-label="A device wants to join the team">
+ <div
+ className="confirm"
+ // Enter answers nothing here. Blocking it in the capture phase also stops the browser from
+ // turning Enter on a focused button into a click.
+ onKeyDownCapture={(e) => {
+ if (e.key === 'Enter') e.preventDefault()
+ }}
+ >
+ <div className="confirm__msg">
+ <strong>A device wants to join {team}</strong>
+ {'\n\n'}Compare this code with the person joining (call or chat) before allowing:{'\n\n'}
+ <strong>{pending.sas}</strong>
+ {'\n\n'}Device key {keyFingerprint(pending.peerKeyB64)}
+ {more > 0 ? `\n\n${more} more ${more === 1 ? 'request is' : 'requests are'} waiting.` : ''}
+ </div>
+ <label className="confirm__option">
+ Role{' '}
+ <select aria-label="Role" value={role} onChange={(e) => setRole(e.target.value as HostedRole)}>
+ <option value="viewer">Viewer</option>
+ <option value="commenter">Commenter</option>
+ <option value="editor">Editor</option>
+ <option value="owner">Owner</option>
+ </select>
+ </label>
+ <p className="remote-consent" role="note">
+ {grant}
+ </p>
+ <div className="confirm__actions">
+ <button className="confirm__btn" autoFocus onClick={() => onDeny(pending.pendingId)}>
+ Deny
+ </button>
+ <button className="confirm__btn danger" onClick={() => onApprove(pending.pendingId, role)}>
+ Allow
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 9bd0e93de..a17102fa5 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -19,6 +19,7 @@ import { FindBar } from '../FindBar'
import { useAgentStatus } from '../../state/agentStatus'
import { useProjects } from '../../state/projects'
import { useSession } from '../../session/session'
+import { isHostedReadOnly } from '../../state/hostedTeams'
import { useSettings } from '../../state/settings'
import { useTerminalSearch } from '../../terminal/useTerminalSearch'
import { useTerminalGlass } from '../../lib/useTerminalGlass'
@@ -101,7 +102,8 @@ interface ModalTerminalProps {
}
export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covered = false }: ModalTerminalProps) {
- const { api } = useSession()
+ const session = useSession()
+ const { api } = session
const hostRef = useRef<HTMLDivElement>(null)
const middleClickPaste = useSettings((st) => st.settings.terminalMiddleClickPaste)
// Chromium pastes the X PRIMARY selection into xterm's hidden textarea on middle click — a path
@@ -204,6 +206,8 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
// view of one session, and a card that renders it in different colours reads as a different
// terminal. (It used to hardcode its own background, which is exactly what happened.)
const term = new Terminal(xtermOptionsFromSettings(s, glassRef.current))
+ // The same read-only rule as the canvas node: a hosted team's Viewer/Commenter never types here.
+ if (isHostedReadOnly(session.id)) term.options.disableStdin = true
// Without a handler xterm answers an OSC 8 click with a window.confirm — the one surface
// where this session's links would prompt instead of opening like the canvas node's.
term.options.linkHandler = createOsc8LinkHandler((uri) =>
diff --git a/src/renderer/lib/hostedAttempts.test.ts b/src/renderer/lib/hostedAttempts.test.ts
new file mode 100644
index 000000000..204f1c524
--- /dev/null
+++ b/src/renderer/lib/hostedAttempts.test.ts
@@ -0,0 +1,307 @@
+import { describe, it, expect, vi } from 'vitest'
+import type { RelayClosedReason } from '@shared/types'
+import { createHostedAttempts, type HostedAttemptDeps, type HostedAttemptRequest } from './hostedAttempts'
+import type { JoinFailure } from './hostedTeam'
+
+const wrap = (m: string) => new Error(`Error invoking remote method 'relay:client:connect': Error: ${m}`)
+const flush = () => new Promise((r) => setTimeout(r, 0))
+
+/** Deps whose every answer the test controls, with a manual clock. */
+function harness() {
+ const connects: Array<{ code: string; resolve: (id: string) => void; reject: (e: Error) => void }> = []
+ const mounts: Array<{ id: string; req: HostedAttemptRequest; resolve: (r: { projectId: string } | { retry: boolean }) => void }> = []
+ const closeCbs = new Map<string, (reason?: RelayClosedReason) => void>()
+ const unsubs: string[] = []
+ const timers: Array<{ fn: () => void; ms: number; cleared: boolean }> = []
+ const stopped: Array<{ req: HostedAttemptRequest; f: JoinFailure }> = []
+ const ended: Array<{ req: HostedAttemptRequest; projectId: string; reason?: RelayClosedReason }> = []
+ const disconnected: string[] = []
+ const deps: HostedAttemptDeps = {
+ connect: (code) => new Promise((resolve, reject) => connects.push({ code, resolve, reject })),
+ mount: (id, req) => new Promise((resolve) => mounts.push({ id, req, resolve })),
+ onClosed: (id, cb) => {
+ closeCbs.set(id, cb)
+ return () => unsubs.push(id)
+ },
+ disconnect: (id) => disconnected.push(id),
+ stopped: (req, f) => stopped.push({ req, f }),
+ ended: (req, projectId, reason) => ended.push({ req, projectId, reason }),
+ setTimer: (fn, ms) => {
+ const t = { fn, ms, cleared: false }
+ timers.push(t)
+ return t
+ },
+ clearTimer: (t) => {
+ ;(t as { cleared: boolean }).cleared = true
+ }
+ }
+ const fire = () => {
+ const t = timers.filter((x) => !x.cleared).pop()
+ if (!t) throw new Error('no armed timer')
+ t.cleared = true
+ t.fn()
+ }
+ const armed = () => timers.filter((t) => !t.cleared)
+ return { deps, connects, mounts, closeCbs, unsubs, timers, armed, fire, stopped, ended, disconnected }
+}
+
+const boot = (over: Partial<HostedAttemptRequest> = {}): HostedAttemptRequest => ({
+ hostId: 'H1', code: 'nodeterm://join?code=AAA', label: 'box', manual: false, retry: true, ...over
+})
+
+describe('hosted attempts: one attempt and one live connection per team (R38/R39)', () => {
+ it('connects, mounts, and holds the team as live', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ expect(a.run(boot())).toBe('started')
+ expect(a.phase('H1')).toBe('connecting')
+ h.connects[0].resolve('c1')
+ await flush()
+ expect(a.phase('H1')).toBe('mounting')
+ expect(h.mounts[0].id).toBe('c1')
+ h.mounts[0].resolve({ projectId: 'proj-1' })
+ await flush()
+ expect(a.phase('H1')).toBe('live')
+ })
+
+ it('a second run for the same team while it connects, waits for approval or is live is refused — never a second connect', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ expect(a.run(boot({ manual: true }))).toBe('busy') // connecting
+ h.connects[0].resolve('c1')
+ await flush()
+ expect(a.run(boot({ manual: true }))).toBe('busy') // SAS / owner approval window (item 15)
+ h.mounts[0].resolve({ projectId: 'proj-1' })
+ await flush()
+ expect(a.run(boot({ manual: true }))).toBe('busy') // live
+ expect(h.connects).toHaveLength(1)
+ // Another team is independent.
+ expect(a.run(boot({ hostId: 'H2' }))).toBe('started')
+ expect(h.connects).toHaveLength(2)
+ })
+
+ it('retries ONLY a network failure, on the 1/2/4/8/15/60 s ladder (R35)', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ const delays: number[] = []
+ for (let i = 0; i < 7; i++) {
+ h.connects[i].reject(wrap('[E_JOIN_NETWORK] Could not reach the nodeterm service.'))
+ await flush()
+ expect(a.phase('H1')).toBe('waiting')
+ delays.push(h.armed()[0].ms)
+ h.fire()
+ expect(a.phase('H1')).toBe('connecting')
+ }
+ expect(delays).toEqual([1000, 2000, 4000, 8000, 15000, 60000, 60000])
+ expect(h.stopped).toEqual([])
+ })
+
+ for (const code of ['E_JOIN_REVOKED', 'E_JOIN_REFUSED', 'E_JOIN_RATE', 'E_JOIN_BAD_CODE', 'E_JOIN_KEY_LOCKED']) {
+ it(`${code} stops the loop at once and is told once — a retry would spend damped mints`, async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(wrap(`[${code}] detail`))
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ expect(h.armed()).toEqual([])
+ expect(h.stopped).toHaveLength(1)
+ expect(h.stopped[0].f).toMatchObject({ code, retry: false, detail: 'detail' })
+ })
+ }
+
+ it('a failure with no code at all is never retried either', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(new Error('Remote access is unavailable in development builds.'))
+ await flush()
+ expect(h.armed()).toEqual([])
+ expect(h.stopped[0].f.code).toBeNull()
+ })
+
+ it('an attempt that asked not to retry (a pasted code) reports a network failure instead of looping', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot({ manual: true, retry: false }))
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ expect(h.armed()).toEqual([])
+ expect(h.stopped[0].f.code).toBe('E_JOIN_NETWORK')
+ })
+
+ it('BUSY stops without being a verdict: reported as busy, never as a denial', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(wrap('[E_JOIN_BUSY] Already joining this team.'))
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ expect(h.stopped[0].f).toMatchObject({ busy: true, retry: false })
+ })
+
+ it('a manual connect cancels the pending backoff and runs the one attempt now (item 15)', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ expect(a.phase('H1')).toBe('waiting')
+ // An automatic run while waiting leaves the existing loop alone.
+ expect(a.run(boot())).toBe('busy')
+ expect(a.run(boot({ manual: true, reconnectProjectId: 'proj-1' }))).toBe('started')
+ expect(h.armed()).toEqual([])
+ expect(h.connects).toHaveLength(2)
+ // The manual request is the one that runs (it carries the tab to reconnect in place).
+ h.connects[1].resolve('c2')
+ await flush()
+ expect(h.mounts[0].req.reconnectProjectId).toBe('proj-1')
+ })
+
+ it('cancel stops a waiting loop for good (the team was forgotten, the canvas went away)', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ a.cancel('H1')
+ expect(h.armed()).toEqual([])
+ expect(a.phase('H1')).toBeNull()
+ })
+
+ it('cancel during a connect: the connection that arrives late is closed, never mounted', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ a.cancel('H1')
+ h.connects[0].resolve('c1')
+ await flush()
+ expect(h.mounts).toEqual([])
+ expect(h.disconnected).toEqual(['c1'])
+ // …and a failure that lands late is not told.
+ a.run(boot())
+ a.cancel('H1')
+ h.connects[1].reject(wrap('[E_JOIN_REVOKED] x'))
+ await flush()
+ expect(h.stopped).toEqual([])
+ })
+
+ it('a mount that never became a tab (SAS declined, owner refused, timed out) releases the team', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].resolve('c1')
+ await flush()
+ h.mounts[0].resolve({ retry: false })
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ expect(h.ended).toEqual([])
+ expect(h.unsubs).toContain('c1')
+ expect(a.run(boot())).toBe('started')
+ })
+
+ it('a connection that dropped before the host answered is retried on the same ladder (the host is restarting)', async () => {
+ // connect() resolves as soon as main's relay client exists — before the host is reached — so a
+ // host that is down shows up here, as a mount that failed on a reason-less close, not as a code.
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].resolve('c1')
+ await flush()
+ h.mounts[0].resolve({ retry: true })
+ await flush()
+ expect(a.phase('H1')).toBe('waiting')
+ expect(h.armed()[0].ms).toBe(1000)
+ expect(h.unsubs).toContain('c1')
+ h.fire()
+ expect(h.connects).toHaveLength(2)
+ expect(h.stopped).toEqual([])
+ })
+
+ it('…but never for an attempt that asked not to retry (a pasted code: the mount already told its user)', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot({ manual: true, retry: false }))
+ h.connects[0].resolve('c1')
+ await flush()
+ h.mounts[0].resolve({ retry: true })
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ expect(h.armed()).toEqual([])
+ })
+
+ it('a live connection that ends is released and reported with the host\'s reason', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].resolve('c1')
+ await flush()
+ h.mounts[0].resolve({ projectId: 'proj-1' })
+ await flush()
+ h.closeCbs.get('c1')!('removed')
+ expect(a.phase('H1')).toBeNull()
+ expect(h.ended).toEqual([{ req: expect.objectContaining({ hostId: 'H1' }), projectId: 'proj-1', reason: 'removed' }])
+ expect(h.unsubs).toContain('c1')
+ })
+
+ it('a close that lands while the tab is still mounting is not lost: the team never sticks "live"', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].resolve('c1')
+ await flush()
+ h.closeCbs.get('c1')!(undefined)
+ expect(a.phase('H1')).toBe('mounting')
+ h.mounts[0].resolve({ projectId: 'proj-1' })
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ expect(h.ended).toEqual([{ req: expect.objectContaining({ hostId: 'H1' }), projectId: 'proj-1', reason: undefined }])
+ })
+
+ it('the backoff starts over after a connection went live', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ h.fire()
+ h.connects[1].resolve('c1')
+ await flush()
+ h.mounts[0].resolve({ projectId: 'proj-1' })
+ await flush()
+ h.closeCbs.get('c1')!(undefined)
+ a.run(boot())
+ h.connects[2].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ expect(h.armed()[0].ms).toBe(1000)
+ })
+
+ it('dispose stops every loop and ignores whatever lands afterwards', async () => {
+ const h = harness()
+ const a = createHostedAttempts(h.deps)
+ a.run(boot())
+ a.run(boot({ hostId: 'H2' }))
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ a.dispose()
+ expect(h.armed()).toEqual([])
+ h.connects[1].resolve('c9')
+ await flush()
+ expect(h.mounts).toEqual([])
+ expect(h.disconnected).toEqual(['c9'])
+ expect(a.run(boot())).toBe('busy') // a disposed owner starts nothing
+ })
+
+ it('a throwing mount is a failed mount, not a stuck team', async () => {
+ const h = harness()
+ const deps = { ...h.deps, mount: vi.fn(async () => { throw new Error('boom') }) }
+ const a = createHostedAttempts(deps)
+ a.run(boot())
+ h.connects[0].resolve('c1')
+ await flush()
+ await flush()
+ expect(a.phase('H1')).toBeNull()
+ })
+})
diff --git a/src/renderer/lib/hostedAttempts.ts b/src/renderer/lib/hostedAttempts.ts
new file mode 100644
index 000000000..b9fcce261
--- /dev/null
+++ b/src/renderer/lib/hostedAttempts.ts
@@ -0,0 +1,215 @@
+// The one owner of a hosted team's connection attempts in the renderer: AT MOST ONE attempt and one
+// live connection per team (hostId), shared by the boot reconnect, a dropped tab's reconnect and a
+// manual "join with code" (R38/R39).
+//
+// Why one: a second connect for a team whose first is still in flight opens a second pending request
+// at the host, which REPLACES the first and closes its socket — the user would see a refusal for an
+// attempt nobody declined. Main refuses a duplicate while it is minting and joining
+// (`[E_JOIN_BUSY]`), but its lock releases once the relay client exists, which is before the SAS
+// dialog and the owner's approval. This owner holds the team through all of it: connecting → the
+// approval wait / tab mount → live, until that connection closes.
+//
+// Why only network failures retry (R35): every other code needs a person (a fresh code, an unlocked
+// keyring, an owner) or a new day, and a loop on one of them spends the team's damped device mints.
+// Pure orchestration over injected deps, so every rule is testable without React or a relay.
+// See docs/hosted-team-relay.md.
+import type { RelayClosedReason } from '@shared/types'
+import { classifyJoinFailure, reconnectDelayMs, type JoinFailure } from './hostedTeam'
+
+export interface HostedAttemptRequest {
+ hostId: string
+ /** The team's join code (a bookmark's, or the one the user pasted). */
+ code: string
+ /** The team's name, for what the user is told. */
+ label: string
+ /** The user asked for this now: it cancels a pending backoff wait and runs at once. */
+ manual: boolean
+ /** A network failure backs off and tries again (an unattended reconnect, a tab click); off for
+ * a pasted code, whose user is watching and is told instead. */
+ retry: boolean
+ /** Reconnect onto this existing tab instead of opening a new one. */
+ reconnectProjectId?: string
+}
+
+export type HostedAttemptPhase = 'connecting' | 'waiting' | 'mounting' | 'live'
+
+/** How a mount ended: a live tab, or not — and then whether trying again could help. `retry` is for
+ * a connection that dropped before the host answered (a host restarting, a relay blip): the relay
+ * client exists before the host is reached, so that failure arrives here rather than as a code. */
+export type HostedMountResult = { projectId: string } | { retry: boolean }
+
+export interface HostedAttemptDeps {
+ /** `relayClient.connect(code)` → a connection id; rejects with main's `[E_JOIN_…]` message. */
+ connect(code: string): Promise<string>
+ /** Turn a fresh connection into a tab (the SAS, the owner's approval, the load). A failure it
+ * resolves with is one it has already handled; `retry` asks for another attempt. Never rejects
+ * (a rejection is read as `{ retry: false }`). */
+ mount(connectionId: string, req: HostedAttemptRequest): Promise<HostedMountResult>
+ onClosed(connectionId: string, listener: (reason?: RelayClosedReason) => void): () => void
+ disconnect(connectionId: string): void
+ /** A connect failed and this team's attempts stopped. Called once per stop, BUSY included (the
+ * caller decides what, if anything, to say — see `joinStopMessage`). */
+ stopped(req: HostedAttemptRequest, failure: JoinFailure): void
+ /** A live connection ended; `reason` is set only when the host refused this device. */
+ ended(req: HostedAttemptRequest, projectId: string, reason?: RelayClosedReason): void
+ setTimer(fn: () => void, ms: number): unknown
+ clearTimer(handle: unknown): void
+}
+
+export interface HostedAttempts {
+ /** Start (or, for a manual request, hurry) this team's attempt. `busy` = this team already has
+ * an attempt connecting, waiting for approval or live, and nothing was started. */
+ run(req: HostedAttemptRequest): 'started' | 'busy'
+ phase(hostId: string): HostedAttemptPhase | null
+ /** Stop a pending backoff or an in-flight connect for good. A connection already past its
+ * connect (approval wait, live tab) is the user's and is left alone. */
+ cancel(hostId: string): void
+ /** Stop everything (the canvas is going away). */
+ dispose(): void
+}
+
+interface Entry {
+ req: HostedAttemptRequest
+ phase: HostedAttemptPhase
+ attempt: number
+ timer: unknown
+ connectionId: string | null
+ projectId: string | null
+ unClose: (() => void) | null
+ /** The connection closed while its tab was still mounting: set to the close's reason holder. */
+ closedEarly: { reason?: RelayClosedReason } | null
+}
+
+export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {
+ const entries = new Map<string, Entry>()
+ let disposed = false
+
+ /** The entry for `hostId` is still `e` — async continuations of a cancelled or replaced attempt
+ * must do nothing. */
+ const current = (e: Entry): boolean => !disposed && entries.get(e.req.hostId) === e
+
+ const release = (e: Entry): void => {
+ e.unClose?.()
+ e.unClose = null
+ if (entries.get(e.req.hostId) === e) entries.delete(e.req.hostId)
+ }
+
+ const endLive = (e: Entry, reason?: RelayClosedReason): void => {
+ const projectId = e.projectId
+ release(e)
+ if (projectId) deps.ended(e.req, projectId, reason)
+ }
+
+ /** Back off, then try again (the 1/2/4/8/15/60 s ladder). */
+ const backOff = (e: Entry): void => {
+ e.phase = 'waiting'
+ e.timer = deps.setTimer(() => {
+ e.timer = null
+ if (current(e)) attempt(e)
+ }, reconnectDelayMs(e.attempt))
+ e.attempt += 1
+ }
+
+ const attempt = (e: Entry): void => {
+ e.phase = 'connecting'
+ let connection: Promise<string>
+ try {
+ connection = deps.connect(e.req.code)
+ } catch (err) {
+ connection = Promise.reject(err)
+ }
+ connection.then(
+ (connectionId) => {
+ if (!current(e)) {
+ // Cancelled (or disposed) while connecting: nobody wants this connection.
+ deps.disconnect(connectionId)
+ return
+ }
+ e.phase = 'mounting'
+ e.connectionId = connectionId
+ e.unClose = deps.onClosed(connectionId, (reason) => {
+ if (!current(e)) return
+ if (e.phase === 'live') endLive(e, reason)
+ else e.closedEarly = { reason } // the mount rejects on it too; its settle decides
+ })
+ let mounted: Promise<HostedMountResult>
+ try {
+ mounted = deps.mount(connectionId, e.req)
+ } catch (err) {
+ mounted = Promise.reject(err)
+ }
+ mounted
+ .catch((): HostedMountResult => ({ retry: false }))
+ .then((result) => {
+ if (!current(e)) return
+ if (!('projectId' in result) || !result.projectId) {
+ e.unClose?.()
+ e.unClose = null
+ e.connectionId = null
+ e.closedEarly = null
+ if ('retry' in result && result.retry && e.req.retry) backOff(e)
+ else release(e)
+ return
+ }
+ const projectId = result.projectId
+ e.projectId = projectId
+ e.attempt = 0
+ if (e.closedEarly) {
+ endLive(e, e.closedEarly.reason)
+ return
+ }
+ e.phase = 'live'
+ })
+ },
+ (err) => {
+ if (!current(e)) return
+ const failure = classifyJoinFailure(err instanceof Error ? err.message : String(err))
+ if (failure.retry && e.req.retry) {
+ backOff(e)
+ return
+ }
+ release(e)
+ deps.stopped(e.req, failure)
+ }
+ )
+ }
+
+ return {
+ run(req) {
+ if (disposed) return 'busy'
+ const existing = entries.get(req.hostId)
+ if (existing) {
+ if (existing.phase !== 'waiting' || !req.manual) return 'busy'
+ // A manual attempt hurries a waiting loop: its backoff timer goes, and the ONE attempt runs
+ // now, with the manual request's terms (it may name the tab to reconnect in place).
+ deps.clearTimer(existing.timer)
+ existing.timer = null
+ existing.req = req
+ attempt(existing)
+ return 'started'
+ }
+ const e: Entry = { req, phase: 'connecting', attempt: 0, timer: null, connectionId: null, projectId: null, unClose: null, closedEarly: null }
+ entries.set(req.hostId, e)
+ attempt(e)
+ return 'started'
+ },
+ phase(hostId) {
+ return entries.get(hostId)?.phase ?? null
+ },
+ cancel(hostId) {
+ const e = entries.get(hostId)
+ if (!e || e.phase === 'mounting' || e.phase === 'live') return
+ if (e.timer !== null) deps.clearTimer(e.timer)
+ e.timer = null
+ release(e)
+ },
+ dispose() {
+ disposed = true
+ for (const e of entries.values()) {
+ if (e.timer !== null) deps.clearTimer(e.timer)
+ e.unClose?.()
+ }
+ entries.clear()
+ }
+ }
+}
diff --git a/src/renderer/lib/hostedJoin.test.ts b/src/renderer/lib/hostedJoin.test.ts
new file mode 100644
index 000000000..483f79a05
--- /dev/null
+++ b/src/renderer/lib/hostedJoin.test.ts
@@ -0,0 +1,258 @@
+import { describe, it, expect, vi } from 'vitest'
+import type { RelayClosedReason } from '@shared/types'
+import { JOIN_CODE_PREFIX } from '@shared/relay-join-code'
+import { createHostedJoiner, type HostedJoinerDeps, type HostedMountOutcome, type HostedNotice } from './hostedJoin'
+import type { HostedAttemptRequest } from './hostedAttempts'
+import { RelayApprovalError } from './hostedTeam'
+
+const wrap = (m: string) => new Error(`Error invoking remote method 'relay:client:connect': Error: ${m}`)
+const flush = async () => {
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0))
+}
+const codeFor = (hostId: string, label = 'box') => JOIN_CODE_PREFIX + Buffer.from(JSON.stringify({ v: 1, hostId, label })).toString('base64url')
+
+type Bookmark = { hostId: string; label: string; approved: boolean; code: string }
+
+function harness(bookmarks: Bookmark[] = []) {
+ const connects: Array<{ code: string; resolve: (id: string) => void; reject: (e: Error) => void }> = []
+ const mounts: Array<{ id: string; req: HostedAttemptRequest; resolve: (o: HostedMountOutcome) => void }> = []
+ const closeCbs = new Map<string, (reason?: RelayClosedReason) => void>()
+ const notices: HostedNotice[] = []
+ const timers: Array<{ fn: () => void; ms: number; cleared: boolean }> = []
+ const open = new Set<string>()
+ let list = [...bookmarks]
+ const deps: HostedJoinerDeps = {
+ connect: (code) => new Promise((resolve, reject) => connects.push({ code, resolve, reject })),
+ onClosed: (id, cb) => {
+ closeCbs.set(id, cb)
+ return () => closeCbs.delete(id)
+ },
+ disconnect: vi.fn(),
+ bookmarks: vi.fn(async () => list),
+ removeBookmark: vi.fn(async (hostId: string) => {
+ list = list.filter((b) => b.hostId !== hostId)
+ }),
+ mount: (id, req) => new Promise((resolve) => mounts.push({ id, req, resolve })),
+ tabOpen: (projectId) => open.has(projectId),
+ notify: (n) => notices.push(n),
+ promptForCode: vi.fn(async () => null as string | null),
+ setTimer: (fn, ms) => {
+ const t = { fn, ms, cleared: false }
+ timers.push(t)
+ return t
+ },
+ clearTimer: (t) => {
+ ;(t as { cleared: boolean }).cleared = true
+ }
+ }
+ return { deps, connects, mounts, closeCbs, notices, timers, open, setList: (l: Bookmark[]) => { list = l } }
+}
+
+/** Connect + mount one attempt to a live tab. */
+async function goLive(h: ReturnType<typeof harness>, i: number, projectId: string) {
+ h.connects[i].resolve(`c${i}`)
+ await flush()
+ h.open.add(projectId)
+ h.mounts[h.mounts.length - 1].resolve({ projectId })
+ await flush()
+}
+
+describe('hosted joiner', () => {
+ it('boot reconnects only APPROVED bookmarks, each as an unattended, retrying, background attempt', async () => {
+ const h = harness([
+ { hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') },
+ { hostId: 'H2', label: 'lab', approved: false, code: codeFor('H2') }
+ ])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ expect(h.connects.map((c) => c.code)).toEqual([codeFor('H1')])
+ await goLive(h, 0, 'proj-1')
+ expect(h.mounts[0].req).toMatchObject({ hostId: 'H1', label: 'box', manual: false, retry: true })
+ })
+
+ it('a pasted code runs NOW, does not loop, and a second paste for the same team is refused politely', async () => {
+ const h = harness()
+ const j = createHostedJoiner(h.deps)
+ j.joinWithCode(` ${codeFor('H1', 'box')} `)
+ expect(h.connects).toHaveLength(1)
+ j.joinWithCode(codeFor('H1', 'box'))
+ expect(h.connects).toHaveLength(1)
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: 'Already connecting to box…' })
+ await goLive(h, 0, 'proj-1')
+ expect(h.mounts[0].req).toMatchObject({ manual: true, retry: false })
+ j.joinWithCode(codeFor('H1', 'box'))
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: "You're already connected to box." })
+ expect(h.connects).toHaveLength(1)
+ })
+
+ it('a code pasted into a greyed tab\'s prompt reconnects THAT tab (never a second one)', async () => {
+ const h = harness()
+ const j = createHostedJoiner(h.deps)
+ j.joinWithCode(codeFor('H1'), 'proj-7')
+ h.connects[0].resolve('c0')
+ await flush()
+ expect(h.mounts[0].req).toMatchObject({ hostId: 'H1', reconnectProjectId: 'proj-7', manual: true, retry: false })
+ })
+
+ it('a pasted code the renderer cannot read is still handed to main, which answers for it', async () => {
+ const h = harness()
+ const j = createHostedJoiner(h.deps)
+ j.joinWithCode(`${JOIN_CODE_PREFIX}%%%`)
+ h.connects[0].reject(wrap('[E_JOIN_BAD_CODE] That team code is invalid.'))
+ await flush()
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'error', text: 'The invite code for the team is not valid. Ask an owner for a fresh code.' })
+ })
+
+ it('a dropped tab reconnects in place, in the background, while its team is still bookmarked and approved', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ await goLive(h, 0, 'proj-1')
+ h.closeCbs.get('c0')!(undefined)
+ await flush()
+ expect(h.connects).toHaveLength(2)
+ await goLive(h, 1, 'proj-1')
+ expect(h.mounts[1].req).toMatchObject({ reconnectProjectId: 'proj-1', manual: false, retry: true })
+ expect(h.notices).toEqual([])
+ })
+
+ it('a drop does NOT reconnect a tab the user closed, a team they forgot, or one no longer approved', async () => {
+ for (const setup of ['closed', 'forgotten', 'unapproved'] as const) {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ await goLive(h, 0, 'proj-1')
+ if (setup === 'closed') h.open.delete('proj-1')
+ if (setup === 'forgotten') h.setList([])
+ if (setup === 'unapproved') h.setList([{ hostId: 'H1', label: 'box', approved: false, code: codeFor('H1') }])
+ h.closeCbs.get('c0')!(undefined)
+ await flush()
+ expect(h.connects, setup).toHaveLength(1)
+ }
+ })
+
+ it('a close the host explained is told once and never reconnects', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ await goLive(h, 0, 'proj-1')
+ h.closeCbs.get('c0')!('removed')
+ await flush()
+ expect(h.connects).toHaveLength(1)
+ expect(h.notices).toEqual([{ kind: 'error', text: 'box: Your access to this team was removed by an owner.' }])
+ })
+
+ it('clicking a greyed hosted tab reconnects it in place now; a tab it never opened is not its business', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ expect(j.reconnectTab('proj-1')).toBe(false)
+ await j.bootReconnect()
+ await goLive(h, 0, 'proj-1')
+ h.setList([]) // forgotten: the automatic reconnect stays off…
+ h.closeCbs.get('c0')!(undefined)
+ await flush()
+ expect(j.isHostedTab('proj-1')).toBe(true)
+ expect(j.reconnectTab('proj-1')).toBe(true) // …but the user asked
+ expect(h.connects).toHaveLength(2)
+ h.connects[1].resolve('c1')
+ await flush()
+ expect(h.mounts[1].req).toMatchObject({ reconnectProjectId: 'proj-1', manual: true, retry: true })
+ })
+
+ it('REVOKED stops and offers "remove and rejoin": forget the bookmark, ask for a fresh code, join with it', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ ;(h.deps.promptForCode as ReturnType<typeof vi.fn>).mockResolvedValue(codeFor('H9', 'box'))
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ h.connects[0].reject(wrap("[E_JOIN_REVOKED] This device's relay access was revoked."))
+ await flush()
+ const n = h.notices.at(-1)!
+ expect(n.kind).toBe('error')
+ expect(n.text).toMatch(/revoked/)
+ expect(n.action?.label).toBe('Remove and rejoin')
+ n.action!.run()
+ await flush()
+ expect(h.deps.removeBookmark).toHaveBeenCalledWith('H1')
+ expect(h.deps.promptForCode).toHaveBeenCalledWith('box')
+ expect(h.connects.at(-1)!.code).toBe(codeFor('H9', 'box'))
+ })
+
+ it('a stop is told in one sentence; BUSY is never told', async () => {
+ const h = harness()
+ const j = createHostedJoiner(h.deps)
+ j.joinWithCode(codeFor('H1'))
+ h.connects[0].reject(wrap('[E_JOIN_BUSY] Already joining this team.'))
+ await flush()
+ expect(h.notices).toEqual([])
+ j.joinWithCode(codeFor('H1'))
+ h.connects[1].reject(wrap('[E_JOIN_REFUSED] The hosted-team bookmarks file /u/relay-bookmarks.json cannot be read or safely rewritten; fix or remove it, then join again.'))
+ await flush()
+ expect(h.notices).toEqual([
+ { kind: 'error', text: 'Could not join box: The hosted-team bookmarks file /u/relay-bookmarks.json cannot be read or safely rewritten; fix or remove it, then join again.' }
+ ])
+ })
+
+ it('a tab that never opened: an unattended attempt retries silently; a pasted code is told why', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ h.connects[0].resolve('c0')
+ await flush()
+ h.mounts[0].resolve({ error: new RelayApprovalError('The relay connection closed before it was approved.'), declined: false })
+ await flush()
+ expect(h.notices).toEqual([])
+ expect(h.timers.filter((t) => !t.cleared)).toHaveLength(1)
+
+ const p = harness()
+ const jp = createHostedJoiner(p.deps)
+ jp.joinWithCode(codeFor('H2', 'lab'))
+ p.connects[0].resolve('c0')
+ await flush()
+ p.mounts[0].resolve({ error: new RelayApprovalError('An owner declined the request.', 'denied'), declined: false })
+ await flush()
+ expect(p.notices).toEqual([{ kind: 'error', text: 'Could not open lab: An owner declined the request.' }])
+ // A SAS the user declined is their own answer: nothing to tell.
+ jp.joinWithCode(codeFor('H2', 'lab'))
+ p.connects[1].resolve('c1')
+ await flush()
+ p.mounts[1].resolve({ error: new Error('closed'), declined: true })
+ await flush()
+ expect(p.notices).toHaveLength(1)
+ })
+
+ it('forgetting a team stops its reconnect loop and removes the bookmark; it is refused while connecting', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ await j.forget('H1', 'box')
+ expect(h.deps.removeBookmark).not.toHaveBeenCalled()
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: 'Still connecting to box; forget it once that finishes.' })
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ expect(h.timers.filter((t) => !t.cleared)).toHaveLength(1) // backing off
+ await j.forget('H1', 'box')
+ expect(h.timers.filter((t) => !t.cleared)).toHaveLength(0) // the loop is gone
+ expect(h.deps.removeBookmark).toHaveBeenCalledWith('H1')
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: 'Forgot box. This device will not reconnect to it.' })
+ })
+
+ it('main\'s refusal to forget (a join still in flight there) is shown in its own words', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ ;(h.deps.removeBookmark as ReturnType<typeof vi.fn>).mockRejectedValue(
+ new Error("Error invoking remote method 'relay:hosted:bookmark-remove': Error: Still joining this team; forget it once that attempt finishes.")
+ )
+ const j = createHostedJoiner(h.deps)
+ await j.forget('H1', 'box')
+ expect(h.notices.at(-1)).toEqual({ kind: 'error', text: 'Could not forget box: Still joining this team; forget it once that attempt finishes.' })
+ })
+
+ it('dispose stops every loop', async () => {
+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])
+ const j = createHostedJoiner(h.deps)
+ await j.bootReconnect()
+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))
+ await flush()
+ j.dispose()
+ expect(h.timers.filter((t) => !t.cleared)).toHaveLength(0)
+ })
+})
diff --git a/src/renderer/lib/hostedJoin.ts b/src/renderer/lib/hostedJoin.ts
new file mode 100644
index 000000000..28f88ab3a
--- /dev/null
+++ b/src/renderer/lib/hostedJoin.ts
@@ -0,0 +1,193 @@
+// Every way this desktop (re)joins a hosted team, over ONE attempt owner per team (hostedAttempts.ts):
+// - boot: each APPROVED bookmark reconnects on its own, in the background;
+// - a drop: a live hosted tab whose connection dropped (no host reason) reconnects in place, in the
+// background, while its team is still bookmarked and approved and the tab is still open;
+// - a click on the greyed tab: reconnects in place now (no pairing-code prompt — the bookmark is the
+// credential);
+// - a pasted join code: joins now, and is told why if it cannot;
+// - forgetting a team: stops its loop and removes its bookmark (the host is not touched).
+// And what the user is told for each: one sentence per stop, nothing for a retry in progress, a
+// "remove and rejoin" offer after a revocation. Pure over injected deps (no React, no window).
+// See docs/hosted-team-relay.md.
+import type { RelayClosedReason, RelayHostedApi } from '@shared/types'
+import { peekJoinCode } from '@shared/relay-join-code'
+import { createHostedAttempts, type HostedAttemptRequest, type HostedMountResult } from './hostedAttempts'
+import { closedReasonMessage, joinStopMessage, mountFailureMessage, mountFailureRetries, stripIpcPrefix } from './hostedTeam'
+
+/** How a mount ended, as the canvas reports it: a live tab, or the error it failed with. `declined`
+ * = this user declined the SAS themselves (nothing to tell them). */
+export type HostedMountOutcome = { projectId: string } | { error: unknown; declined: boolean }
+
+export interface HostedNotice {
+ kind: 'info' | 'error'
+ text: string
+ action?: { label: string; run: () => void }
+}
+
+export interface HostedJoinerDeps {
+ /** `relayClient.connect` — a join code in, a connection id out (or main's `[E_JOIN_…]` refusal). */
+ connect(code: string): Promise<string>
+ onClosed(connectionId: string, listener: (reason?: RelayClosedReason) => void): () => void
+ disconnect(connectionId: string): void
+ bookmarks: RelayHostedApi['bookmarks']
+ removeBookmark: RelayHostedApi['removeBookmark']
+ /** The SAS (a first join), the owner's approval, the tab. Never rejects on purpose; a rejection
+ * is read as a failure with that error. */
+ mount(connectionId: string, req: HostedAttemptRequest): Promise<HostedMountOutcome>
+ /** Is this project still an open tab (not closed, not deleted)? */
+ tabOpen(projectId: string): boolean
+ notify(notice: HostedNotice): void
+ /** Ask the user for a fresh invite code for `teamLabel`; null = cancelled. */
+ promptForCode(teamLabel: string): Promise<string | null>
+ setTimer(fn: () => void, ms: number): unknown
+ clearTimer(handle: unknown): void
+}
+
+export interface HostedJoiner {
+ /** A join code the user pasted: joins now, never loops. `reconnectProjectId` = it was pasted
+ * into a greyed tab's reconnect prompt, so that tab is the one it reconnects. */
+ joinWithCode(code: string, reconnectProjectId?: string): void
+ /** A greyed tab was clicked. False when it is not a hosted tab this joiner opened (the caller
+ * takes its pairing-code path). */
+ reconnectTab(projectId: string): boolean
+ isHostedTab(projectId: string): boolean
+ /** Reconnect every approved bookmark (once, at boot). */
+ bootReconnect(): Promise<void>
+ /** Forget a team: its loop stops and its bookmark goes. Refused while it is connecting. */
+ forget(hostId: string, label: string): Promise<void>
+ /** Is this team connecting or waiting for the host right now? */
+ connecting(hostId: string): boolean
+ dispose(): void
+}
+
+const team = (label: string): string => label.trim() || 'the team'
+
+export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {
+ /** The team each hosted tab this joiner opened belongs to, by project id. */
+ const tabs = new Map<string, { hostId: string; code: string; label: string }>()
+ let run: (req: HostedAttemptRequest) => 'started' | 'busy' = () => 'busy'
+
+ const attempts = createHostedAttempts({
+ connect: deps.connect,
+ onClosed: deps.onClosed,
+ disconnect: deps.disconnect,
+ setTimer: deps.setTimer,
+ clearTimer: deps.clearTimer,
+ async mount(connectionId, req): Promise<HostedMountResult> {
+ let outcome: HostedMountOutcome
+ try {
+ outcome = await deps.mount(connectionId, req)
+ } catch (error) {
+ outcome = { error, declined: false }
+ }
+ if ('projectId' in outcome) {
+ tabs.set(outcome.projectId, { hostId: req.hostId, code: req.code, label: req.label })
+ return { projectId: outcome.projectId }
+ }
+ if (outcome.declined) return { retry: false }
+ const retry = mountFailureRetries(outcome.error)
+ // An unattended attempt that will try again says nothing; the next one may well work.
+ if (retry && req.retry) return { retry: true }
+ deps.notify({ kind: 'error', text: mountFailureMessage(outcome.error, req.label) })
+ return { retry: false }
+ },
+ stopped(req, failure) {
+ const text = joinStopMessage(failure, req.label)
+ if (!text) return
+ if (failure.code === 'E_JOIN_REVOKED') {
+ deps.notify({ kind: 'error', text, action: { label: 'Remove and rejoin', run: () => void removeAndRejoin(req) } })
+ return
+ }
+ deps.notify({ kind: 'error', text })
+ },
+ ended(req, projectId, reason) {
+ const said = closedReasonMessage(reason)
+ if (said) {
+ deps.notify({ kind: 'error', text: `${team(req.label)}: ${said}` })
+ return
+ }
+ // A drop. Come back in place, unattended — but only for a tab still open, on a team still
+ // bookmarked and approved (a forgotten team, or one whose approval was withdrawn, waits for
+ // the user; an approved bookmark reconnects with no SAS on this side).
+ if (!deps.tabOpen(projectId)) return
+ void deps.bookmarks().then(
+ (list) => {
+ const b = list.find((x) => x.hostId === req.hostId)
+ if (!b?.approved || !deps.tabOpen(projectId)) return
+ run({ hostId: b.hostId, code: b.code, label: b.label, manual: false, retry: true, reconnectProjectId: projectId })
+ },
+ () => {}
+ )
+ }
+ })
+ run = (req) => attempts.run(req)
+
+ const busyText = (hostId: string, label: string): string =>
+ attempts.phase(hostId) === 'live' ? `You're already connected to ${team(label)}.` : `Already connecting to ${team(label)}…`
+
+ async function removeAndRejoin(req: HostedAttemptRequest): Promise<void> {
+ // The bookmark still holds the revoked token: offering it again would only be refused again.
+ try {
+ await deps.removeBookmark(req.hostId)
+ } catch (err) {
+ deps.notify({ kind: 'error', text: `Could not forget ${team(req.label)}: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` })
+ return
+ }
+ const code = (await deps.promptForCode(req.label))?.trim()
+ if (code) joiner.joinWithCode(code)
+ }
+
+ const joiner: HostedJoiner = {
+ joinWithCode(raw, reconnectProjectId) {
+ const code = raw.trim()
+ const peek = peekJoinCode(code)
+ // A code the renderer cannot read still goes to main, which verifies codes and answers for
+ // this one; its key is the text itself, so a double paste of it is still one attempt.
+ const hostId = peek?.hostId ?? `unreadable:${code}`
+ const label = peek?.label ?? ''
+ const req: HostedAttemptRequest = { hostId, code, label, manual: true, retry: false, ...(reconnectProjectId ? { reconnectProjectId } : {}) }
+ if (run(req) === 'busy') {
+ deps.notify({ kind: 'info', text: busyText(hostId, label) })
+ }
+ },
+ reconnectTab(projectId) {
+ const t = tabs.get(projectId)
+ if (!t) return false
+ if (run({ ...t, manual: true, retry: true, reconnectProjectId: projectId }) === 'busy') {
+ deps.notify({ kind: 'info', text: `Already reconnecting to ${team(t.label)}…` })
+ }
+ return true
+ },
+ isHostedTab(projectId) {
+ return tabs.has(projectId)
+ },
+ async bootReconnect() {
+ const list = await deps.bookmarks().catch(() => [])
+ for (const b of list) {
+ if (b.approved) run({ hostId: b.hostId, code: b.code, label: b.label, manual: false, retry: true })
+ }
+ },
+ async forget(hostId, label) {
+ if (joiner.connecting(hostId)) {
+ deps.notify({ kind: 'info', text: `Still connecting to ${team(label)}; forget it once that finishes.` })
+ return
+ }
+ attempts.cancel(hostId)
+ try {
+ await deps.removeBookmark(hostId)
+ } catch (err) {
+ deps.notify({ kind: 'error', text: `Could not forget ${team(label)}: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` })
+ return
+ }
+ deps.notify({ kind: 'info', text: `Forgot ${team(label)}. This device will not reconnect to it.` })
+ },
+ connecting(hostId) {
+ const phase = attempts.phase(hostId)
+ return phase === 'connecting' || phase === 'mounting'
+ },
+ dispose() {
+ attempts.dispose()
+ }
+ }
+ return joiner
+}
diff --git a/src/renderer/lib/hostedOwner.test.ts b/src/renderer/lib/hostedOwner.test.ts
new file mode 100644
index 000000000..5775ae86e
--- /dev/null
+++ b/src/renderer/lib/hostedOwner.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi } from 'vitest'
+import type { HostedPending, HostedPendingClosedReason, HostedSessionApi } from '@shared/types'
+import { attachHostedOwner, answerHostedRequest } from './hostedOwner'
+import type { QueuedRequest } from './hostedPendingQueue'
+
+function fakeHosted(pulled: HostedPending[] | Error = []) {
+ const calls: string[] = []
+ let onPending: ((p: HostedPending) => void) | null = null
+ let onClosed: ((c: { pendingId: string; reason: HostedPendingClosedReason }) => void) | null = null
+ const unPending = vi.fn()
+ const unClosed = vi.fn()
+ const hosted = {
+ self: vi.fn(),
+ inviteCode: vi.fn(),
+ approve: vi.fn(async () => true),
+ deny: vi.fn(async () => true),
+ pending: vi.fn(async () => {
+ calls.push('pull')
+ if (pulled instanceof Error) throw pulled
+ return pulled
+ }),
+ onPeerPending: vi.fn((l) => {
+ calls.push('sub:pending')
+ onPending = l
+ return unPending
+ }),
+ onPendingClosed: vi.fn((l) => {
+ calls.push('sub:closed')
+ onClosed = l
+ return unClosed
+ })
+ } as unknown as HostedSessionApi
+ return { hosted, calls, unPending, unClosed, push: (p: HostedPending) => onPending?.(p), close: (id: string, reason: HostedPendingClosedReason) => onClosed?.({ pendingId: id, reason }) }
+}
+
+const sink = () => {
+ const added: QueuedRequest[] = []
+ const closed: Array<[string, string]> = []
+ const dropped: string[] = []
+ return { added, closed, dropped, add: (i: QueuedRequest) => added.push(i), close: (id: string, r: HostedPendingClosedReason) => closed.push([id, r]), drop: (p: string) => dropped.push(p) }
+}
+const P = (id: string, since = 1): HostedPending => ({ pendingId: id, sas: '1 2', peerKeyB64: 'K', since })
+const flush = () => new Promise((r) => setTimeout(r, 0))
+
+describe('attachHostedOwner (R25)', () => {
+ it('subscribes FIRST, then pulls once, and feeds both into the queue', async () => {
+ const f = fakeHosted([P('pulled')])
+ const s = sink()
+ attachHostedOwner(f.hosted, { projectId: 'p1', teamLabel: 'box' }, s)
+ expect(f.calls).toEqual(['sub:pending', 'sub:closed', 'pull'])
+ f.push(P('pushed'))
+ await flush()
+ expect(s.added.map((i) => i.pending.pendingId).sort()).toEqual(['pulled', 'pushed'])
+ expect(s.added[0]).toMatchObject({ projectId: 'p1', teamLabel: 'box', answerer: f.hosted })
+ f.close('pushed', 'expired')
+ expect(s.closed).toEqual([['pushed', 'expired']])
+ })
+
+ it('a failed pull is not fatal: the push deltas still arrive', async () => {
+ const f = fakeHosted(new Error('E_DISCONNECTED'))
+ const s = sink()
+ attachHostedOwner(f.hosted, { projectId: 'p1', teamLabel: 'box' }, s)
+ await flush()
+ f.push(P('a'))
+ expect(s.added).toHaveLength(1)
+ })
+
+ it('detaching unsubscribes, drops the tab\'s requests, and ignores a pull that lands afterwards', async () => {
+ let resolvePull!: (v: HostedPending[]) => void
+ const f = fakeHosted()
+ ;(f.hosted.pending as ReturnType<typeof vi.fn>).mockImplementation(() => new Promise((r) => { resolvePull = r }))
+ const s = sink()
+ const detach = attachHostedOwner(f.hosted, { projectId: 'p1', teamLabel: 'box' }, s)
+ detach()
+ expect(f.unPending).toHaveBeenCalled()
+ expect(f.unClosed).toHaveBeenCalled()
+ expect(s.dropped).toEqual(['p1'])
+ resolvePull([P('late')])
+ await flush()
+ f.push(P('also-late'))
+ expect(s.added).toEqual([])
+ })
+})
+
+describe('answerHostedRequest', () => {
+ const item = (hosted: HostedSessionApi): QueuedRequest => ({ projectId: 'p1', teamLabel: 'box', pending: P('x'), answerer: hosted })
+
+ it('approves with the chosen role and says nothing when it landed', async () => {
+ const f = fakeHosted()
+ expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'commenter' })).toBeNull()
+ expect(f.hosted.approve).toHaveBeenCalledWith('x', 'commenter')
+ })
+
+ it('a false answer means another owner (or the device leaving) got there first', async () => {
+ const f = fakeHosted()
+ ;(f.hosted.deny as ReturnType<typeof vi.fn>).mockResolvedValue(false)
+ expect(await answerHostedRequest(item(f.hosted), { kind: 'deny' })).toEqual({ kind: 'info', text: 'That request was already answered or has gone.' })
+ })
+
+ it('a refused answer says so, in the host\'s words', async () => {
+ const f = fakeHosted()
+ ;(f.hosted.approve as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Only an owner can approve.'))
+ expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'viewer' })).toEqual({ kind: 'error', text: 'Could not answer the request: Only an owner can approve.' })
+ })
+})
diff --git a/src/renderer/lib/hostedOwner.ts b/src/renderer/lib/hostedOwner.ts
new file mode 100644
index 000000000..c3359b902
--- /dev/null
+++ b/src/renderer/lib/hostedOwner.ts
@@ -0,0 +1,64 @@
+// An OWNER's relay tab on a hosted team: listen for devices asking to join and answer them.
+//
+// Subscribe FIRST, then pull (R25). The host tells a connected owner every open request as it
+// arrives and replays the open ones when the owner's session opens — that replay can land before
+// this tab subscribed, and the pull (`relay:hosted:pending`) is what makes that safe. The queue
+// de-dupes, so the two overlapping is harmless. See docs/hosted-team-relay.md.
+import type { HostedPendingClosedReason, HostedRole, HostedSessionApi } from '@shared/types'
+import type { QueuedRequest } from './hostedPendingQueue'
+import { stripIpcPrefix } from './hostedTeam'
+
+export interface OwnerQueueSink {
+ add(item: QueuedRequest): void
+ close(pendingId: string, reason: HostedPendingClosedReason): void
+ /** The tab is going away: drop its requests. */
+ drop(projectId: string): void
+}
+
+/** Start feeding one owner tab's requests into the queue. Returns its teardown (idempotent). */
+export function attachHostedOwner(
+ hosted: HostedSessionApi,
+ ctx: { projectId: string; teamLabel: string },
+ sink: OwnerQueueSink
+): () => void {
+ let live = true
+ const add = (pending: unknown): void => {
+ if (live) sink.add({ projectId: ctx.projectId, teamLabel: ctx.teamLabel, pending: pending as QueuedRequest['pending'], answerer: hosted })
+ }
+ const unPending = hosted.onPeerPending(add)
+ const unClosed = hosted.onPendingClosed((c) => {
+ if (live && c && typeof c.pendingId === 'string') sink.close(c.pendingId, c.reason)
+ })
+ hosted.pending().then(
+ (list) => {
+ if (Array.isArray(list)) for (const p of list) add(p)
+ },
+ // A failed pull (the tab dropped, the host refused) costs only the replay safety net: the push
+ // deltas keep arriving, and a reconnect pulls again.
+ () => {}
+ )
+ return () => {
+ if (!live) return
+ live = false
+ unPending()
+ unClosed()
+ sink.drop(ctx.projectId)
+ }
+}
+
+export type HostedAnswer = { kind: 'approve'; role: HostedRole } | { kind: 'deny' }
+
+/** Send an owner's answer. Resolves with the line to show the owner, or null when it landed. */
+export async function answerHostedRequest(
+ item: QueuedRequest,
+ answer: HostedAnswer
+): Promise<{ kind: 'info' | 'error'; text: string } | null> {
+ const id = item.pending.pendingId
+ try {
+ const ok = answer.kind === 'approve' ? await item.answerer.approve(id, answer.role) : await item.answerer.deny(id)
+ // False is an answer, not a failure: another owner got there first, or the device left.
+ return ok ? null : { kind: 'info', text: 'That request was already answered or has gone.' }
+ } catch (err) {
+ return { kind: 'error', text: `Could not answer the request: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` }
+ }
+}
diff --git a/src/renderer/lib/hostedPendingQueue.test.ts b/src/renderer/lib/hostedPendingQueue.test.ts
new file mode 100644
index 000000000..011bbf12b
--- /dev/null
+++ b/src/renderer/lib/hostedPendingQueue.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ EMPTY_PENDING_QUEUE,
+ addRequest,
+ closeRequest,
+ settleRequest,
+ dropProjectRequests,
+ headRequest,
+ SETTLED_MEMORY,
+ type QueuedRequest
+} from './hostedPendingQueue'
+
+const answerer = { approve: vi.fn(async () => true), deny: vi.fn(async () => true) }
+const req = (pendingId: string, since: number, projectId = 'p1'): QueuedRequest => ({
+ projectId,
+ teamLabel: 'box',
+ pending: { pendingId, sas: '111 222', peerKeyB64: `K${pendingId}`, since },
+ answerer
+})
+
+describe('hosted pending queue (R37)', () => {
+ it('keeps EVERY open request, oldest first — a second knock is never dropped', () => {
+ let q = addRequest(EMPTY_PENDING_QUEUE, req('b', 20))
+ q = addRequest(q, req('a', 10))
+ q = addRequest(q, req('c', 30))
+ expect(q.items.map((i) => i.pending.pendingId)).toEqual(['a', 'b', 'c'])
+ expect(headRequest(q)?.pending.pendingId).toBe('a')
+ })
+
+ it('de-dupes by pendingId: a pull that repeats a pushed request, or a replay, adds nothing', () => {
+ let q = addRequest(EMPTY_PENDING_QUEUE, req('a', 10))
+ const again = addRequest(q, req('a', 10))
+ expect(again).toBe(q)
+ q = addRequest(q, req('b', 5))
+ expect(q.items.map((i) => i.pending.pendingId)).toEqual(['b', 'a'])
+ })
+
+ it('a request closed by another owner is dropped, and only the one on screen earns a line', () => {
+ let q = addRequest(addRequest(EMPTY_PENDING_QUEUE, req('a', 10)), req('b', 20))
+ const behind = closeRequest(q, 'b', 'approved')
+ expect(behind.notice).toBeNull()
+ expect(behind.queue.items.map((i) => i.pending.pendingId)).toEqual(['a'])
+ const onScreen = closeRequest(q, 'a', 'denied')
+ expect(onScreen.notice).toBe('Another owner answered this request.')
+ expect(headRequest(onScreen.queue)?.pending.pendingId).toBe('b')
+ })
+
+ it('expired, gone and replaced close silently (a replaced request\'s successor arrives on its own)', () => {
+ for (const reason of ['expired', 'gone', 'replaced'] as const) {
+ const r = closeRequest(addRequest(EMPTY_PENDING_QUEUE, req('a', 10)), 'a', reason)
+ expect(r.notice, reason).toBeNull()
+ expect(r.queue.items).toEqual([])
+ }
+ })
+
+ it('a closed or answered request never comes back from a late replay or pull', () => {
+ let q = addRequest(EMPTY_PENDING_QUEUE, req('a', 10))
+ q = settleRequest(q, 'a') // this owner answered it
+ expect(q.items).toEqual([])
+ expect(addRequest(q, req('a', 10)).items).toEqual([])
+ // A close for a request this owner never saw is remembered too.
+ q = closeRequest(q, 'z', 'expired').queue
+ expect(addRequest(q, req('z', 1)).items).toEqual([])
+ })
+
+ it('the closed-id memory is bounded', () => {
+ let q = EMPTY_PENDING_QUEUE
+ for (let i = 0; i < SETTLED_MEMORY + 10; i++) q = settleRequest(q, `s${i}`)
+ expect(q.settled.length).toBe(SETTLED_MEMORY)
+ expect(q.settled).not.toContain('s0')
+ expect(q.settled).toContain(`s${SETTLED_MEMORY + 9}`)
+ })
+
+ it('a tab that goes away takes only its own requests, and does not mark them answered', () => {
+ let q = addRequest(addRequest(EMPTY_PENDING_QUEUE, req('a', 10, 'p1')), req('b', 20, 'p2'))
+ q = dropProjectRequests(q, 'p1')
+ expect(q.items.map((i) => i.pending.pendingId)).toEqual(['b'])
+ // Its reconnect pulls them again.
+ expect(addRequest(q, req('a', 10, 'p1')).items.map((i) => i.pending.pendingId)).toEqual(['a', 'b'])
+ })
+
+ it('ignores what is not a request (the events come off the wire)', () => {
+ for (const bad of [
+ { pendingId: '', sas: 'x', peerKeyB64: 'k', since: 1 },
+ { pendingId: 'a', sas: 1, peerKeyB64: 'k', since: 1 },
+ { pendingId: 'a', sas: 'x', peerKeyB64: 'k', since: Number.NaN },
+ null
+ ]) {
+ expect(addRequest(EMPTY_PENDING_QUEUE, { ...req('a', 1), pending: bad as never }).items).toEqual([])
+ }
+ })
+})
diff --git a/src/renderer/lib/hostedPendingQueue.ts b/src/renderer/lib/hostedPendingQueue.ts
new file mode 100644
index 000000000..7f965b1eb
--- /dev/null
+++ b/src/renderer/lib/hostedPendingQueue.ts
@@ -0,0 +1,93 @@
+// The owner's queue of devices waiting to join a hosted team — pure, so the rules are testable
+// without React. The host allows up to 16 requests at once (one per device key), so a single "the
+// pending request" slot would silently drop the second knock (R37): every open request is kept,
+// keyed by pendingId, oldest first, and the dialog shows the head. Seeded by the pull an owner's tab
+// makes on open (R25); the push events are deltas after that, and either may repeat the other.
+import type { HostedPending, HostedPendingClosedReason, HostedRole } from '@shared/types'
+import { pendingClosedNotice } from './hostedTeam'
+
+/** Where an answer goes: the hosted verbs of the session that raised the request. */
+export interface HostedAnswerer {
+ approve(pendingId: string, role: HostedRole): Promise<boolean>
+ deny(pendingId: string): Promise<boolean>
+}
+
+export interface QueuedRequest {
+ /** The owner's relay tab the request arrived on (a tab that goes away takes its own requests). */
+ projectId: string
+ teamLabel: string
+ pending: HostedPending
+ answerer: HostedAnswerer
+}
+
+export interface PendingQueue {
+ items: readonly QueuedRequest[]
+ /** Requests already answered here or closed at the host, most recent last: a late replay or pull
+ * of one must not bring its dialog back. */
+ settled: readonly string[]
+}
+
+export const EMPTY_PENDING_QUEUE: PendingQueue = Object.freeze({ items: [], settled: [] })
+
+/** How many closed request ids are remembered (4× the host's concurrent cap). */
+export const SETTLED_MEMORY = 64
+
+/** A request as the host sends it — these arrive off the wire, so the shape is checked here. */
+function wellFormed(p: unknown): p is HostedPending {
+ if (!p || typeof p !== 'object') return false
+ const o = p as Record<string, unknown>
+ return (
+ typeof o.pendingId === 'string' &&
+ o.pendingId.length > 0 &&
+ typeof o.sas === 'string' &&
+ typeof o.peerKeyB64 === 'string' &&
+ typeof o.since === 'number' &&
+ Number.isFinite(o.since)
+ )
+}
+
+const remember = (settled: readonly string[], id: string): string[] =>
+ [...settled.filter((x) => x !== id), id].slice(-SETTLED_MEMORY)
+
+/** Add a request (a push, or one entry of the pull). Unchanged when it is malformed, already queued
+ * or already settled. Kept oldest first; a tie keeps arrival order. */
+export function addRequest(q: PendingQueue, item: QueuedRequest): PendingQueue {
+ if (!wellFormed(item.pending)) return q
+ const id = item.pending.pendingId
+ if (q.settled.includes(id) || q.items.some((i) => i.pending.pendingId === id)) return q
+ const at = q.items.findIndex((i) => i.pending.since > item.pending.since)
+ const items = at < 0 ? [...q.items, item] : [...q.items.slice(0, at), item, ...q.items.slice(at)]
+ return { ...q, items }
+}
+
+/** The host says a request is no longer pending. `notice` is set only when it was the one on
+ * screen and ANOTHER owner answered it (approved/denied); expired/gone/replaced close silently. */
+export function closeRequest(
+ q: PendingQueue,
+ pendingId: string,
+ reason: HostedPendingClosedReason
+): { queue: PendingQueue; notice: string | null } {
+ const wasHead = headRequest(q)?.pending.pendingId === pendingId
+ const queue: PendingQueue = {
+ items: q.items.filter((i) => i.pending.pendingId !== pendingId),
+ settled: remember(q.settled, pendingId)
+ }
+ return { queue, notice: wasHead ? pendingClosedNotice(reason) : null }
+}
+
+/** This owner answered a request: it leaves the queue now (the host's own close follows). */
+export function settleRequest(q: PendingQueue, pendingId: string): PendingQueue {
+ return { items: q.items.filter((i) => i.pending.pendingId !== pendingId), settled: remember(q.settled, pendingId) }
+}
+
+/** The owner's tab went away (dropped, closed): its requests leave the queue unanswered — its
+ * reconnect pulls them again, so they are not marked settled. */
+export function dropProjectRequests(q: PendingQueue, projectId: string): PendingQueue {
+ const items = q.items.filter((i) => i.projectId !== projectId)
+ return items.length === q.items.length ? q : { ...q, items }
+}
+
+/** The request the dialog shows: the oldest one. */
+export function headRequest(q: PendingQueue): QueuedRequest | null {
+ return q.items[0] ?? null
+}
diff --git a/src/renderer/lib/hostedTeam.test.ts b/src/renderer/lib/hostedTeam.test.ts
new file mode 100644
index 000000000..06b8d66a7
--- /dev/null
+++ b/src/renderer/lib/hostedTeam.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect } from 'vitest'
+import {
+ reconnectDelayMs,
+ closedReasonMessage,
+ keyFingerprint,
+ HOSTED_APPROVAL_WAIT_MS,
+ stripIpcPrefix,
+ classifyJoinFailure,
+ joinStopMessage,
+ isReadOnlyRole,
+ hostedRoleLabel,
+ viewerBannerText,
+ pendingClosedNotice,
+ waitingForOwnerText,
+ RelayApprovalError,
+ mountFailureRetries,
+ mountFailureMessage
+} from './hostedTeam'
+
+describe('hosted team helpers', () => {
+ it('reconnect backoff 1/2/4/8/15 s then every 60 s', () => {
+ expect([0, 1, 2, 3, 4, 5, 9].map(reconnectDelayMs)).toEqual([1000, 2000, 4000, 8000, 15000, 60000, 60000])
+ })
+ it('names only reasons the host actually sent', () => {
+ expect(closedReasonMessage('removed')).toBe('Your access to this team was removed by an owner.')
+ expect(closedReasonMessage('denied')).toBe('An owner declined the request.')
+ expect(closedReasonMessage('expired')).toBe('No owner answered the request in time.')
+ expect(closedReasonMessage(undefined)).toBeNull()
+ })
+ it('fingerprint is short and stable', () => {
+ expect(keyFingerprint('AAAABBBBCCCCDDDD')).toBe('AAAA·BBBB')
+ })
+})
+
+describe('hosted join failures (R35 / R39)', () => {
+ const wrap = (m: string) => `Error invoking remote method 'relay:client:connect': Error: ${m}`
+
+ it('the approval wait is the host\'s own pending TTL', () => {
+ expect(HOSTED_APPROVAL_WAIT_MS).toBe(600_000)
+ })
+
+ it('strips Electron\'s prefix, and only that', () => {
+ expect(stripIpcPrefix(wrap('[E_JOIN_REFUSED] The file is bad.'))).toBe('[E_JOIN_REFUSED] The file is bad.')
+ expect(stripIpcPrefix('Error: plain')).toBe('plain')
+ expect(stripIpcPrefix('nothing to strip')).toBe('nothing to strip')
+ })
+
+ it('retries ONLY a network failure', () => {
+ expect(classifyJoinFailure(wrap('[E_JOIN_NETWORK] Could not reach the nodeterm service.'))).toMatchObject({ code: 'E_JOIN_NETWORK', retry: true, busy: false })
+ for (const code of ['E_JOIN_REVOKED', 'E_JOIN_REFUSED', 'E_JOIN_RATE', 'E_JOIN_BAD_CODE', 'E_JOIN_KEY_LOCKED', 'E_JOIN_BUSY']) {
+ expect(classifyJoinFailure(wrap(`[${code}] x`)).retry, code).toBe(false)
+ }
+ // A failure that carries no code (a dev build's refusal, a bug) is never retried unattended.
+ expect(classifyJoinFailure('Remote access is unavailable in development builds')).toMatchObject({ code: null, retry: false })
+ })
+
+ it('BUSY is its own fact: another attempt of ours is running, not a verdict about the team', () => {
+ expect(classifyJoinFailure(wrap('[E_JOIN_BUSY] Already joining this team.'))).toMatchObject({ code: 'E_JOIN_BUSY', busy: true, retry: false })
+ })
+
+ it('keeps the detail main wrote, without Electron\'s prefix or the code tag', () => {
+ const f = classifyJoinFailure(wrap('[E_JOIN_REFUSED] The hosted-team bookmarks file /x/relay-bookmarks.json cannot be read or safely rewritten; fix or remove it, then join again.'))
+ expect(f.detail).toBe('The hosted-team bookmarks file /x/relay-bookmarks.json cannot be read or safely rewritten; fix or remove it, then join again.')
+ })
+
+ it('says one sentence per code; a refusal shows main\'s own detail verbatim (items 13, 19)', () => {
+ const refused = classifyJoinFailure(wrap('[E_JOIN_REFUSED] The hosted-team bookmarks file /x/b.json cannot be read.'))
+ expect(joinStopMessage(refused, 'box')).toBe('Could not join box: The hosted-team bookmarks file /x/b.json cannot be read.')
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_REVOKED] x')), 'box')).toMatch(/^This device's access to box was revoked\. Remove the team and join again with a fresh invite code\.$/)
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_RATE] x')), 'box')).toBe('Too many join attempts for box today. Try again tomorrow.')
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_BAD_CODE] x')), 'box')).toBe('The invite code for box is not valid. Ask an owner for a fresh code.')
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_KEY_LOCKED] Unlock the keyring and reconnect.')), 'box')).toBe(
+ "Could not load this device's identity to join box: Unlock the keyring and reconnect."
+ )
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_NETWORK] Could not reach the nodeterm service.')), 'box')).toBe(
+ 'Could not reach box: Could not reach the nodeterm service.'
+ )
+ expect(joinStopMessage(classifyJoinFailure('Remote access is unavailable in development builds.'), 'box')).toBe(
+ 'Could not join box: Remote access is unavailable in development builds.'
+ )
+ // A team we know no name for.
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_RATE] x')), '')).toBe('Too many join attempts for the team today. Try again tomorrow.')
+ })
+
+ it('BUSY is never announced as a failure', () => {
+ expect(joinStopMessage(classifyJoinFailure(wrap('[E_JOIN_BUSY] x')), 'box')).toBeNull()
+ })
+})
+
+describe('hosted roles', () => {
+ it('only viewers and commenters are read-only; unknown is not a role this answers', () => {
+ expect(isReadOnlyRole('viewer')).toBe(true)
+ expect(isReadOnlyRole('commenter')).toBe(true)
+ expect(isReadOnlyRole('editor')).toBe(false)
+ expect(isReadOnlyRole('owner')).toBe(false)
+ expect(isReadOnlyRole(undefined)).toBe(false)
+ })
+
+ it('the banner is one English line naming the role and the team', () => {
+ expect(hostedRoleLabel('commenter')).toBe('Commenter')
+ expect(viewerBannerText('viewer', 'box')).toBe("You're a Viewer in box — terminals are read-only. Ask an owner for Editor access.")
+ expect(viewerBannerText('commenter', 'box')).toBe("You're a Commenter in box — terminals are read-only. Ask an owner for Editor access.")
+ })
+
+ it('another owner answering a request on screen is said; the rest close silently', () => {
+ expect(pendingClosedNotice('approved')).toBe('Another owner answered this request.')
+ expect(pendingClosedNotice('denied')).toBe('Another owner answered this request.')
+ expect(pendingClosedNotice('expired')).toBeNull()
+ expect(pendingClosedNotice('gone')).toBeNull()
+ expect(pendingClosedNotice('replaced')).toBeNull()
+ })
+
+ it('the joiner\'s wait names the team', () => {
+ expect(waitingForOwnerText('box')).toBe('Waiting for an owner of box to approve this device…')
+ expect(waitingForOwnerText('')).toBe('Waiting for an owner of the team to approve this device…')
+ })
+})
+
+describe('a hosted tab that never opened', () => {
+ it('retries only a drop the host did not explain, or a host that vanished right after approving', () => {
+ expect(mountFailureRetries(new RelayApprovalError('The relay connection closed before it was approved.'))).toBe(true)
+ expect(mountFailureRetries(Object.assign(new Error('The connection to the server was lost.'), { code: 'E_DISCONNECTED' }))).toBe(true)
+ for (const reason of ['denied', 'expired', 'removed'] as const) {
+ expect(mountFailureRetries(new RelayApprovalError('x', reason)), reason).toBe(false)
+ }
+ expect(mountFailureRetries(new Error('No owner answered the request in time.'))).toBe(false) // our own timeout
+ expect(mountFailureRetries(null)).toBe(false)
+ })
+
+ it('names the team and says what happened', () => {
+ expect(mountFailureMessage(new RelayApprovalError('An owner declined the request.', 'denied'), 'box')).toBe('Could not open box: An owner declined the request.')
+ expect(mountFailureMessage(new Error("Error invoking remote method 'x': Error: boom"), '')).toBe('Could not open the team: boom')
+ })
+})
diff --git a/src/renderer/lib/hostedTeam.ts b/src/renderer/lib/hostedTeam.ts
new file mode 100644
index 000000000..892e34e47
--- /dev/null
+++ b/src/renderer/lib/hostedTeam.ts
@@ -0,0 +1,145 @@
+// Pure helpers for a hosted team (a Server Edition hosting over the E2EE relay, joined by a
+// `nodeterm://join` code): the unattended reconnect's backoff and retry decision, the sentences a
+// refusal is told in, and the role wording. No React, no window — see docs/hosted-team-relay.md.
+import { joinErrorCode, joinErrorRetries, type JoinErrorCode } from '@shared/relay-join-errors'
+import type { HostedPendingClosedReason, HostedRole, RelayClosedReason } from '@shared/types'
+
+const BACKOFF = [1000, 2000, 4000, 8000, 15000]
+
+/** How long the `attempt`-th unattended retry waits: 1, 2, 4, 8, 15 s, then every 60 s. */
+export function reconnectDelayMs(attempt: number): number {
+ return attempt < BACKOFF.length ? BACKOFF[attempt] : 60_000
+}
+
+/** The sentence for a close the HOST explained (it refused this device), or null for a close it did
+ * not — only reasons the host actually sent are named, never a guessed cause. */
+export function closedReasonMessage(reason?: string): string | null {
+ switch (reason) {
+ case 'removed':
+ return 'Your access to this team was removed by an owner.'
+ case 'denied':
+ return 'An owner declined the request.'
+ case 'expired':
+ return 'No owner answered the request in time.'
+ default:
+ return null
+ }
+}
+
+/** A close that ended a relay connection before it was approved (session/relay-tab.ts). `reason` is
+ * the host's own, set only when a hosted team's host refused this device (an owner declined, nobody
+ * answered, it was removed); a Team Access close carries none and keeps its old message exactly. */
+export class RelayApprovalError extends Error {
+ constructor(message: string, readonly reason?: RelayClosedReason) {
+ super(message)
+ this.name = 'RelayApprovalError'
+ }
+}
+
+/** Could another attempt help a hosted tab that never opened? Only when the connection dropped
+ * WITHOUT the host saying why (a host restarting, a relay blip) or the host vanished right after
+ * approving. A refusal the host explained, a timeout, a declined SAS: no. */
+export function mountFailureRetries(err: unknown): boolean {
+ if (err instanceof RelayApprovalError) return err.reason === undefined
+ return (err as { code?: unknown } | null)?.code === 'E_DISCONNECTED'
+}
+
+/** The line a hosted tab that never opened is told in. */
+export function mountFailureMessage(err: unknown, teamLabel: string): string {
+ const message = err instanceof Error ? err.message : String(err)
+ return `Could not open ${teamLabel.trim() || 'the team'}: ${stripIpcPrefix(message)}`
+}
+
+/** A device key's short display form. */
+export function keyFingerprint(peerKeyB64: string): string {
+ return `${peerKeyB64.slice(0, 4)}·${peerKeyB64.slice(4, 8)}`
+}
+
+/** A hosted team's FIRST join waits for an owner as long as the host keeps the request pending
+ * (core hosted-service `PENDING_TTL_MS`); a pairing offer keeps the relay tab's own 60 s. */
+export const HOSTED_APPROVAL_WAIT_MS = 600_000
+
+/** Main's message without the prefix Electron wraps an `ipcMain.handle` rejection in. */
+export function stripIpcPrefix(message: string): string {
+ return String(message)
+ .replace(/^Error invoking remote method '[^']*': /, '')
+ .replace(/^Error: /, '')
+}
+
+/** What a failed hosted connect means for the unattended reconnect. */
+export interface JoinFailure {
+ /** The stable `[E_JOIN_…]` code, or null when the failure carried none. */
+ code: JoinErrorCode | null
+ /** Worth another unattended attempt: a network failure, and nothing else (R35). */
+ retry: boolean
+ /** Another attempt of OURS for the same team is running — never a verdict about the team. */
+ busy: boolean
+ /** Main's own sentence, without Electron's prefix or the code tag. */
+ detail: string
+}
+
+export function classifyJoinFailure(message: string): JoinFailure {
+ const code = joinErrorCode(String(message))
+ const detail = stripIpcPrefix(message).replace(/^\[E_JOIN_[A-Z_]+\]\s*/, '').trim()
+ return { code, retry: joinErrorRetries(code), busy: code === 'E_JOIN_BUSY', detail }
+}
+
+const teamName = (label: string): string => label.trim() || 'the team'
+
+/**
+ * The one sentence a stopped hosted connect is told in, or null when there is nothing to tell
+ * (BUSY: our other attempt for that team is the one that will answer). A refusal and a locked
+ * keyring carry main's own detail verbatim — it names the file or the fix; a stock sentence would
+ * hide both (items 13, 19).
+ */
+export function joinStopMessage(f: JoinFailure, teamLabel: string): string | null {
+ const team = teamName(teamLabel)
+ switch (f.code) {
+ case 'E_JOIN_BUSY':
+ return null
+ case 'E_JOIN_REVOKED':
+ return `This device's access to ${team} was revoked. Remove the team and join again with a fresh invite code.`
+ case 'E_JOIN_RATE':
+ return `Too many join attempts for ${team} today. Try again tomorrow.`
+ case 'E_JOIN_BAD_CODE':
+ return `The invite code for ${team} is not valid. Ask an owner for a fresh code.`
+ case 'E_JOIN_KEY_LOCKED':
+ return `Could not load this device's identity to join ${team}: ${f.detail}`
+ case 'E_JOIN_NETWORK':
+ return `Could not reach ${team}: ${f.detail}`
+ default:
+ return `Could not join ${team}: ${f.detail}`
+ }
+}
+
+const ROLE_LABEL: Readonly<Record<HostedRole, string>> = {
+ owner: 'Owner',
+ editor: 'Editor',
+ commenter: 'Commenter',
+ viewer: 'Viewer'
+}
+
+export function hostedRoleLabel(role: HostedRole): string {
+ return ROLE_LABEL[role] ?? 'Viewer'
+}
+
+/** Below Editor: the tab may watch (and a commenter may comment), never type, edit or save. */
+export function isReadOnlyRole(role: HostedRole | null | undefined): boolean {
+ return role === 'viewer' || role === 'commenter'
+}
+
+/** The slim banner over a read-only hosted canvas. */
+export function viewerBannerText(role: HostedRole, teamLabel: string): string {
+ return `You're a ${hostedRoleLabel(role)} in ${teamName(teamLabel)} — terminals are read-only. Ask an owner for Editor access.`
+}
+
+/** What an owner is told when a request they were looking at closed on its own: only an answer from
+ * ANOTHER owner is worth a line; an expiry, a drop or a newer request from the same device is not. */
+export function pendingClosedNotice(reason: HostedPendingClosedReason): string | null {
+ return reason === 'approved' || reason === 'denied' ? 'Another owner answered this request.' : null
+}
+
+/** The joiner's non-blocking wait for an owner (a first join can take up to ten minutes). */
+export function waitingForOwnerText(teamLabel: string): string {
+ return `Waiting for an owner of ${teamName(teamLabel)} to approve this device…`
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 99ba58e44..dfaf07566 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -224,6 +224,7 @@ import { useSshConn } from '../state/sshConn'
import { useWorktrees } from '../state/worktrees'
import { isRemoteSessionNode } from '@shared/worktree'
import { useSession, useActiveSessionPresence } from '../session/session'
+import { isHostedReadOnly, useHostedReadOnly } from '../state/hostedTeams'
import { isBrowserRuntime } from '../bridge/runtime'
import { agentLaunchOverride, COLLAPSED_HEIGHT, type CanvasNode } from '../state/workspace'
import { NodeColorSwatches } from '../components/NodeColorSwatches'
@@ -1212,6 +1213,9 @@ export function TerminalNode({
// namespaces (pty, fs) go through it; app-global ones (clipboard, shell) stay on the global.
const session = useSession()
const { api } = session
+ // A hosted team tab whose role is below Editor (false everywhere else): no "Restart in folder" —
+ // it recycles the session, which the host refuses for them.
+ const hostedReadOnly = useHostedReadOnly(session.id)
// The path dialect belongs to the core that owns this tab's filesystem, not necessarily this
// browser/window. Server Edition and relay tabs can be viewed from a different OS, so their
// core reports `process.platform` through the already-core-bound tmux status call. Keep it in a
@@ -2239,6 +2243,10 @@ export function TerminalNode({
// Appearance comes from ONE place, shared with the kanban card modal's viewer of this same
// session (`ModalTerminal`) — see `xtermOptionsFromSettings`.
const term = parked?.term ?? new Terminal(xtermOptionsFromSettings(s, isLiquidGlass(s.appTheme)))
+ // A hosted team's Viewer/Commenter watches and never types: keystrokes and pastes are not taken
+ // at all (the host refuses pty:write for them anyway). Set only for such a tab — every other
+ // session never touches the option. The role is known before the session exists (relay-tab).
+ if (isHostedReadOnly(session.id)) term.options.disableStdin = true
// Only on a FRESH instance: a parked terminal already carries the table, and the buffer it kept
// alive was measured with it — re-registering under a live buffer buys nothing.
if (!parked) activateUnicode11(term)
@@ -6132,13 +6140,15 @@ export function TerminalNode({
This terminal&apos;s folder was deleted (or replaced) — the shell&apos;s working
directory no longer exists.
</span>
- <button
- className="term-node__stalecwd-restart"
- onClick={restartInFolder}
- title={`End this shell and start a fresh one in ${(data.cwd as string) || 'the project folder'}. Anything still running in this terminal will end.`}
- >
- Restart in folder
- </button>
+ {!hostedReadOnly && (
+ <button
+ className="term-node__stalecwd-restart"
+ onClick={restartInFolder}
+ title={`End this shell and start a fresh one in ${(data.cwd as string) || 'the project folder'}. Anything still running in this terminal will end.`}
+ >
+ Restart in folder
+ </button>
+ )}
<button
className="term-node__stalecwd-dismiss"
onClick={dismissStaleCwd}
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index e23a07b6b..ddd1ca50b 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -17,6 +17,10 @@ import {
import { LocalTransport } from '../terminal/local-transport'
import type { NodeTerminalApi, Project, Workspace } from '@shared/types'
import type { RelayApiHandle } from '../bridge/relay-api'
+import { useHostedTeams } from '../state/hostedTeams'
+import { useHostedPending } from '../state/hostedPending'
+import { EMPTY_PENDING_QUEUE } from '../lib/hostedPendingQueue'
+import type { HostedPending, HostedSelf, RelayClosedReason } from '@shared/types'
/** A fake relayClient.onClosed sink: keeps the callback so the test can fire a socket drop. */
function fakeRelayClient() {
@@ -308,3 +312,146 @@ describe('tabClickAction (which behavior a tab click gets)', () => {
expect(tabClickAction(true, 'local')).toBe('ignore')
})
})
+
+// ── Hosted team tabs (joined by a `nodeterm://join` code) ─────────────────────────────────────────
+
+function fakeHostedApi(self: HostedSelf | Error, pulled: HostedPending[] = []) {
+ const log: string[] = []
+ const base = fakeBridgedApi()
+ const unPending = vi.fn()
+ const unClosed = vi.fn()
+ let pushPending: ((p: HostedPending) => void) | null = null
+ const api = {
+ ...base.api,
+ workspace: {
+ load: vi.fn(async () => {
+ log.push('workspace.load')
+ return { version: 2, activeProjectId: '', projects: [] }
+ })
+ },
+ hosted: {
+ self: vi.fn(async () => {
+ log.push('self')
+ if (self instanceof Error) throw self
+ return self
+ }),
+ pending: vi.fn(async () => {
+ log.push('pending')
+ return pulled
+ }),
+ inviteCode: vi.fn(),
+ approve: vi.fn(),
+ deny: vi.fn(),
+ onPeerPending: vi.fn((l: (p: HostedPending) => void) => {
+ log.push('sub:pending')
+ pushPending = l
+ return unPending
+ }),
+ onPendingClosed: vi.fn(() => {
+ log.push('sub:closed')
+ return unClosed
+ })
+ }
+ } as unknown as NodeTerminalApi
+ return { api, log, unPending, unClosed, push: (p: HostedPending) => pushPending?.(p) }
+}
+
+function reasonRelayClient() {
+ const cbs: Array<(reason?: RelayClosedReason) => void> = []
+ return {
+ onClosed: vi.fn((_id: string, cb: (reason?: RelayClosedReason) => void) => {
+ cbs.push(cb)
+ return () => {}
+ }),
+ fire: (reason?: RelayClosedReason) => cbs.forEach((cb) => cb(reason))
+ }
+}
+
+describe('openRelayTab — hosted team tabs', () => {
+ beforeEach(() => {
+ useHostedTeams.setState({ bySession: {} })
+ useHostedPending.setState({ queue: EMPTY_PENDING_QUEUE, notice: null })
+ })
+
+ it('learns its role BEFORE anything mounts, gates the api on it, and records it for the UI', async () => {
+ const h = fakeHostedApi({ role: 'viewer', label: 'laptop', hostLabel: 'box' })
+ const setHostedRole = vi.fn()
+ const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close: vi.fn(), setHostedRole }
+ const { deps } = makeDeps({ handle })
+ const tab = await openRelayTab('conn-h', 'from code', deps)
+ expect(h.log[0]).toBe('self')
+ expect(h.log.indexOf('self')).toBeLessThan(h.log.indexOf('workspace.load'))
+ expect(setHostedRole).toHaveBeenCalledWith('viewer')
+ expect(tab.hosted).toEqual({ role: 'viewer', teamLabel: 'box' })
+ expect(useHostedTeams.getState().bySession[tab.sessionId]).toEqual({ role: 'viewer', teamLabel: 'box' })
+ // A viewer is not an owner: it never subscribes to join requests, and never pulls them.
+ expect(h.log).not.toContain('pending')
+ expect(h.log).not.toContain('sub:pending')
+ })
+
+ it('an unreadable role is the LOWEST role (fail closed), and the tab still opens', async () => {
+ const h = fakeHostedApi(new Error('You are not a member of this team.'))
+ const setHostedRole = vi.fn()
+ const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close: vi.fn(), setHostedRole }
+ const tab = await openRelayTab('conn-h', 'box', makeDeps({ handle }).deps)
+ expect(setHostedRole).toHaveBeenCalledWith('viewer')
+ expect(tab.hosted).toEqual({ role: 'viewer', teamLabel: 'box' })
+ })
+
+ it('an OWNER subscribes first, then pulls the open requests into the queue (R25/R37)', async () => {
+ const waiting: HostedPending = { pendingId: 'p1', sas: '123 456', peerKeyB64: 'KEY', since: 1 }
+ const h = fakeHostedApi({ role: 'owner', label: 'me', hostLabel: 'box' }, [waiting])
+ const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close: vi.fn(), setHostedRole: vi.fn() }
+ const tab = await openRelayTab('conn-h', 'box', makeDeps({ handle }).deps)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(h.log.indexOf('sub:pending')).toBeLessThan(h.log.indexOf('pending'))
+ expect(useHostedPending.getState().queue.items.map((i) => i.pending.pendingId)).toEqual(['p1'])
+ expect(useHostedPending.getState().queue.items[0]).toMatchObject({ projectId: tab.projectId, teamLabel: 'box' })
+ // A second request is queued, not dropped.
+ h.push({ pendingId: 'p2', sas: '9', peerKeyB64: 'K2', since: 2 })
+ expect(useHostedPending.getState().queue.items).toHaveLength(2)
+ // The tab dropping takes its requests (and its subscriptions) with it.
+ handleRelayDrop(tab, { setProjectUnavailable: () => {} })
+ expect(h.unPending).toHaveBeenCalled()
+ expect(h.unClosed).toHaveBeenCalled()
+ expect(useHostedPending.getState().queue.items).toEqual([])
+ })
+
+ it('a Team Access relay tab (no hosted api) takes the old path: no role, no store entry', async () => {
+ const { api } = fakeBridgedApi()
+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }
+ const tab = await openRelayTab('conn-legacy', 'Mac', makeDeps({ handle }).deps)
+ expect(tab.hosted).toBeUndefined()
+ expect(useHostedTeams.getState().bySession).toEqual({})
+ expect(useHostedPending.getState().queue).toBe(EMPTY_PENDING_QUEUE)
+ })
+
+ it('a hosted refusal before approval rejects in the host\'s words and carries the reason', async () => {
+ const h = fakeHostedApi({ role: 'viewer', label: '', hostLabel: 'box' })
+ const handle: RelayApiHandle = { api: h.api, ready: () => new Promise<void>(() => {}), close: vi.fn(), setHostedRole: vi.fn() }
+ const relayClient = reasonRelayClient()
+ const bootstrap = openRelayTab('conn-h', 'box', makeDeps({ handle, relayClient }).deps)
+ relayClient.fire('denied')
+ const err = await bootstrap.catch((e: Error & { reason?: string }) => e)
+ expect((err as Error).message).toBe('An owner declined the request.')
+ expect((err as { reason?: string }).reason).toBe('denied')
+ })
+
+ it('a legacy close before approval keeps its old message exactly', async () => {
+ const { api } = fakeBridgedApi()
+ const handle: RelayApiHandle = { api, ready: () => new Promise<void>(() => {}), close: vi.fn() }
+ const relayClient = reasonRelayClient()
+ const bootstrap = openRelayTab('conn-l', 'Mac', makeDeps({ handle, relayClient }).deps)
+ relayClient.fire(undefined)
+ await expect(bootstrap).rejects.toThrow(/^The relay connection closed before it was approved\.$/)
+ })
+
+ it('a background reconnect binds the tab without switching to it (activate: false)', async () => {
+ const h = fakeHostedApi({ role: 'editor', label: '', hostLabel: 'box' })
+ const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close: vi.fn(), setHostedRole: vi.fn() }
+ const { deps, setActiveProject } = makeDeps({ handle })
+ const tab = await openRelayTab('conn-h', 'box', { ...deps, activate: false })
+ expect(setActiveProject).not.toHaveBeenCalled()
+ expect(sessionForProject(tab.projectId).id).toBe(tab.sessionId) // still bound
+ })
+})
diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.ts
index 8968ed8b6..1524c63a0 100644
--- a/src/renderer/session/relay-tab.ts
+++ b/src/renderer/session/relay-tab.ts
@@ -14,8 +14,12 @@
// forever — a dead tab that never errors. So we RACE `ready()` against the connection's real
// close signal (relayClient.onClosed) plus a timeout backstop, and reject on either.
-import type { Project, RelayClientApi } from '@shared/types'
+import type { HostedRole, HostedSessionApi, Project, RelayClientApi } from '@shared/types'
import { buildRelayApi, type RelayApiHandle } from '../bridge/relay-api'
+import { closedReasonMessage, RelayApprovalError } from '../lib/hostedTeam'
+import { attachHostedOwner } from '../lib/hostedOwner'
+import { useHostedTeams, type HostedTeamInfo } from '../state/hostedTeams'
+import { hostedPendingSink } from '../state/hostedPending'
import {
createSession,
bindProjectToSession,
@@ -45,17 +49,42 @@ export interface RelayTabDeps {
setActiveProject: (projectId: string) => void
/** TEST SEAM: build the relay api handle. Production omits it → `buildRelayApi`. */
buildApi?: (connectionId: string) => RelayApiHandle
- /** TEST SEAM: approval-timeout backstop (default `APPROVAL_TIMEOUT_MS`). */
+ /** Approval-timeout backstop (default `APPROVAL_TIMEOUT_MS`). A hosted team's first join passes
+ * the host's own pending TTL: an owner has ten minutes to answer, not one. */
timeoutMs?: number
+ /** The connection was made from a hosted team's join code: build the hosted api (its `hosted`
+ * verbs and role gate). Absent = a Team Access relay tab, byte-identical to before. */
+ hosted?: boolean
+ /** Switch to the tab once it is live (default true). A reconnect nobody clicked (boot, a dropped
+ * tab coming back) binds its tab without taking the screen from whatever the user is on. */
+ activate?: boolean
}
export interface RelayTab {
sessionId: string
projectId: string
+ /** A hosted team's tab: this device's role there and the team's name. Absent otherwise. */
+ hosted?: HostedTeamInfo
/** Tear the tab's session down (runs the held presence teardown + relay socket close, once). */
dispose(): void
}
+const ROLES: readonly HostedRole[] = ['owner', 'editor', 'commenter', 'viewer']
+
+/**
+ * Ask a hosted host which role this device has, and publish it to the api's role gate BEFORE
+ * anything mounts (nothing but this request has been sent yet). An answer that cannot be read is the
+ * LOWEST role: the host enforces the real one either way, and the direction a wrong guess must err
+ * in is "shows less", never "sends what will be refused".
+ */
+async function learnHostedRole(hosted: HostedSessionApi, handle: RelayApiHandle, label: string): Promise<HostedTeamInfo> {
+ const self = await hosted.self().catch(() => null)
+ const role: HostedRole = self && ROLES.includes(self.role) ? self.role : 'viewer'
+ handle.setHostedRole?.(role)
+ const hostLabel = self && typeof self.hostLabel === 'string' ? self.hostLabel.trim() : ''
+ return { role, teamLabel: hostLabel || label }
+}
+
/**
* Bootstrap a relay project tab. Resolves once the connection is mutually approved and the tab is
* live; REJECTS (never hangs) if the socket drops or times out before approval.
@@ -65,18 +94,23 @@ export async function openRelayTab(
label: string,
deps: RelayTabDeps
): Promise<RelayTab> {
- const build = deps.buildApi ?? buildRelayApi
+ const build = deps.buildApi ?? ((id: string) => buildRelayApi(id, undefined, deps.hosted ? { hosted: true } : undefined))
// Built BEFORE we await ready() so the one-shot onApproved listener is registered in time.
const handle = build(connectionId)
+ let hostedInfo: HostedTeamInfo | undefined
try {
await raceApproval(handle, connectionId, deps)
+ // A hosted team's tab learns its role before its session exists, so nothing a component sends
+ // on mount is sent under the wrong one (see bridge/hosted-gate.ts).
+ if (handle.api.hosted) hostedInfo = await learnHostedRole(handle.api.hosted, handle, label)
} catch (err) {
handle.close() // tear the dead/stuck relay socket down before surfacing the failure
throw err
}
const session = createSession('relay', handle.api, label)
+ if (hostedInfo) useHostedTeams.getState().set(session.id, hostedInfo)
// The teardowns the tab owes on disconnect (obligation 1): the presence subscription this session
// just opened, and the relay socket. Both run exactly once in disposeSession.
holdSessionTeardown(session.id, getSessionStores(session.id).presence.connect())
@@ -100,12 +134,23 @@ export async function openRelayTab(
? deps.adoptProject({ ...hostProject, remote: true }).id
: deps.addProject(label).id
bindProjectToSession(projectId, session.id)
- setActiveSession(session.id)
- deps.setActiveProject(projectId)
+ if (deps.activate !== false) {
+ setActiveSession(session.id)
+ deps.setActiveProject(projectId)
+ }
+ // An OWNER answers the devices asking to join. Its subscription (and its queued requests) go
+ // with the session: a drop or a close runs this teardown, a reconnect subscribes and pulls anew.
+ if (hostedInfo?.role === 'owner' && handle.api.hosted) {
+ holdSessionTeardown(
+ session.id,
+ attachHostedOwner(handle.api.hosted, { projectId, teamLabel: hostedInfo.teamLabel }, hostedPendingSink)
+ )
+ }
return {
sessionId: session.id,
projectId,
+ ...(hostedInfo ? { hosted: hostedInfo } : {}),
dispose: () => disposeSession(session.id),
}
} catch (err) {
@@ -197,11 +242,29 @@ function raceApproval(
if (timer) clearTimeout(timer)
fn()
}
- unClose = deps.relayClient.onClosed(connectionId, () =>
- finish(() => reject(new Error('The relay connection closed before it was approved.')))
+ // A hosted host may say WHY before it closes (an owner declined, nobody answered); a close
+ // without a reason keeps the old sentence exactly.
+ unClose = deps.relayClient.onClosed(connectionId, (reason) =>
+ finish(() =>
+ reject(
+ new RelayApprovalError(
+ closedReasonMessage(reason) ?? 'The relay connection closed before it was approved.',
+ reason
+ )
+ )
+ )
)
timer = setTimeout(
- () => finish(() => reject(new Error('Timed out waiting for the host to approve.'))),
+ () =>
+ finish(() =>
+ reject(
+ new Error(
+ handle.api.hosted
+ ? (closedReasonMessage('expired') as string)
+ : 'Timed out waiting for the host to approve.'
+ )
+ )
+ ),
deps.timeoutMs ?? APPROVAL_TIMEOUT_MS
)
handle.ready().then(
diff --git a/src/renderer/state/hostedPending.ts b/src/renderer/state/hostedPending.ts
new file mode 100644
index 000000000..1b06e7fd1
--- /dev/null
+++ b/src/renderer/state/hostedPending.ts
@@ -0,0 +1,53 @@
+import { create } from 'zustand'
+import type { HostedPendingClosedReason } from '@shared/types'
+import {
+ EMPTY_PENDING_QUEUE,
+ addRequest,
+ closeRequest,
+ dropProjectRequests,
+ settleRequest,
+ type PendingQueue,
+ type QueuedRequest
+} from '../lib/hostedPendingQueue'
+import type { OwnerQueueSink } from '../lib/hostedOwner'
+
+/**
+ * The devices waiting for THIS owner's answer, across every hosted tab where this device is an
+ * owner (the rules are the pure `lib/hostedPendingQueue.ts`). The approval dialog shows the head.
+ * `notice` is the latest line worth telling the owner ("Another owner answered this request"),
+ * bumped by `seq` so the same sentence twice is still two notices. Transient.
+ */
+interface HostedPendingStore {
+ queue: PendingQueue
+ notice: { seq: number; text: string } | null
+ add: (item: QueuedRequest) => void
+ close: (pendingId: string, reason: HostedPendingClosedReason) => void
+ settle: (pendingId: string) => void
+ drop: (projectId: string) => void
+}
+
+export const useHostedPending = create<HostedPendingStore>((set) => ({
+ queue: EMPTY_PENDING_QUEUE,
+ notice: null,
+ add: (item) => set((s) => {
+ const queue = addRequest(s.queue, item)
+ return queue === s.queue ? s : { queue }
+ }),
+ close: (pendingId, reason) =>
+ set((s) => {
+ const r = closeRequest(s.queue, pendingId, reason)
+ return r.notice ? { queue: r.queue, notice: { seq: (s.notice?.seq ?? 0) + 1, text: r.notice } } : { queue: r.queue }
+ }),
+ settle: (pendingId) => set((s) => ({ queue: settleRequest(s.queue, pendingId) })),
+ drop: (projectId) => set((s) => {
+ const queue = dropProjectRequests(s.queue, projectId)
+ return queue === s.queue ? s : { queue }
+ })
+}))
+
+/** The store as the owner subscription's sink. */
+export const hostedPendingSink: OwnerQueueSink = {
+ add: (item) => useHostedPending.getState().add(item),
+ close: (pendingId, reason) => useHostedPending.getState().close(pendingId, reason),
+ drop: (projectId) => useHostedPending.getState().drop(projectId)
+}
diff --git a/src/renderer/state/hostedTeams.ts b/src/renderer/state/hostedTeams.ts
new file mode 100644
index 000000000..f0f7d433c
--- /dev/null
+++ b/src/renderer/state/hostedTeams.ts
@@ -0,0 +1,55 @@
+import { create } from 'zustand'
+import type { HostedRole } from '@shared/types'
+import { isReadOnlyRole } from '../lib/hostedTeam'
+
+/**
+ * What this device is on each hosted team it has a relay tab to, keyed by SESSION id: the role the
+ * host answered (`relay:hosted:self`) and the team's name. Set by `openRelayTab` before the tab's
+ * session has anything mounted, read by the surfaces that mirror the role — the viewer banner, the
+ * read-only canvas, the read-only terminal, the owner-only palette entry. Absent = not a hosted
+ * tab (local, Server Edition, a Team Access relay tab): every reader then takes its old path.
+ *
+ * TRANSIENT: a role is a fact about one connection to a host that re-decides it on every message;
+ * the next connection asks again. Nothing here is persisted. The UI only mirrors the role — the
+ * host enforces it (src/core/relay/access-policy.ts).
+ */
+export interface HostedTeamInfo {
+ role: HostedRole
+ /** The host's own label (from `self()`), else the join code's. */
+ teamLabel: string
+}
+
+interface HostedTeamsStore {
+ bySession: Record<string, HostedTeamInfo | undefined>
+ set: (sessionId: string, info: HostedTeamInfo) => void
+ forget: (sessionId: string) => void
+}
+
+export const useHostedTeams = create<HostedTeamsStore>((set) => ({
+ bySession: {},
+ set: (sessionId, info) => set((s) => ({ bySession: { ...s.bySession, [sessionId]: info } })),
+ forget: (sessionId) =>
+ set((s) => {
+ if (!s.bySession[sessionId]) return s
+ const { [sessionId]: _gone, ...rest } = s.bySession
+ return { bySession: rest }
+ })
+}))
+
+/** This session's hosted team, or undefined for every non-hosted session. */
+export function hostedInfoFor(sessionId: string): HostedTeamInfo | undefined {
+ return useHostedTeams.getState().bySession[sessionId]
+}
+
+/** A hosted tab whose role is below Editor. False for every non-hosted session. */
+export function isHostedReadOnly(sessionId: string): boolean {
+ return isReadOnlyRole(hostedInfoFor(sessionId)?.role)
+}
+
+export function useHostedInfo(sessionId: string): HostedTeamInfo | undefined {
+ return useHostedTeams((s) => s.bySession[sessionId])
+}
+
+export function useHostedReadOnly(sessionId: string): boolean {
+ return useHostedTeams((s) => isReadOnlyRole(s.bySession[sessionId]?.role))
+}
diff --git a/src/shared/hosted-access.test.ts b/src/shared/hosted-access.test.ts
new file mode 100644
index 000000000..9b1c05292
--- /dev/null
+++ b/src/shared/hosted-access.test.ts
@@ -0,0 +1,63 @@
+// src/shared/hosted-access.test.ts
+import { describe, it, expect } from 'vitest'
+import { IPC } from './ipc'
+import { hostedMayCall, hostedRoleRefusal, HOSTED_VIEW_METHODS, HOSTED_COMMENT_METHODS } from './hosted-access'
+
+describe('hosted access mirror (the client side of the host policy)', () => {
+ it('editors and owners may call anything', () => {
+ for (const role of ['owner', 'editor'] as const) {
+ expect(hostedMayCall(role, IPC.ptyWrite)).toBe(true)
+ expect(hostedMayCall(role, IPC.workspaceSave)).toBe(true)
+ expect(hostedMayCall(role, IPC.canvasMut)).toBe(true)
+ }
+ })
+
+ it('a viewer may call only what the host lets a viewer call', () => {
+ expect(hostedMayCall('viewer', IPC.workspaceLoad)).toBe(true)
+ expect(hostedMayCall('viewer', IPC.ptyCreate)).toBe(true)
+ expect(hostedMayCall('viewer', IPC.presenceHello)).toBe(true)
+ for (const m of [IPC.workspaceSave, IPC.canvasMut, IPC.ptyWrite, IPC.ptyRecycle, IPC.claudeCliCaps, IPC.gitWorktreeList, IPC.presenceChat, IPC.boardLogAppend]) {
+ expect(hostedMayCall('viewer', m), m).toBe(false)
+ }
+ })
+
+ it('a commenter may also chat and comment, and nothing more', () => {
+ expect(hostedMayCall('commenter', IPC.presenceChat)).toBe(true)
+ expect(hostedMayCall('commenter', IPC.boardLogAppend)).toBe(true)
+ expect(hostedMayCall('commenter', IPC.workspaceLoad)).toBe(true)
+ expect(hostedMayCall('commenter', IPC.ptyWrite)).toBe(false)
+ expect(hostedMayCall('commenter', IPC.canvasMut)).toBe(false)
+ })
+
+ it('an unknown role is the lowest one', () => {
+ expect(hostedMayCall(null, IPC.workspaceLoad)).toBe(true)
+ expect(hostedMayCall(null, IPC.ptyWrite)).toBe(false)
+ expect(hostedMayCall('admin' as never, IPC.ptyWrite)).toBe(false)
+ })
+
+ it('the hosted team verbs always go through: the host judges them itself', () => {
+ for (const m of [IPC.relayHostedSelf, IPC.relayHostedPending, IPC.relayHostedApprove, IPC.relayHostedDeny, IPC.relayHostedInviteCode]) {
+ expect(hostedMayCall('viewer', m), m).toBe(true)
+ }
+ })
+
+ it('own keys only: a method named like an Object.prototype member is not allowed', () => {
+ expect(hostedMayCall('viewer', 'constructor')).toBe(false)
+ expect(hostedMayCall('viewer', '__proto__')).toBe(false)
+ })
+
+ it('the lists name real channels, once each', () => {
+ const ipc = new Set((Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string'))
+ for (const m of [...HOSTED_VIEW_METHODS, ...HOSTED_COMMENT_METHODS]) expect(ipc.has(m), m).toBe(true)
+ expect(new Set(HOSTED_VIEW_METHODS).size).toBe(HOSTED_VIEW_METHODS.length)
+ for (const m of HOSTED_COMMENT_METHODS) expect(HOSTED_VIEW_METHODS.includes(m), m).toBe(false)
+ })
+
+ it('refuses in the host\'s own words, with its code', () => {
+ const e = hostedRoleRefusal('viewer')
+ expect(e.message).toBe("Viewers can't do that here. Ask an owner for Editor access.")
+ expect(e.code).toBe('E_ROLE')
+ expect(hostedRoleRefusal('commenter').message).toMatch(/^Commenters can't/)
+ expect(hostedRoleRefusal(null).message).toMatch(/^Viewers can't/)
+ })
+})
diff --git a/src/shared/hosted-access.ts b/src/shared/hosted-access.ts
new file mode 100644
index 000000000..ea0e96757
--- /dev/null
+++ b/src/shared/hosted-access.ts
@@ -0,0 +1,67 @@
+// The CLIENT side of a hosted team's role policy: which relay calls a Viewer or Commenter may send.
+//
+// The host decides (src/core/relay/access-policy.ts `VIEW` / `COMMENT`, argument checks included);
+// this is only its mirror, so a read-only teammate's tab does not send the host calls it will refuse
+// anyway — the autosave, the canvas edits, the typing, the mount-time probes. A refusal the host
+// would have sent comes back from here instead, in the host's words and with its code, so every
+// caller behaves exactly as it would have. The access-policy guard test pins these two lists to the
+// host's tables: a channel the host opens to viewers and this file does not name would silently
+// disappear from a viewer's tab. See docs/hosted-team-relay.md.
+import { IPC } from './ipc'
+import type { HostedRole } from './types'
+
+/** Every channel the host serves a Viewer (its `VIEW` table's keys). */
+export const HOSTED_VIEW_METHODS: readonly string[] = Object.freeze([
+ IPC.workspaceLoad,
+ IPC.ptyCreate,
+ IPC.ptyResize,
+ IPC.ptyFlow,
+ IPC.ptyKill,
+ IPC.ptyCapture,
+ IPC.ptyReadScrollback,
+ IPC.ptyPaneCommand,
+ IPC.ptyTmuxStatus,
+ IPC.fsList,
+ IPC.fsRead,
+ IPC.fsReadBinary,
+ IPC.fsExists,
+ IPC.gitStatus,
+ IPC.gitRepoRoot,
+ IPC.gitDiff,
+ IPC.gitShowFile,
+ IPC.gitHistory,
+ IPC.agentSubagentSnapshot,
+ IPC.presenceHello,
+ IPC.presenceCursor,
+ IPC.presenceFocus,
+ IPC.presenceProject,
+ IPC.boardLogRead,
+ IPC.boardLogSubscribe,
+ IPC.boardLogUnsubscribe
+])
+
+/** What a Commenter may call on top of a Viewer's (its `COMMENT` table's keys). */
+export const HOSTED_COMMENT_METHODS: readonly string[] = Object.freeze([IPC.presenceChat, IPC.boardLogAppend])
+
+const VIEW = new Set(HOSTED_VIEW_METHODS)
+const COMMENT = new Set(HOSTED_COMMENT_METHODS)
+
+/** The hosted team verbs: intercepted and judged by the host itself (owner-only ones included). */
+const HOSTED_PREFIX = 'relay:hosted:'
+
+/** May a teammate with `role` send `method`? `null` (not known yet) is the lowest role. */
+export function hostedMayCall(role: HostedRole | null, method: string): boolean {
+ if (typeof method !== 'string') return false
+ if (method.startsWith(HOSTED_PREFIX)) return true
+ if (role === 'owner' || role === 'editor') return true
+ if (VIEW.has(method)) return true
+ return role === 'commenter' && COMMENT.has(method)
+}
+
+const ROLE_NAME: Readonly<Record<string, string>> = { owner: 'Owners', editor: 'Editors', commenter: 'Commenters', viewer: 'Viewers' }
+
+/** The refusal the host would have answered with (relay-host's `E_ROLE` + access-policy's words). */
+export function hostedRoleRefusal(role: HostedRole | null): Error & { code: string } {
+ const name = role && Object.hasOwn(ROLE_NAME, role) ? ROLE_NAME[role] : ROLE_NAME.viewer
+ return Object.assign(new Error(`${name} can't do that here. Ask an owner for Editor access.`), { code: 'E_ROLE' })
+}
diff --git a/src/shared/relay-join-code.test.ts b/src/shared/relay-join-code.test.ts
new file mode 100644
index 000000000..6dd14d660
--- /dev/null
+++ b/src/shared/relay-join-code.test.ts
@@ -0,0 +1,33 @@
+// src/shared/relay-join-code.test.ts
+import { describe, it, expect } from 'vitest'
+import { JOIN_CODE_PREFIX, isJoinCode, peekJoinCode } from './relay-join-code'
+
+/** base64url of a JSON object, the way the core encoder writes a join code. */
+const encode = (o: unknown): string =>
+ JOIN_CODE_PREFIX + Buffer.from(JSON.stringify(o), 'utf-8').toString('base64url')
+
+describe('join code (renderer-safe half)', () => {
+ it('recognizes the prefix, trimmed, and nothing else', () => {
+ expect(isJoinCode(` ${JOIN_CODE_PREFIX}abc \n`)).toBe(true)
+ expect(isJoinCode('nodeterm://pair?code=abc')).toBe(false)
+ expect(isJoinCode('')).toBe(false)
+ expect(isJoinCode(undefined as unknown as string)).toBe(false)
+ })
+
+ it('peeks the team id and label a code CLAIMS, without trusting them', () => {
+ expect(peekJoinCode(encode({ v: 1, hostId: 'H1', label: 'box', hostPublicKeyB64: 'k' }))).toEqual({ hostId: 'H1', label: 'box' })
+ // A code whose label is missing still names its team.
+ expect(peekJoinCode(encode({ v: 1, hostId: 'H1' }))).toEqual({ hostId: 'H1', label: '' })
+ })
+
+ it('answers null for anything it cannot read, and never throws', () => {
+ expect(peekJoinCode('nodeterm://pair?code=abc')).toBeNull()
+ expect(peekJoinCode(`${JOIN_CODE_PREFIX}%%%`)).toBeNull()
+ expect(peekJoinCode(`${JOIN_CODE_PREFIX}`)).toBeNull()
+ expect(peekJoinCode(encode({ v: 1 }))).toBeNull()
+ expect(peekJoinCode(encode({ v: 1, hostId: 7 }))).toBeNull()
+ expect(peekJoinCode(encode({ v: 1, hostId: 'x'.repeat(65) }))).toBeNull()
+ expect(peekJoinCode(encode(['H1']))).toBeNull()
+ expect(peekJoinCode(encode(null))).toBeNull()
+ })
+})
diff --git a/src/shared/relay-join-code.ts b/src/shared/relay-join-code.ts
new file mode 100644
index 000000000..438fd718d
--- /dev/null
+++ b/src/shared/relay-join-code.ts
@@ -0,0 +1,38 @@
+// The renderer-safe half of a hosted team's join code (`nodeterm://join?code=<base64url(JSON)>`).
+//
+// The real codec lives in core (src/core/relay/join-code.ts): it VERIFIES a code (the hostId must
+// derive from the host key it carries, the relay must be one we will dial) and needs node's crypto
+// to do so. The renderer cannot import it, but it still has to tell a join code from a pairing offer
+// and to know which team a pasted code names, so it can keep ONE attempt per team (a second attempt
+// would open a second pending request on the host, which replaces the first). The prefix lives here
+// once and core imports it.
+//
+// `peekJoinCode` trusts nothing: it reads what a code CLAIMS, for display and for de-duplication
+// only. Every decision that matters is made in main, on the verified decode.
+
+export const JOIN_CODE_PREFIX = 'nodeterm://join?code='
+
+/** Is this a hosted team's join code (as opposed to a pairing offer)? */
+export function isJoinCode(s: string): boolean {
+ return typeof s === 'string' && s.trim().startsWith(JOIN_CODE_PREFIX)
+}
+
+/** The same cap core's decoder puts on a hostId. */
+const HOST_ID_MAX = 64
+
+/** The team a join code names, UNVERIFIED — or null when it does not read as one. Never throws. */
+export function peekJoinCode(s: string): { hostId: string; label: string } | null {
+ if (!isJoinCode(s)) return null
+ try {
+ const b64 = s.trim().slice(JOIN_CODE_PREFIX.length).replace(/-/g, '+').replace(/_/g, '/')
+ if (!b64) return null
+ const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4))
+ const o = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as unknown
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return null
+ const r = o as Record<string, unknown>
+ if (typeof r.hostId !== 'string' || !r.hostId || r.hostId.length > HOST_ID_MAX) return null
+ return { hostId: r.hostId, label: typeof r.label === 'string' ? r.label : '' }
+ } catch {
+ return null
+ }
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 2edeaebf6..b13f74e3f 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -3535,10 +3535,55 @@ export interface RelayHostedApi {
/** The bookmarks, never their device tokens. `approved` = both humans approved this device on
* that host, so a reconnect needs no SAS comparison on this side. */
bookmarks(): Promise<Array<{ hostId: string; label: string; approved: boolean; code: string }>>
- /** Forget a bookmark (its device token and its approval). */
+ /** Forget a bookmark (its device token and its approval). Rejects while a join for that team is
+ * still minting or joining: that join would write the bookmark straight back. */
removeBookmark(hostId: string): Promise<void>
}
+/** A hosted team member's role (the core team store's `TeamRole`). */
+export type HostedRole = 'owner' | 'editor' | 'commenter' | 'viewer'
+
+/** A device waiting for an owner to approve it (core hosted-service's `HostedPending`). */
+export interface HostedPending {
+ pendingId: string
+ /** The code both people compare out of band. */
+ sas: string
+ peerKeyB64: string
+ /** Host wall-clock ms the request arrived. */
+ since: number
+}
+
+/** Why a pending request stopped being pending. `approved` / `denied` may be ANOTHER owner's answer;
+ * `replaced` = the same device asked again (its newer request arrives on its own). */
+export type HostedPendingClosedReason = 'approved' | 'denied' | 'expired' | 'replaced' | 'gone'
+
+/** What `relay:hosted:self` answers: this device's role, its label on the team, the host's label. */
+export interface HostedSelf {
+ role: HostedRole
+ label: string
+ hostLabel: string
+}
+
+/**
+ * The hosted team verbs of ONE relay session. Only a relay tab joined by a `nodeterm://join` code has
+ * it (`NodeTerminalApi.hosted`); a local session, a Server Edition browser and a Team Access relay
+ * tab (desktop to desktop) never do. The host answers every one of these itself and judges the
+ * caller's role: `self` is open to any member, the rest are owner-only.
+ */
+export interface HostedSessionApi {
+ self(): Promise<HostedSelf>
+ /** The requests still waiting (owner-only). Pulled once on open; the events below are deltas. */
+ pending(): Promise<HostedPending[]>
+ /** The team's join code, or null when the host has none to hand out. */
+ inviteCode(): Promise<string | null>
+ /** Admit a waiting device with `role`. False when it is gone or another owner answered first. */
+ approve(pendingId: string, role: HostedRole): Promise<boolean>
+ /** Refuse a waiting device. False when it is already gone. */
+ deny(pendingId: string): Promise<boolean>
+ onPeerPending(listener: (p: HostedPending) => void): () => void
+ onPendingClosed(listener: (p: { pendingId: string; reason: HostedPendingClosedReason }) => void): () => void
+}
+
/** A paired device as exposed to the renderer — the bearer token is never included. */
export interface PairedDevice {
id: string
@@ -3736,6 +3781,9 @@ export interface NodeTerminalApi {
relayHost: RelayHostApi
relayClient: RelayClientApi
relayHosted: RelayHostedApi
+ /** The hosted team verbs of THIS session's host — present only on a relay tab joined by a hosted
+ * team's join code; absent everywhere else (local, Server Edition, Team Access relay tabs). */
+ hosted?: HostedSessionApi
handoff: HandoffApi
pairing: PairingApi
presence: PresenceApi