Skip to content

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

fix(hosted-team): `team unshare` stops terminals a Viewer is already watching (I3)

reviewe6f986b18a0c
diff --git a/CLAUDE.md b/CLAUDE.md
index 28d17f896..02ccc4055 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6190,7 +6190,9 @@ The invariants, each with its reason:
<ref>:<p>` resolves `<p>` against the repository's top level and `git status`/`log` report the
whole repository, so from a shared `repo/shared/` a Viewer read `repo/secret/key.txt` (measured,
C1) — a monorepo subfolder gets no git panel; `pty:create` is cut down to a whitelist, because
- `sshRemote`'s args run `ssh` on the host during the existence probe. Editors pass untouched
+ `sshRemote`'s args run `ssh` on the host during the existence probe. A non-editor's terminal
+ frames (output, resync, size, exit) are judged per frame by the session's node
+ (`PtyManager.nodeOfSession`), because a subscription outlives `team unshare`. Editors pass untouched
(Editor is shell access). The UI mirror (`@shared/hosted-access.ts`, `bridge/hosted-gate.ts`) is
convenience; `access-policy.guard.test.ts` pins it equal and fails on any relay-API channel
nobody classified.
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
index af86fa626..3bf18d753 100644
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@ -62,7 +62,7 @@ such as hosting not starting), 2 the command line is wrong.
| `team init` | Creates the host key (once) and `team.json` if absent, then starts hosting. Prints the address and join code when hosting started. An unreadable key is refused, never replaced. |
| `team add-owner <device-key> [--label <name>]` | Pins that device as an **owner**. An existing member's key is promoted to owner. The key must be the canonical 44-character base64 public key; a typo gets its own message before anything is sent. |
| `team remove <device-key> [--force]` | Unpins the key and cuts its live sessions (they are told `removed`). Removing the last owner needs `--force`. |
-| `team share <projectId>` / `team unshare <projectId>` | Adds or removes a project in `sharedProjects`. The id is **not** checked against the workspace. |
+| `team share <projectId>` / `team unshare <projectId>` | Adds or removes a project in `sharedProjects`. The id is **not** checked against the workspace. An unshare applies to the next message: a Viewer already watching one of its terminals gets no more output from it. |
| `team info [--json]` | The team address and join code. The plain form prints the join code only while hosting is on; `--json` returns `{enabled, info, joinCode}`. |
| `team status [--json]` | Hosting state, members, and pending join requests (see [Status and troubleshooting](#status-and-troubleshooting)). |
| `team rotate-key` | Replaces the host key. Every bookmark and join code stops working. A hosting service restarts on the new key; one that was not hosting stays off. |
@@ -214,8 +214,14 @@ receives only the events `VIEW_EVENTS` lists: `canvas:mut`, `workspace:external-
`agent:unread-clear` for shared nodes; `agent:subagent-activity` for subagents a shared node
started; `context:update`, `presence:sync` and `presence:peer` for everyone (see
[Limitations](#limitations-v1)); the per-session pty channels, which only a session's subscribers
-receive; and `board-log:changed:<id>` / `project-setup:event:<id>` for shared projects. Terminal
-bytes pass, because they go only to a session's subscribers.
+receive; and `board-log:changed:<id>` / `project-setup:event:<id>` for shared projects.
+
+**A terminal is judged by its node on every frame.** Terminal output and `pty:resync` (a repaint of
+the screen) reach a non-editor only while the session's node is in a shared project. `pty:size`,
+`pty:exit`, `pty:closed` and `pty:recycled` stop once the node is known to be outside every shared
+project; for a session that has already ended they still pass, since all they carry is that fact.
+This is what makes `team unshare` stop a terminal a Viewer is already watching: the subscription
+itself outlives the unshare, but nothing more of that terminal is delivered to it.
The renderer mirrors the two allowlists in `@shared/hosted-access.ts` (`bridge/hosted-gate.ts`
answers a refused call locally, in the host's words), and the guard test pins the mirror equal to
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 0968a2683..e01955a4f 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -4349,6 +4349,16 @@ export class PtyManager {
}
}
+ /**
+ * The canvas node a live session runs (its unconditional `nodeId`, see `Session`), or undefined
+ * when the session is unknown: never created, or already ended. Read-only. The hosted team relay
+ * judges each terminal frame it sends a Viewer by it, so `team unshare` stops a stream the viewer
+ * joined earlier (docs/hosted-team-relay.md).
+ */
+ nodeOfSession(sessionId: string): string | undefined {
+ return this.sessions.get(sessionId)?.nodeId
+ }
+
/**
* The CURRENT screen of a live session, by sessionId — the redraw sent to a client that fell so
* far behind that its socket backlog was discarded (see ServerPlatform's WS_DROP_WATER). Reuses
diff --git a/src/core/relay/access-policy.test.ts b/src/core/relay/access-policy.test.ts
index b1184eddc..42b2cc533 100644
--- a/src/core/relay/access-policy.test.ts
+++ b/src/core/relay/access-policy.test.ts
@@ -10,12 +10,15 @@ import {
type AccessContext
} from './access-policy'
import { IPC } from '../../shared/ipc'
+import { encodePtyData } from '../../shared/rpc'
import type { UiSink } from '../ui-sink-registry'
const ctx = (role: AccessContext['role']): AccessContext => ({
role,
sharedProjects: new Set(['P']),
projectOfNode: (id) => (id === 'n1' ? 'P' : id === 'n2' ? 'Q' : undefined),
+ // Terminal sessions: 's' / 's1' run node n1 (project P, shared), 's2' runs n2 (project Q, not).
+ nodeOfSession: (sid) => (sid === 's' || sid === 's1' ? 'n1' : sid === 's2' ? 'n2' : undefined),
projectCwds: () => ['/srv/app'],
realpath: (p) => (p.startsWith('/srv/app/link') ? '/etc/passwd' : p)
})
@@ -100,6 +103,7 @@ describe('access policy: the fs jail', () => {
role: 'viewer',
sharedProjects: new Set(['P']),
projectOfNode: () => undefined,
+ nodeOfSession: () => undefined,
projectCwds: () => [path.join(root, 'link')],
realpath: (p) => {
try {
@@ -492,6 +496,7 @@ describe('access policy: git needs a shared root that is its own repository (C1)
role: 'viewer',
sharedProjects: new Set(['P']),
projectOfNode: () => undefined,
+ nodeOfSession: () => undefined,
projectCwds: () => [root],
realpath: (p) => {
try {
@@ -517,3 +522,76 @@ describe('access policy: git needs a shared root that is its own repository (C1)
})
const READ_JAIL_MSG = 'Viewers can only read files inside a shared project.'
+
+// I3 / R45. `team unshare` changes only team.json, and a viewer that already joined a terminal of the
+// project keeps its subscription: before this, pty bytes, size, exit and repaint frames kept
+// streaming to it until it reconnected. The sink now asks, per frame, which node the session runs
+// and whether that node is (still) in a shared project.
+describe('access policy: a terminal stops streaming to a non-editor once its project is unshared (I3)', () => {
+ const ev = (channel: string, ...args: unknown[]) => JSON.stringify({ t: 'ev', channel, args })
+ const unshared = (role: AccessContext['role']): AccessContext => ({ ...ctx(role), sharedProjects: new Set() })
+ const sinkWith = () => {
+ const text: string[] = []
+ const bin: Uint8Array[] = []
+ const sink: UiSink = { sendText: (j) => text.push(j), sendBinary: (b) => bin.push(b), bufferedAmount: () => 0 }
+ return { sink, text, bin }
+ }
+
+ it('terminal bytes reach a viewer only for a session whose node is in a shared project NOW', () => {
+ let c = ctx('viewer')
+ const { sink, bin } = sinkWith()
+ const w = wrapSinkForRole(sink, () => c)
+ w.sendBinary(encodePtyData('s1', 'shared'))
+ w.sendBinary(encodePtyData('s2', 'other project'))
+ w.sendBinary(encodePtyData('nope', 'unknown session'))
+ w.sendBinary(new Uint8Array([9, 9])) // not a pty frame at all
+ expect(bin).toEqual([encodePtyData('s1', 'shared')])
+ c = unshared('viewer') // `team unshare P`
+ w.sendBinary(encodePtyData('s1', 'after unshare'))
+ expect(bin).toHaveLength(1)
+ })
+
+ it('an editor receives every frame, and its context is never asked about the session', () => {
+ const { sink, bin } = sinkWith()
+ const c: AccessContext = {
+ ...unshared('editor'),
+ nodeOfSession: () => {
+ throw new Error('an editor frame must not be judged')
+ }
+ }
+ const w = wrapSinkForRole(sink, () => c)
+ w.sendBinary(encodePtyData('s2', 'x'))
+ w.sendBinary(new Uint8Array([9]))
+ expect(bin).toHaveLength(2)
+ })
+
+ it('a context that cannot be built drops terminal bytes instead of throwing into the registry', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const { sink, bin } = sinkWith()
+ const w = wrapSinkForRole(sink, () => {
+ throw new Error('team store unreadable')
+ })
+ expect(() => w.sendBinary(encodePtyData('s1', 'x'))).not.toThrow()
+ expect(bin).toEqual([])
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('per-session events: a repaint needs a shared session; the others stop once the node is known and unshared', () => {
+ // pty:resync carries the screen itself, so it is judged like terminal bytes.
+ expect(filterOutboundEvent(ev(IPC.ptyResync('s1'), 'screen'), ctx('viewer'))).toBe(true)
+ expect(filterOutboundEvent(ev(IPC.ptyResync('s1'), 'screen'), unshared('viewer'))).toBe(false)
+ expect(filterOutboundEvent(ev(IPC.ptyResync('nope'), 'screen'), ctx('viewer'))).toBe(false)
+ for (const ch of [IPC.ptyExit, IPC.ptySize, IPC.ptyClosed, IPC.ptyRecycled]) {
+ expect(filterOutboundEvent(ev(ch('s1'), 0), ctx('viewer')), ch('s1')).toBe(true)
+ expect(filterOutboundEvent(ev(ch('s1'), 0), unshared('viewer')), ch('s1')).toBe(false)
+ expect(filterOutboundEvent(ev(ch('s2'), 0), ctx('commenter')), ch('s2')).toBe(false)
+ // A session that is already gone (a recycle is announced after the old session left the
+ // manager) still tells its subscribers it ended: nothing but that fact is in it.
+ expect(filterOutboundEvent(ev(ch('gone'), 0), ctx('viewer')), ch('gone')).toBe(true)
+ expect(filterOutboundEvent(ev(ch('s2'), 0), unshared('editor')), ch('s2')).toBe(true)
+ }
+ })
+})
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index eb5eb5741..51ff96c06 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -18,6 +18,7 @@
// theatre.
import path from 'node:path'
import { IPC } from '../../shared/ipc'
+import { decodePtyDataSessionId } from '../../shared/rpc'
import type { TeamRole } from './team-store'
import type { AccessDecision } from './relay-host'
import type { UiSink } from '../ui-sink-registry'
@@ -27,6 +28,9 @@ export interface AccessContext {
sharedProjects: ReadonlySet<string>
/** The project a node belongs to, from the persisted canvases. */
projectOfNode(nodeId: string): string | undefined
+ /** The node (canvas node id) a live terminal session runs, from the pty manager; undefined when
+ * the session is unknown (never existed, or already ended). */
+ nodeOfSession(sessionId: string): string | undefined
/** The LOCAL cwds of the shared projects. */
projectCwds(): string[]
/** `fs.realpath`; null = the path does not resolve. */
@@ -427,14 +431,34 @@ export const VIEW_EVENTS: Readonly<Record<string, EventCheck>> = Object.freeze({
[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. */
+/**
+ * Is this terminal session's node (still) in a shared project? `undefined` = the session is not
+ * known to the pty manager (never existed, or already ended). A viewer subscribes to a session only
+ * through the jailed pty:create above, but `team unshare` does not end that subscription (R45), so
+ * every frame of it is judged again here.
+ */
+function sessionShared(sessionId: string, ctx: AccessContext): boolean | undefined {
+ const nodeId = ctx.nodeOfSession(sessionId)
+ return nodeId === undefined ? undefined : sharedNode(nodeId, ctx)
+}
+
+/** A frame that carries the terminal's CONTENT (bytes, a repaint): only for a known, shared session. */
+const sessionContent = (sessionId: string, ctx: AccessContext): boolean => sessionShared(sessionId, ctx) === true
+
+/** A lifecycle frame (size, exit, closed, recycled) holds no content, only a fact about the session:
+ * refused once the session's node is known to be outside the shared projects. A session the manager
+ * no longer knows still tells its subscribers it ended (a recycle is announced after the old
+ * session left the manager). */
+const sessionLifecycle = (sessionId: string, ctx: AccessContext): boolean => sessionShared(sessionId, ctx) !== false
+
+/** Per-name event channels. The pty ones are sent only to a session's SUBSCRIBERS, and are judged by
+ * the session's node (see `sessionShared`). */
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.ptyExit(''), sessionLifecycle],
+ [IPC.ptySize(''), sessionLifecycle],
+ [IPC.ptyClosed(''), sessionLifecycle],
+ [IPC.ptyRecycled(''), sessionLifecycle],
+ [IPC.ptyResync(''), sessionContent],
[IPC.boardLogChanged(''), (projectId, ctx) => sharedProject(projectId, ctx)],
[IPC.projectSetupEvent(''), (projectId, ctx) => sharedProject(projectId, ctx)]
]
@@ -478,33 +502,46 @@ export function narrowResponseForRole(method: string, result: unknown, ctx: Acce
return Array.isArray(result) ? result.filter((e) => sharedNode(field(e, 'nodeId'), ctx)) : []
}
+/**
+ * true = deliver this binary frame to the peer. Editors and owners get every frame. For anyone else
+ * only a pty data frame of a session whose node is in a shared project NOW: a subscription outlives
+ * `team unshare` (R45), and a frame that cannot be attributed is dropped, never guessed.
+ */
+export function filterOutboundBinary(buf: Uint8Array, ctx: AccessContext): boolean {
+ if (isEditor(ctx.role)) return true
+ const sessionId = decodePtyDataSessionId(buf)
+ return sessionId !== null && sessionContent(sessionId, 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`).
+ * applies to the next event or terminal frame. `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
+ /** Run a delivery decision. 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 (the send itself) must still propagate, so only the decision is guarded. */
+ const decide = (judge: () => boolean): boolean => {
+ try {
+ return judge()
+ } catch (err) {
+ if (!warned) {
+ warned = true
+ console.warn(`[access-policy] could not build the access context; dropping events: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ return 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)
+ if (decide(() => filterOutboundEvent(json, ctxFor(), owners))) sink.sendText(json)
+ },
+ sendBinary: (buf) => {
+ if (decide(() => filterOutboundBinary(buf, ctxFor()))) sink.sendBinary(buf)
},
- sendBinary: (buf) => sink.sendBinary(buf),
bufferedAmount: () => sink.bufferedAmount?.() ?? 0
}
}
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.ts
index 0de28f378..d5e279510 100644
--- a/src/core/relay/hosted-service.test.ts
+++ b/src/core/relay/hosted-service.test.ts
@@ -13,6 +13,7 @@ import { loadHostKey } from './host-key'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
import { decodeJoinCode } from './join-code'
import { IPC } from '../../shared/ipc'
+import { encodePtyData } from '../../shared/rpc'
import type { RelayTransport } from './relay-socket'
import type { UiSink } from '../ui-sink-registry'
@@ -57,7 +58,7 @@ afterEach(() => {
}
})
-type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectOfNode' | 'killPeer'>> & {
+type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectOfNode' | 'nodeOfSession' | 'killPeer'>> & {
recordTimers?: boolean
dataDir?: string
}
@@ -96,6 +97,8 @@ function world(opts: WorldOpts = {}) {
dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',
attach,
projectOfNode: opts.projectOfNode ?? ((id) => (id === 'n-other' ? 'Q' : 'P')),
+ // Terminal sessions: 'sess-shared' runs n-shared (project P), 'sess-other' runs n-other (Q).
+ nodeOfSession: opts.nodeOfSession ?? ((sid) => (sid === 'sess-shared' ? 'n-shared' : sid === 'sess-other' ? 'n-other' : undefined)),
projectCwd: () => '/srv/app',
fetch: (async () => { mints++; return new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 }) }) as typeof fetch,
transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT },
@@ -107,6 +110,7 @@ function world(opts: WorldOpts = {}) {
live.push({ svc, dataDir })
const join = (keys = genKeyPair(), auto = false, humanConfirms = true, onApproved?: (c: RelayClientSession) => void) => {
const frames: string[] = []
+ const bytes: Array<[string, string]> = []
const denied: string[] = []
let approved = false
let closed = 0
@@ -117,7 +121,7 @@ function world(opts: WorldOpts = {}) {
// transport runs before the client holds its socket (the client defers that confirm).
autoApprove: auto, onSas: (s) => { if (humanConfirms) s.confirm() },
onApproved: (s) => { approved = true; onApproved?.(s) }, onFrame: (j) => frames.push(j),
- onPtyData: () => {}, onClose: () => { closed++ }, onDenied: (r) => denied.push(r)
+ onPtyData: (sid, d) => bytes.push([sid, d]), onClose: () => { closed++ }, onDenied: (r) => denied.push(r)
})
const res = (id: number) => {
const f = frames.find((x) => { const m = JSON.parse(x); return m.t === 'res' && m.id === id })
@@ -125,7 +129,7 @@ function world(opts: WorldOpts = {}) {
}
const events = (channel: string) => frames.map((x) => JSON.parse(x)).filter((m) => m.t === 'ev' && m.channel === channel).map((m) => m.args[0])
return {
- c, frames, denied, keys, res, events,
+ c, frames, bytes, denied, keys, res, events,
isApproved: () => approved,
closedCount: () => closed,
req: (id: number, method: string, args: unknown[] = []) => c.send(JSON.stringify({ t: 'req', id, method, args })),
@@ -636,6 +640,41 @@ describe('hosted service — roles', () => {
})
})
+describe('hosted service — unshare stops a terminal a viewer is already watching (I3, R45)', () => {
+ it('after `team unshare`, output, size and exit of that terminal no longer reach a viewer; an editor keeps them', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const viewer = await approvedGuest(w, owner, 'viewer', 5)
+ const vSink = [...w.sinks.values()].at(-1)!
+ const editor = await approvedGuest(w, owner, 'editor', 6)
+ const eSink = [...w.sinks.values()].at(-1)!
+ const size = (n: number) => JSON.stringify({ t: 'ev', channel: IPC.ptySize('sess-shared'), args: [{ cols: n, rows: n }] })
+ const exit = JSON.stringify({ t: 'ev', channel: IPC.ptyExit('sess-shared'), args: [0] })
+ // Both are watching the shared terminal (the PtyManager sends to its subscribers' sinks).
+ for (const s of [vSink, eSink]) {
+ s.sendBinary(encodePtyData('sess-shared', 'before'))
+ s.sendText(size(1))
+ }
+ await vi.waitFor(() => expect(viewer.bytes).toEqual([['sess-shared', 'before']]))
+ expect(viewer.events(IPC.ptySize('sess-shared'))).toEqual([{ cols: 1, rows: 1 }])
+
+ await w.svc.share('P', false)
+ for (const s of [vSink, eSink]) {
+ s.sendBinary(encodePtyData('sess-shared', 'after'))
+ s.sendText(size(2))
+ s.sendText(exit)
+ }
+ await vi.waitFor(() => expect(editor.bytes).toEqual([['sess-shared', 'before'], ['sess-shared', 'after']]))
+ expect(editor.events(IPC.ptyExit('sess-shared'))).toEqual([0])
+ // A round trip on the viewer's own tunnel: anything sent to it before this answer has arrived.
+ viewer.req(1, IPC.relayHostedSelf)
+ await vi.waitFor(() => expect(viewer.res(1)).toBeDefined())
+ expect(viewer.bytes).toEqual([['sess-shared', 'before']])
+ expect(viewer.events(IPC.ptySize('sess-shared'))).toEqual([{ cols: 1, rows: 1 }])
+ expect(viewer.events(IPC.ptyExit('sess-shared'))).toEqual([])
+ })
+})
+
describe('hosted service — a session with no team entry (R27)', () => {
it('in the window between a removal’s team write and its kill, the removed peer is served NOTHING', async () => {
const kills: Array<[string, string]> = []
@@ -719,7 +758,7 @@ describe('hosted service — removal', () => {
const again = createHostedService({
dataDir: w.dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'd', hostLabel: 'x',
attach: { attach: () => 1, detach: () => {}, dispatch: async (_i, r) => ({ t: 'res', id: r.id, ok: true, result: null }), cast: () => {} },
- projectOfNode: () => undefined, projectCwd: () => undefined
+ projectOfNode: () => undefined, nodeOfSession: () => undefined, projectCwd: () => undefined
})
expect(await again.remove(pub(keys), false)).toBe('removed')
})
diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.ts
index 9ce7e2aea..56857cdf3 100644
--- a/src/core/relay/hosted-service.ts
+++ b/src/core/relay/hosted-service.ts
@@ -76,6 +76,9 @@ export interface HostedServiceDeps {
hostLabel: string
attach: PeerAttach
projectOfNode(nodeId: string): string | undefined
+ /** The node a live terminal session runs (`PtyManager.nodeOfSession`). A viewer's terminal frames
+ * are judged by it, so `team unshare` stops a stream the viewer already joined (R45). */
+ nodeOfSession(sessionId: string): string | undefined
projectCwd(projectId: string): string | undefined
/** TEST ONLY: an in-process transport per listener. Production opens a real WebSocket. */
transport?: () => RelayTransport
@@ -217,6 +220,7 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
role,
sharedProjects: shared,
projectOfNode: (nodeId) => deps.projectOfNode(nodeId),
+ nodeOfSession: (sessionId) => deps.nodeOfSession(sessionId),
projectCwds: () =>
[...shared].map((p) => deps.projectCwd(p)).filter((cwd): cwd is string => typeof cwd === 'string' && cwd.length > 0),
realpath
diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.ts
index b64042e68..549d7feed 100644
--- a/src/main/remote/hosted-join.test.ts
+++ b/src/main/remote/hosted-join.test.ts
@@ -671,7 +671,7 @@ function hostedWorld() {
}
const svc = createHostedService({
dataDir: dir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',
- attach, projectOfNode: () => 'P', projectCwd: () => '/srv/app',
+ attach, projectOfNode: () => 'P', nodeOfSession: () => undefined, projectCwd: () => '/srv/app',
fetch: (async () => new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })) as typeof fetch,
transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT }
})
diff --git a/src/server/hosted-e2e.test.ts b/src/server/hosted-e2e.test.ts
index b08507196..a421c781f 100644
--- a/src/server/hosted-e2e.test.ts
+++ b/src/server/hosted-e2e.test.ts
@@ -135,6 +135,8 @@ function teammate(code: JoinCode, transport: RelayTransport, keys: KeyPair, pinn
const frames: Frame[] = []
const frameWaiters: Array<{ test: (f: Frame) => boolean; resolve: (f: Frame) => void }> = []
const byteWaiters: Array<{ sessionId: string; resolve: (d: string) => void }> = []
+ /** Every terminal chunk received, in order: "received nothing" is as much a result as a chunk. */
+ const received: Array<[string, string]> = []
const denied: string[] = []
let approve!: () => void
const approved = new Promise<void>((r) => {
@@ -165,6 +167,7 @@ function teammate(code: JoinCode, transport: RelayTransport, keys: KeyPair, pinn
}
},
onPtyData: (sessionId, data) => {
+ received.push([sessionId, data])
for (const w of [...byteWaiters]) {
if (w.sessionId !== sessionId) continue
byteWaiters.splice(byteWaiters.indexOf(w), 1)
@@ -179,6 +182,7 @@ function teammate(code: JoinCode, transport: RelayTransport, keys: KeyPair, pinn
c,
approved,
denied,
+ received,
/** One RPC round trip over the E2EE tunnel. */
call(method: string, args: unknown[] = []): Promise<Frame> {
const id = nextId++
@@ -395,6 +399,18 @@ describe.skipIf(process.platform === 'win32')('hosted team relay, end to end on
expect(owner.denied).toEqual([])
expect(guest.denied).toEqual([])
+ // ---- 7b. `team unshare`: the viewer stays connected, but the terminal it is already watching
+ // goes quiet for it at once (R45); its owner keeps the output. The session's node is looked up
+ // through the real PtyManager on every frame.
+ await admin(dataDir, { cmd: 'share', projectId: SHARED, on: false })
+ const ownerAfterUnshare = owner.bytes(ownerSessionId)
+ spawned[0].onDataCb?.('after the unshare\r\n')
+ expect(await step('owner receives output after the unshare', ownerAfterUnshare)).toContain('after the unshare')
+ // One round trip on the viewer's own tunnel: anything sent to it before this answer has arrived.
+ expect(await guest.call(IPC.relayHostedSelf)).toMatchObject({ ok: true, result: { role: 'viewer' } })
+ expect(guest.received.map(([, d]) => d).join('')).toContain('hello from the owner')
+ expect(guest.received.map(([, d]) => d).join('')).not.toContain('after the unshare')
+
// ---- 8. The viewer's desktop goes away: its membership stays, its connection does not, and the
// owner's terminal keeps running for the owner.
const left = owner.event(IPC.presencePeer, (d) => d.op === 'leave')
diff --git a/src/server/index.ts b/src/server/index.ts
index 9a7e0ba82..2675f761b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -883,6 +883,9 @@ export async function startServer(
// persistedCanvases() scan re-parses every local project's file (measured 4.5 ms per call at
// 20 projects x 100 nodes).
projectOfNode: (nodeId) => workspaceStore.projectIdForNode(nodeId),
+ // A viewer's terminal frames are judged by the session's node, per frame (`team unshare` must
+ // stop a stream the viewer already joined). One map lookup.
+ nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),
projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),
// TEST ONLY seams (see ServerConfig): never set by resolveConfig, so production dials the relay
// and mints against API_BASE with the global fetch.
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 0845d5141..c8a7d2c12 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -139,3 +139,13 @@ export function decodePtyData(buf: Uint8Array): { sessionId: string; data: strin
data: dec.decode(buf.subarray(3 + sidLen))
}
}
+
+/** The session a pty data frame belongs to, without decoding its payload (a per-frame check on a
+ * hot path: the hosted relay's viewer sink). Null when the buffer is not a pty data frame. Same
+ * header rules as `decodePtyData`. */
+export function decodePtyDataSessionId(buf: Uint8Array): string | null {
+ if (buf.length < 3 || buf[0] !== PTY_DATA_FRAME) return null
+ const sidLen = (buf[1] << 8) | buf[2]
+ if (3 + sidLen > buf.length) return null
+ return dec.decode(buf.subarray(3, 3 + sidLen))
+}