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.

Merge origin/main into feat/hosted-team-relay

review2baf4f7b344e
diff --cc src/core/relay/access-policy.ts
index f7c67cfee,000000000..17e73cc74
mode 100644,000000..100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@@ -1,468 -1,0 +1,478 @@@
+// Hosted-relay roles are a SECURITY BOUNDARY, enforced here, at the one choke point every relay
+// peer message crosses (relay-host.ts hooks). The UI only mirrors it.
+//
+// Two rules the whole file rests on:
+// - DENY BY DEFAULT for non-editors, in BOTH directions. Inbound, a method is reachable by a
+// Viewer/Commenter only if it is in VIEW/COMMENT below. Outbound, an event reaches them only if
+// it is in VIEW_EVENTS / VIEW_EVENT_PREFIXES: the core BROADCASTS to every attached client (the
+// debug log stream, whole project documents, account usage…), so an allow-by-default filter
+// would hand a viewer everything nobody remembered to list. A channel added tomorrow is
+// Editor-only, in and out, until someone decides otherwise.
+// - "READ" IS NOT "SAFE": relay peers were fully trusted, so fs:read is not jailed, pty:create on
+// any persistKey joins OR SPAWNS (and its options can name an ssh route), and two git "reads"
+// are not reads at all — `git diff --no-index` diffs any file on the host, and a `git show` ref
+// that starts with `-` is parsed as an option (`--output=<file>` WRITES a file). Every VIEW entry
+// therefore carries its own argument check.
+//
+// Editors and owners pass untouched: Editor is shell access by definition, so gating them would be
+// theatre.
+import path from 'node:path'
+import { IPC } from '../../shared/ipc'
+import type { TeamRole } from './team-store'
+import type { AccessDecision } from './relay-host'
+import type { UiSink } from '../ui-sink-registry'
+
+export interface AccessContext {
+ role: TeamRole
+ sharedProjects: ReadonlySet<string>
+ /** The project a node belongs to, from the persisted canvases. */
+ projectOfNode(nodeId: string): string | undefined
+ /** The LOCAL cwds of the shared projects. */
+ projectCwds(): string[]
+ /** `fs.realpath`; null = the path does not resolve. */
+ realpath(p: string): string | null
+}
+
+type Check = (args: unknown[], ctx: AccessContext) => AccessDecision
+const OK: AccessDecision = { allow: true }
+const no = (message: string): AccessDecision => ({ allow: false, message })
+const pass: Check = () => OK
+
+const isEditor = (role: unknown): boolean => role === 'owner' || role === 'editor'
+
+const sharedProject = (id: unknown, ctx: AccessContext): boolean =>
+ typeof id === 'string' && ctx.sharedProjects.has(id)
+
+const sharedNode = (id: unknown, ctx: AccessContext): boolean => {
+ if (typeof id !== 'string') return false
+ const project = ctx.projectOfNode(id)
+ return project !== undefined && ctx.sharedProjects.has(project)
+}
+
+/** One property of an object payload (our own fixed key names only), else undefined. */
+const field = (v: unknown, key: string): unknown =>
+ v !== null && typeof v === 'object' ? (v as Record<string, unknown>)[key] : undefined
+
+/**
+ * The shared project roots as REAL paths. A project opened through a symlinked folder has a cwd that
+ * never equals its files' realpaths, so the cwd is realpathed too (and kept as written when it does
+ * not resolve). A relative or empty cwd is never a root: `'' + sep` is a prefix of every path.
+ */
+function sharedRoots(ctx: AccessContext): string[] {
+ const roots: string[] = []
+ for (const cwd of ctx.projectCwds()) {
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) continue
+ roots.push(ctx.realpath(cwd) ?? cwd)
+ }
+ return roots
+}
+
+/** `p` is `root` or below it. Relative-path based, so a sibling like `/srv/app2` is not inside
+ * `/srv/app`, a root of `/` contains everything, and a path on another Windows drive is outside. */
+function within(root: string, p: string): boolean {
+ const rel = path.relative(root, p)
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))
+}
+
+/** The REAL path of `p` when it is an absolute path inside a shared project root, else null. The
+ * file is realpathed, so a symlink planted inside the project that points out of it is outside. */
+function realInSharedCwd(p: unknown, ctx: AccessContext): string | null {
+ if (typeof p !== 'string' || !path.isAbsolute(p)) return null
+ const resolved = ctx.realpath(path.resolve(p))
+ if (!resolved) return null
+ return sharedRoots(ctx).some((root) => within(root, resolved)) ? resolved : null
+}
+
+const READ_JAIL = 'Viewers can only read files inside a shared project.'
+
+const nodeArg0: Check = (a, ctx) => (sharedNode(a[0], ctx) ? OK : no('That terminal is not in a shared project.'))
+const pathArg0: Check = (a, ctx) => (realInSharedCwd(a[0], ctx) ? OK : no(READ_JAIL))
+const projectArg0: Check = (a, ctx) => (sharedProject(a[0], ctx) ? OK : no('That project is not shared.'))
+
+/** The ONLY create fields a watch-only join keeps. Everything else on `PtyCreateOptions` either
+ * shapes a spawn (shell, cwd, account, env) or routes one: `sshRemote.conn` carries `extraArgs`
+ * and `execTrusted`, and the join's existence probe runs `ssh` with them BEFORE `joinOnly` refuses
+ * anything — an `-oProxyCommand=` there is a command run on this host. */
+function viewerCreateOptions(o: Record<string, unknown>): Record<string, unknown> {
+ const out: Record<string, unknown> = { persistKey: o.persistKey }
+ if (typeof o.cols === 'number') out.cols = o.cols
+ if (typeof o.rows === 'number') out.rows = o.rows
+ if (typeof o.viewerId === 'string') out.viewerId = o.viewerId
+ return { ...out, joinOnly: true, sizeVote: false }
+}
+
+/** `git diff` (handler args: cwd, file, staged, untracked). The FILE is jailed as well as the cwd. */
+const gitDiff: Check = (a, ctx) => {
+ const cwd = realInSharedCwd(a[0], ctx)
+ if (!cwd) return no(READ_JAIL)
+ const file = a[1]
+ // Pathspec magic (`:(top)…`) re-roots the path at the repository, which can sit above the project.
+ if (typeof file !== 'string' || file.startsWith(':')) return no(READ_JAIL)
+ const target = path.resolve(cwd, file)
+ // The handler reads `untracked` truthily, and then runs `git diff --no-index -- /dev/null <file>`,
+ // which compares FILES, not a repository: any path on the host. Only a real path inside passes.
+ if (a[3]) return realInSharedCwd(target, ctx) ? OK : no(READ_JAIL)
+ // A tracked diff: git refuses a pathspec outside the repository and does not follow a symlink in
+ // one, so a lexical check is enough — and a deleted file, which has no realpath, stays viewable.
+ return sharedRoots(ctx).some((root) => within(root, target)) ? OK : no(READ_JAIL)
+}
+
+/** `git show <ref>:<file>` (handler args: cwd, ref, file). A ref starting with `-` becomes an
+ * OPTION of `git show`; measured: `--output=<path>` writes the command's output to that path. */
+const gitShowFile: Check = (a, ctx) => {
+ if (!realInSharedCwd(a[0], ctx)) return no(READ_JAIL)
+ const ref = a[1]
+ if (ref !== undefined && ref !== null && (typeof ref !== 'string' || ref.startsWith('-'))) {
+ return no('That is not a revision name.')
+ }
+ return typeof a[2] === 'string' ? OK : no(READ_JAIL)
+}
+
+export const VIEW: Readonly<Record<string, Check>> = Object.freeze({
+ // Narrowed to the shared projects by the host's narrowResponse hook.
+ [IPC.workspaceLoad]: pass,
+ [IPC.ptyCreate]: (a, ctx) => {
+ const o = a[0]
+ if (!o || typeof o !== 'object' || Array.isArray(o) || !sharedNode((o as Record<string, unknown>).persistKey, ctx)) {
+ return no('Viewers can only watch terminals in a shared project that are already running.')
+ }
+ return { allow: true, args: [viewerCreateOptions(o as Record<string, unknown>)] }
+ },
+ // Rewritten to "not looking": a viewer's window never sizes the shared terminal.
+ [IPC.ptyResize]: (a) => ({ allow: true, args: [a[0], null, null, ...(a.length > 3 ? [a[3]] : [])] }),
+ // Handler args: sessionId, resume, viewerId. A PAUSE is not the sender's own business: it pauses
+ // the shared pty process (`PtyManager.setFlow` → `proc.pause()`) for every subscriber until the
+ // pausing view resumes or leaves, so a viewer that never resumes freezes the editor's terminal.
+ // A viewer may only resume (a no-op for a view that owes no pause). That closes the EXPLICIT
+ // pause, not every pause: a relay peer whose socket backlog passes WS_HIGH_WATER (1 MB) still
+ // takes that connection's `socket` backpressure ticket (ui-sink-registry.ts `sendTo`), which pauses
+ // the shared pty for every subscriber until the backlog drains below WS_LOW_WATER or the peer
+ // leaves. Only past the 8 MB drop-and-redraw ceiling is its output dropped and the pause handed
+ // back. A known residual: docs/hosted-team-relay.md, "Limitations (v1)".
+ [IPC.ptyFlow]: (a) => (a[1] === true ? OK : no('Viewers never pause a shared terminal.')),
+ // Detaches the sender's OWN view only (the core checks `subscribes`); the session keeps running.
+ [IPC.ptyKill]: pass,
+ [IPC.ptyCapture]: nodeArg0,
+ [IPC.ptyReadScrollback]: nodeArg0,
+ [IPC.ptyPaneCommand]: nodeArg0,
+ [IPC.ptyTmuxStatus]: pass,
+ [IPC.fsList]: pathArg0,
+ [IPC.fsRead]: pathArg0,
+ [IPC.fsReadBinary]: pathArg0,
+ [IPC.fsExists]: pathArg0,
+ [IPC.gitStatus]: pathArg0,
+ [IPC.gitRepoRoot]: pathArg0,
+ [IPC.gitDiff]: gitDiff,
+ [IPC.gitShowFile]: gitShowFile,
+ // Its only other argument's ref (`baseRef`) is refused by the core when it starts with `-`.
+ [IPC.gitHistory]: pathArg0,
+ // The RESPONSE is trimmed by narrowResponseForRole (it is a response, not an event).
+ [IPC.agentSubagentSnapshot]: pass,
+ [IPC.presenceHello]: pass,
+ [IPC.presenceCursor]: pass,
+ [IPC.presenceFocus]: pass,
+ [IPC.presenceProject]: pass,
+ [IPC.boardLogRead]: projectArg0,
+ [IPC.boardLogSubscribe]: projectArg0,
+ [IPC.boardLogUnsubscribe]: projectArg0
+})
+
+export const COMMENT: Readonly<Record<string, Check>> = Object.freeze({
+ [IPC.presenceChat]: pass,
+ [IPC.boardLogAppend]: projectArg0
+})
+
+/**
+ * Relay-reachable channels reviewed and deliberately left Editor-only: every `IPC.*` the relay tab's
+ * API builders reference that is not in VIEW/COMMENT (the guard test lists them). Listing a channel
+ * here changes nothing at runtime — non-editors are denied anything not allowlisted — it records
+ * that someone DECIDED. This is about what a peer may SEND; what it may RECEIVE is VIEW_EVENTS, so
+ * server→client event channels are listed here too (a client cannot invoke them).
+ */
+export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
+ // Terminals: typing, ending, restarting and signalling a session; host-side probes.
+ IPC.ptyWrite,
+ IPC.ptyDestroy,
+ IPC.ptyRecycle,
+ IPC.ptySessionAge,
+ IPC.ptySendText,
+ IPC.ptyPaneOwner,
+ IPC.ptyTerminateForeground,
+ IPC.ptyReadSessionName,
+ // Workspace, project settings and setup: writes, probes of arbitrary folders, trust, scripts.
+ IPC.workspaceSave,
+ IPC.workspaceProbeFolder,
+ IPC.workspaceProjectFileState,
+ IPC.projectSettingsRead,
+ IPC.projectSettingsWriteShared,
+ IPC.projectSettingsUpdateLocal,
+ IPC.projectSettingsLaunchInfo,
+ IPC.projectSetupRun,
+ IPC.projectSetupCancel,
+ IPC.projectSetupConsentSubmit,
+ IPC.projectSetupRequestTrust,
+ IPC.projectSetupSubscribe,
+ IPC.projectSetupUnsubscribe,
+ IPC.worktreeMaterializeShared,
+ // Host settings, credentials and paths.
+ IPC.settingsLoad,
+ IPC.settingsSave,
+ IPC.agentDiscoverModels,
+ IPC.agentGatewayCredentialStatus,
+ IPC.agentGatewayCredentialSave,
+ IPC.agentGatewayCredentialClear,
+ IPC.appUserDataDir,
+ IPC.claudeCliCaps,
+ // Files: writes, uploads, and unjailed listings / downloads.
+ IPC.fsWrite,
+ IPC.fsMkdir,
+ IPC.filesQuickOpen,
+ IPC.filesDownloadTicket,
+ IPC.filesSaveUpload,
+ IPC.filesSaveCanvasImage,
+ // Git: every mutation, plus network, worktree and commit-message (runs an agent CLI) operations.
+ IPC.gitInit,
+ IPC.gitClone,
+ IPC.gitCloneAbort,
+ IPC.gitCloneDefaultParent,
+ IPC.gitCommit,
+ IPC.gitPush,
+ IPC.gitPull,
+ IPC.gitSync,
+ IPC.gitPublish,
+ IPC.gitStage,
+ IPC.gitUnstage,
+ IPC.gitStageAll,
+ IPC.gitUnstageAll,
+ IPC.gitDiscard,
+ IPC.gitSwitchBranch,
+ IPC.gitCreateBranch,
+ IPC.commitGenerate,
+ IPC.gitCommitFiles,
+ IPC.gitRemoteCommitUrl,
+ IPC.gitMerge,
+ IPC.gitRebase,
+ IPC.gitDeleteBranch,
+ IPC.gitRenameBranch,
+ IPC.gitFetch,
+ IPC.gitForcePush,
+ IPC.gitStashPush,
+ IPC.gitStashPop,
+ IPC.gitRevert,
+ IPC.gitBranchAt,
+ IPC.gitCheckoutCommit,
+ IPC.gitWorktreeList,
+ IPC.gitWorktreeAdd,
+ IPC.gitWorktreeMerge,
+ IPC.gitWorktreeRemove,
+ IPC.gitSetActiveRemote,
+ // Agent context, the host debug log, GitHub (host token) and agent control.
+ IPC.contextEnsure,
+ IPC.logSnapshot,
+ IPC.logClear,
+ IPC.logSubscribe,
+ IPC.logUnsubscribe,
+ IPC.githubIssuesSubscribe,
+ IPC.githubIssuesUnsubscribe,
+ IPC.githubIssuesQuery,
+ IPC.githubIssuesRefresh,
+ IPC.githubIssuesMove,
+ IPC.githubIssuesCreateLabels,
+ IPC.githubIssuesClearCache,
++ // Pull request CI / mergeability (landed on main alongside this branch). Reads and writes alike
++ // run on the HOST's GitHub token, like the issue verbs above, so non-editors get none of them.
++ IPC.githubIssuesPullStatus,
++ IPC.githubIssuesChasePulls,
++ IPC.githubIssuesPullChecks,
++ IPC.githubIssuesClaimPullAutoMove,
++ IPC.githubIssuesNotePullWaits,
+ IPC.githubProjectAvatar,
+ IPC.githubControlStatus,
+ IPC.githubControlApprove,
+ IPC.githubControlRevoke,
+ IPC.githubControlSelectProvider,
+ IPC.githubControlSaveToken,
+ IPC.githubControlClearToken,
+ IPC.agentHibernated,
+ IPC.agentAnswerPermission,
+ IPC.agentAckDone,
++ // A relay tab's `seedAgentIdentity` is a local no-op (relay-api.ts), so this never crosses the
++ // tunnel today; it WRITES the mirror's session identities, so a peer that sent it is an editor.
++ IPC.agentSeedIdentity,
+ // 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,
+ IPC.workspaceExternalChange,
+ IPC.workspaceServerChange,
+ IPC.projectTrustChanged,
+ IPC.projectSetupConsentRequest,
+ IPC.projectSetupConsentDismiss,
+ IPC.gitCloneProgress,
+ IPC.contextUpdate,
+ IPC.logBatch,
+ IPC.agentStatus,
+ IPC.agentUnreadClear,
+ IPC.agentSubagentActivity,
+ IPC.presenceSync,
+ IPC.presencePeer
+])
+
+const ROLE_NAME: Readonly<Record<string, string>> = { owner: 'Owners', editor: 'Editors', commenter: 'Commenters', viewer: 'Viewers' }
+
+export function decideAccess(_kind: 'req' | 'cast', method: string, args: unknown[], ctx: AccessContext): AccessDecision {
+ if (isEditor(ctx.role)) return OK
+ // Own keys only: a method named `constructor` must not find Object.prototype's.
+ const check =
+ typeof method !== 'string'
+ ? undefined
+ : Object.hasOwn(VIEW, method)
+ ? VIEW[method]
+ : ctx.role === 'commenter' && Object.hasOwn(COMMENT, method)
+ ? COMMENT[method]
+ : undefined
+ if (!check) {
+ // An unrecognised role is the lowest one, never a new name in the sentence.
+ const name = Object.hasOwn(ROLE_NAME, ctx.role) ? ROLE_NAME[ctx.role] : ROLE_NAME.viewer
+ return no(`${name} can't do that here. Ask an owner for Editor access.`)
+ }
+ return check(Array.isArray(args) ? args : [], ctx)
+}
+
+/**
+ * Which node started each subagent (toolUseId → nodeId), learned from the `subagent-start` events
+ * this sink saw. `agent:subagent-activity` carries only `{ toolUseId, chunk }` — no node id — so this
+ * is the one way to tell a shared node's subagent transcript from anyone else's. Per sink, bounded.
+ */
+export type SubagentOwners = Map<string, string>
+const SUBAGENT_OWNERS_MAX = 512
+
+function learnSubagentOwner(payload: unknown, owners: SubagentOwners): void {
+ if (field(payload, 'kind') !== 'subagent-start') return
+ const toolUseId = field(payload, 'toolUseId')
+ const nodeId = field(payload, 'nodeId')
+ if (typeof toolUseId !== 'string' || typeof nodeId !== 'string') return
+ // No delete on subagent-end: the tail flushes its last chunk AFTER the end event.
+ const prev = owners.get(toolUseId)
+ owners.delete(toolUseId)
+ // Two nodes claiming one id: attributable to neither (fails closed; '' is never a shared node).
+ owners.set(toolUseId, prev === undefined || prev === nodeId ? nodeId : '')
+ while (owners.size > SUBAGENT_OWNERS_MAX) owners.delete(owners.keys().next().value as string)
+}
+
+type EventCheck = (args: unknown[], ctx: AccessContext, owners: SubagentOwners | undefined) => boolean
+const always: EventCheck = () => true
+
+/** Exact event channels a Viewer/Commenter may RECEIVE. Anything else is dropped for them. */
+export const VIEW_EVENTS: Readonly<Record<string, EventCheck>> = Object.freeze({
+ [IPC.canvasMut]: (a, ctx) => sharedProject(a[0], ctx),
+ [IPC.agentStatus]: (a, ctx) => sharedNode(field(a[0], 'nodeId'), ctx),
+ [IPC.agentSubagentActivity]: (a, ctx, owners) => {
+ const toolUseId = field(a[0], 'toolUseId')
+ return typeof toolUseId === 'string' && sharedNode(owners?.get(toolUseId), ctx)
+ },
+ [IPC.agentUnreadClear]: (a, ctx) => sharedNode(a[0], ctx),
+ // Both carry a whole Project document.
+ [IPC.workspaceExternalChange]: (a, ctx) => sharedProject(field(a[0], 'id'), ctx),
+ [IPC.workspaceServerChange]: (a, ctx) => sharedProject(field(a[0], 'id'), ctx),
+ [IPC.projectTrustChanged]: (a, ctx) => sharedProject(field(a[0], 'projectId'), ctx),
+ // Token counts + model for an opaque agent session id: no project, node, path or text.
+ [IPC.contextUpdate]: always,
+ [IPC.presenceSync]: always,
+ [IPC.presencePeer]: always
+})
+
+/** Per-name event channels. The pty ones are sent only to a session's SUBSCRIBERS, and a viewer
+ * subscribes only through the jailed pty:create above. */
+const VIEW_EVENT_PREFIXES: ReadonlyArray<readonly [string, (suffix: string, ctx: AccessContext) => boolean]> = [
+ [IPC.ptyExit(''), () => true],
+ [IPC.ptySize(''), () => true],
+ [IPC.ptyClosed(''), () => true],
+ [IPC.ptyRecycled(''), () => true],
+ [IPC.ptyResync(''), () => true],
+ [IPC.boardLogChanged(''), (projectId, ctx) => sharedProject(projectId, ctx)],
+ [IPC.projectSetupEvent(''), (projectId, ctx) => sharedProject(projectId, ctx)]
+]
+
+/**
+ * true = deliver this sink message to the peer. Editors and owners get everything. For anyone else a
+ * message is delivered only if it is an event on an allowlisted channel whose check passes; a
+ * message that cannot be attributed (not JSON, not an event, no channel) is dropped, never guessed.
+ * `subagentOwners` is the sink's memory of who started which subagent (see wrapSinkForRole);
+ * without it, subagent output is never delivered to a non-editor.
+ */
+export function filterOutboundEvent(json: string, ctx: AccessContext, subagentOwners?: SubagentOwners): boolean {
+ if (isEditor(ctx.role)) return true
+ let m: unknown
+ try {
+ m = JSON.parse(json)
+ } catch {
+ return false
+ }
+ if (field(m, 't') !== 'ev') return false
+ const channel = field(m, 'channel')
+ if (typeof channel !== 'string') return false
+ const rawArgs = field(m, 'args')
+ const args = Array.isArray(rawArgs) ? rawArgs : []
+ // Learn BEFORE deciding: a start on a node that is not shared today still names its owner.
+ if (channel === IPC.agentStatus && subagentOwners) learnSubagentOwner(args[0], subagentOwners)
+ if (Object.hasOwn(VIEW_EVENTS, channel)) return VIEW_EVENTS[channel](args, ctx, subagentOwners)
+ for (const [prefix, check] of VIEW_EVENT_PREFIXES) {
+ if (channel.startsWith(prefix)) return check(channel.slice(prefix.length), ctx)
+ }
+ return false
+}
+
+/**
+ * A response the peer asked for that no argument check can narrow. Only the subagent snapshot today:
+ * it holds every running subagent's task text, keyed by node. Editors and every other method pass
+ * through unchanged. Wire it into the host's `narrowResponse` hook.
+ */
+export function narrowResponseForRole(method: string, result: unknown, ctx: AccessContext): unknown {
+ if (isEditor(ctx.role) || method !== IPC.agentSubagentSnapshot) return result
+ return Array.isArray(result) ? result.filter((e) => sharedNode(field(e, 'nodeId'), ctx)) : []
+}
+
+/**
+ * The peer's sink, filtered for its role. `ctxFor` is asked per message, so a role or share change
+ * applies to the next event. Terminal bytes (`sendBinary`) pass: they go only to a session's
+ * subscribers. `bufferedAmount` stays the underlying socket's — Stage 2 backpressure and the 8 MB
+ * drop ceiling key on it (see relay-host.ts `open`).
+ */
+export function wrapSinkForRole(sink: UiSink, ctxFor: () => AccessContext): UiSink {
+ const owners: SubagentOwners = new Map()
+ let warned = false
+ return {
+ sendText: (json) => {
+ let deliver: boolean
+ try {
+ deliver = filterOutboundEvent(json, ctxFor(), owners)
+ } catch (err) {
+ // Fail closed WITHOUT throwing: the registry reads a throwing sink as a dead socket and would
+ // tear the peer down while its relay socket stays open. The socket's own throws (below) must
+ // still propagate, so only the decision is guarded.
+ if (!warned) {
+ warned = true
+ console.warn(`[access-policy] could not build the access context; dropping events: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ return
+ }
+ if (deliver) sink.sendText(json)
+ },
+ sendBinary: (buf) => sink.sendBinary(buf),
+ bufferedAmount: () => sink.bufferedAmount?.() ?? 0
+ }
+}
diff --cc src/core/relay/relay-project-scope.ts
index ec0195d44,000000000..63f81ce76
mode 100644,000000..100644
--- a/src/core/relay/relay-project-scope.ts
+++ b/src/core/relay/relay-project-scope.ts
@@@ -1,75 -1,0 +1,80 @@@
+// Which relay-guest methods name a PROJECT, and which project — the one table behind the scope jail
+// in `relay-host.ts` (a session bound to one shared project must never let the guest reach another).
+//
+// The jail used to be a per-feature switch with a `default: not project-scoped` arm, so a method the
+// switch did not list was waved through. That is safe only for as long as every project-naming
+// channel is remembered in every switch, and it failed OPEN for the next one nobody added: a new
+// `githubIssues:*` verb would have reached another project's repository with no refusal anywhere.
+// So membership is by CLASS (channel prefix), and a method inside a class that this table cannot
+// read a projectId out of is answered as "names an unknown project" — which a scoped session
+// refuses. Adding a channel to a class therefore costs one table row to become reachable, rather
+// than one forgotten row to become a hole.
+//
+// `projects.*` is in the class although no IPC channel carries that prefix today: it is the phone
+// dialect's board verbs (`projects.ensureBoard` / `setCardColumn` / `editCardLabels`, served by
+// host-service to an approved PHONE, never on this tunnel). Classifying it here means that if a
+// relay guest ever sends one — or a future channel is named after it — it is judged by the shared
+// project rather than passed to a router on the assumption that nothing answers.
+//
+// Unscoped sessions are not affected at all: with no shared project the jail is off, exactly as
+// before (the host registry is then the only gate, as it is for the host's own renderer).
+
+import { IPC } from '../../shared/ipc'
+
+export interface ProjectScope {
+ /** The method belongs to a project-scoped channel class. */
+ scoped: boolean
+ /** The projectId it names — `undefined` when the class is known but the method is not, which
+ * the jail treats as "not the shared project" (fail closed). */
+ projectId: unknown
+}
+
+/** Channel prefixes whose every method acts on ONE project. */
+export const PROJECT_SCOPED_PREFIXES = ['githubIssues:', 'board-log:', 'projects.'] as const
+
+const fromFirstArg = (args: unknown[]): unknown => args[0]
+const fromFirstArgField = (args: unknown[]): unknown =>
+ args[0] && typeof args[0] === 'object' ? (args[0] as { projectId?: unknown }).projectId : undefined
+
+/** Methods whose projectId we know how to read. Everything else in a scoped class fails closed. */
+const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {
+ [IPC.githubIssuesSubscribe]: fromFirstArgField,
+ [IPC.githubIssuesQuery]: fromFirstArgField,
+ [IPC.githubIssuesMove]: fromFirstArgField,
+ [IPC.githubIssuesRefresh]: fromFirstArg,
+ [IPC.githubIssuesCreateLabels]: fromFirstArg,
+ [IPC.githubIssuesClearCache]: fromFirstArg,
+ [IPC.githubIssuesUnsubscribe]: fromFirstArg,
++ [IPC.githubIssuesPullStatus]: fromFirstArg,
++ [IPC.githubIssuesChasePulls]: fromFirstArg,
++ [IPC.githubIssuesPullChecks]: fromFirstArg,
++ [IPC.githubIssuesClaimPullAutoMove]: fromFirstArgField,
++ [IPC.githubIssuesNotePullWaits]: fromFirstArgField,
+ [IPC.boardLogAppend]: fromFirstArg,
+ [IPC.boardLogRead]: fromFirstArg,
+ [IPC.boardLogSubscribe]: fromFirstArg,
+ [IPC.boardLogUnsubscribe]: fromFirstArg,
+ // The phone dialect's params object, should one ever arrive as the first arg.
+ 'projects.ensureBoard': fromFirstArgField,
+ 'projects.setCardColumn': fromFirstArgField,
+ 'projects.editCardLabels': fromFirstArgField
+}
+
+export function projectScopeOf(method: string, args: unknown[]): ProjectScope {
+ if (!PROJECT_SCOPED_PREFIXES.some((p) => method.startsWith(p))) {
+ return { scoped: false, projectId: undefined }
+ }
+ const extract = EXTRACTORS[method]
+ return { scoped: true, projectId: extract ? extract(Array.isArray(args) ? args : []) : undefined }
+}
+
+/** True when a session bound to `sharedProjectId` must refuse this method. Unscoped ⇒ never. */
+export function outOfProjectScope(
+ sharedProjectId: string | undefined,
+ method: string,
+ args: unknown[]
+): boolean {
+ if (!sharedProjectId) return false
+ const scope = projectScopeOf(method, args)
+ return scope.scoped && scope.projectId !== sharedProjectId
+}
diff --cc src/core/workspace-store.ts
index a65eefefb,a7e00be02..167064e9b
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@@ -1506,45 -1505,39 +1507,78 @@@ export class WorkspaceStore
return undefined
}
+ /**
+ * The project a node belongs to — the first project that has it, exactly as a `persistedCanvases`
+ * scan answers. Memoized, because a hosted-team relay asks it once per access decision for every
+ * viewer (each agent:status event, subagent-activity chunk, unread-clear, snapshot element) and a
+ * `persistedCanvases()` call re-parses every local project's cached file.
+ *
+ * The memo is validated against the IDENTITY of every input `persistedCanvases` reads
+ * (`canvasInputs`), not a version counter: a counter is only as good as the writers that remember
+ * to bump it, and this class changes those inputs from a dozen places — `lastWritten.set`, index
+ * reassignment, and in-place entry updates (`e.cache = …`, `e.project = …`, `e.id = …` on a
+ * re-key). Every one of them replaces a reference, so a snapshot comparison sees all of them,
+ * including writers added later. It rests on one rule this file already keeps: a project's node
+ * array is replaced, never mutated in place.
+ */
+ projectIdForNode(nodeId: string): string | undefined {
+ const inputs = this.canvasInputs()
+ const memo = this.nodeProjectMemo
+ const fresh =
+ memo !== null && memo.inputs.length === inputs.length && memo.inputs.every((v, i) => v === inputs[i])
+ if (fresh) return memo.map.get(nodeId)
+ const map = new Map<string, string>()
+ for (const c of this.persistedCanvases()) {
+ for (const n of c.nodes) if (!map.has(n.id)) map.set(n.id, c.id)
+ }
+ this.nodeProjectMemo = { inputs, map }
+ return map.get(nodeId)
+ }
+
+ /** Every input `persistedCanvases` reads, by identity: the index object, and per entry the entry,
+ * its id, its inline project, its ssh cache, its cwd and the text last written/read for that
+ * cwd's project file. */
+ private canvasInputs(): unknown[] {
+ const out: unknown[] = [this.index]
+ for (const e of this.index?.entries ?? []) {
+ out.push(e, e.id, e.project, e.cache, e.cwd, e.cwd ? this.lastWritten.get(projectFilePath(e.cwd)) : undefined)
+ }
+ return out
+ }
+
+ /**
+ * Every node id in every project the index holds — open, closed and SSH alike — or `undefined`
+ * when that set cannot be known: the index is not loaded, a local ref's project.json has not been
+ * read this run (unavailable folder, corrupt file), or an SSH entry has no offline cache.
+ *
+ * The agent-status mirror uses it to drop an IDENTITY-ONLY entry (a session id kept past the 6 h
+ * state expiry) whose node was deleted while this process was not watching. A wrong "gone" costs
+ * the phone that node's session id, so every doubt answers `undefined` — the mirror then bounds
+ * the entry by its identity TTL alone. Same three-entry-kind scan as `findNode`.
+ * Consequence: ONE permanently unavailable local ref or one never-cached SSH project turns
+ * existence pruning off for EVERY project, leaving only the 30-day identity TTL.
+ * Parses through `parsedLastWritten`, so a mirror flush re-parses no unchanged project.json.
+ */
+ knownNodeIds(): Set<string> | undefined {
+ if (!this.index) return undefined
+ const ids = new Set<string>()
+ for (const e of this.index.entries) {
+ let nodes: CanvasNodeState[] | undefined
+ if (e.project) nodes = e.project.nodes
+ else if (e.cache) nodes = e.cache.nodes
+ else if (e.cwd) {
+ try {
+ nodes = this.parsedLastWritten(projectFilePath(e.cwd))?.nodes
+ } catch {
+ return undefined
+ }
+ }
+ if (!Array.isArray(nodes)) return undefined
+ for (const n of nodes) if (n && typeof n.id === 'string') ids.add(n.id)
+ }
+ return ids
+ }
+
/**
* Every persisted canvas as {id, nodes, bridges} — the raw material the Server Edition derives
* its context-link map from (src/server/context-link.ts). Same three-entry-kind scan as
diff --cc src/renderer/bridge/relay-api.ts
index 2d42057ce,3a1d02022..0f5755d7e
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@@ -186,11 -165,11 +186,16 @@@ export function buildRelayApi
// 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,
+ // The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's
+ // core, whose mirror is seeded by the host's own renderer from its own localStorage. This
+ // machine's localStorage holds no identity for them, and `...local` would plant this machine's
+ // ids into this machine's mirror under the peer's node ids.
- seedAgentIdentity: () => undefined
++ seedAgentIdentity: () => undefined,
+
+ // 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 {
diff --cc src/renderer/canvas/Canvas.tsx
index f4e201302,a3d49d9b3..c868ec5ce
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@@ -480,17 -497,9 +497,18 @@@ import
reconnectRelayTab,
type RelayTab,
} from '../session/relay-tab'
+import { HostedApprovalDialog } from '../components/HostedApprovalDialog'
+import { emitLocalRelayClose, onLocalRelayClose } from '../bridge/relay-local-close'
+import { isJoinCode } from '@shared/relay-join-code'
+import { createHostedJoiner, type HostedJoiner, type HostedMountOutcome } from '../lib/hostedJoin'
+import { HOSTED_APPROVAL_WAIT_MS, isReadOnlyRole, stripIpcPrefix, viewerBannerText } 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 {
+ deliveriesToRetire,
launchesToFire,
queueControlLaunch,
LAUNCH_STALL_MS,
@@@ -710,15 -741,9 +751,18 @@@ function noticeDwellMs(text: string): n
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
+
+/** Is this project an open tab (not closed, not deleted)? What a hosted reconnect is for (R40). */
+function isOpenTab(projectId: string): boolean {
+ const p = useProjects.getState().getProject(projectId)
+ return !!p && !p.closed
+}
+
+ /** What the agent-control handler's `reply` accepts, for helpers that build one outside it. */
+ type ControlReply = { ok: boolean; message?: string; result?: unknown; error?: string }
+
/** 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 {
diff --cc src/renderer/nodes/TerminalNode.tsx
index dfaf07566,cd7c05429..d33dcd434
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@@ -3312,28 -3333,6 +3341,29 @@@ export function TerminalNode(
// the near-side guard above produces, retry included.
if (unavailable) {
const refusal = ptyRefusal(unavailable)
+ // A hosted-relay VIEWER opened a terminal it could not find running. Nothing failed and
+ // nothing is offline, so neither overlay applies — "Try again" would only respawn into the
+ // same refusal. What CAN still be on screen is state from an earlier run of this effect
+ // (a refresh re-enters here): a spawn-error overlay (only its own "Try again" clears it),
+ // the stale-cwd and lost-session banners (the success path resets them on every create
+ // result, and this path returns before it; "Restart in folder" would recycle a session
+ // this view does not hold), a refused-launch banner about a launch into a session that
+ // is not attached, and a letterbox sized to a pty that is not attached. Clear them the
+ // way the neighbouring refusals set theirs, say why the pane is empty, and stop;
+ // "Refresh terminal" re-asks on demand.
+ if (unavailable === 'join-only') {
+ setCo(termKey, {
+ offline: false,
+ spawnError: null,
+ staleCwd: false,
+ lostSession: false,
+ launchTooLongBytes: null,
- letterbox: false
++ letterbox: false,
++ geminiRetired: false
+ })
+ if (!disposed) term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)
+ return
+ }
setCo(
termKey,
refusal.connectionLost