Merge pull request #8303 from deepseek-harness/feat/liveshare-owner-state-claim
fix(liveshare): claim the owner state per running host
This commit is contained in:
1 parent
fbcc66220c
commit
99208d19d9
38 files changed
+1481
-128
No files matched your search
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-11-liveshare-owner-state-host-claim.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state:
|
||||
en: fe99c1b2c07f8b44
|
||||
zh: 127e08e92ec5fefe
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/problem:
|
||||
en: 547680b92db88db1
|
||||
zh: 46db5e6498aa1a25
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/decision:
|
||||
en: 16acf8f131c35b82
|
||||
zh: afed5f4b4c0dcb7a
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/alternatives-considered:
|
||||
en: 451b3983c32e8c1d
|
||||
zh: 3b44b6b8782db1be
|
||||
/agent-note-one-host-claims-the-liveshare-owner-state/consequences:
|
||||
en: b88da2957ada40b3
|
||||
zh: 2d624911e24755e5
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: one host claims the LiveShare owner state
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-11-liveshare-owner-state-host-claim.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The LiveShare owner state — the persisted shares, the Relay registrations they hold, and the forks recorded beside them — is addressed by the Host's DSH home, not by the process serving it. A second Host that starts on that home restores the same shares and re-registers them with the Liveshare server, which moves each registration onto the new connection. The earlier Host's authority reads then answer for a registration the server has moved, fence the share, and, with it, stop the owner's own turn. The state needed one named owner per directory that does not depend on every Host agreeing to ignore the others.
|
||||
|
||||
## Decision
|
||||
|
||||
`claimOwnerHost` (packages/experimental/liveshare/src/host/owner-host-claim.ts) writes `owner-host.json` beside the owner state file and names the process serving it. The holder restores, registers, and changes the shares; every other Host loads the records and publishes nothing. The claim is taken once at mount: a Host that loses it to a successor detects that on its next read, because a share operation re-reads the file instead of trusting the claim it took. A lost claim turns every modifying `liveshareShares` operation into the typed refusal `liveshareShares/owner-state-held`, and leaves reads available, so a non-holding Host still shows the owner what is shared. It imports a credential — its own sign-in — but claims and re-registers nothing.
|
||||
|
||||
The rules are the ones the [session write lease](2026-08-31-cross-process-session-write-lease.md) settled: ownership carries no expiry, contention is a typed answer rather than a crash, and a record left by a process that is gone is reclaimed. Three properties differ, because this directory is not session data:
|
||||
|
||||
- **The claim is advisory, and it gates Relay registrations rather than file writes.** The state file's own registry locking keeps concurrent writes from dropping durable entries, so the claim protects no share data and no Session log. Its whole purpose is that one process owns the server-side registrations at a time.
|
||||
- **There is deliberately no deadline.** A deadline exists to expropriate a stalled holder, and a wedged Host here keeps only its own registrations; a takeover would register the shares from a second connection while the stalled holder still believes it owns them. A holder that stops serving therefore keeps the state until its process exits.
|
||||
- **A record naming this process is reclaimed.** Every Host in one process shares the same owner state, so a second mount inside one process must not find itself fenced out by its own pid.
|
||||
|
||||
The record is published as one whole file: it is written under a temporary name and then hard-linked to the claim path, so the link publishes the record it names or fails because a claim is there, and no reader ever sees a half-written claim. Taking the claim against a live holder throws `OwnerHostClaimHeldError`; the Host reports that holder's pid and continues without the state rather than failing to start. Teardown releases the claim last, after the tunnel and worker registrations have stopped, so a successor cannot start registering the same shares while the holder is still withdrawing them.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A lease with an expiry, renewal, and takeover** — the shape a distributed lock usually takes, and the one this repository's Session writes replaced with a kernel lock. Renewal traffic and a takeover race would buy nothing here: no write is torn by a second owner, and the only cost of a stalled holder is that its own shares serve until the process exits.
|
||||
|
||||
**Doing nothing and letting every Host serve the shares** — the defect itself: whichever Host registers last wins the registration, and the other fences the share and stops the owner's turn, so two running Hosts make the owner's own Session stop without anyone asking for it.
|
||||
|
||||
**A kernel lock held for the life of the process** — the Session write lease's own mechanism, which recovers on crash with no record at all. It cannot express "this Host lost the state to a successor" to a Host that must keep running and serving reads, and it would report contention by failing acquisition rather than by naming a pid the owner can act on. The record is also what a later Host reads to say which process to stop.
|
||||
|
||||
**Refusing to start beside a live holder** — a second Host is a legitimate way to look at what this machine shares, and failing its mount would take the rest of that DSH home's startup down with the claim.
|
||||
|
||||
## Consequences
|
||||
|
||||
Two Hosts on one DSH home now have one authoritative server registration each share, and the non-holding Host answers a modifying operation with a refusal that names the holder rather than silently diverging. The holder's death frees the state at the next Host start; until then the state is unreachable, which is the deliberate cost of not expropriating a stalled holder. Pid reuse can name the claim's holder wrongly: the next Host then runs without the shares until that unrelated process exits or the record is removed, and nothing is lost when it recovers. The claim compares nothing outside this DSH home, so it remains an advisory guard for one user's state directory, not a multi-host authorization service — nothing stops a Host pointed at another home from registering the same shares with the server.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note:单一宿主认领 LiveShare 房主状态
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-11-liveshare-owner-state-host-claim.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
LiveShare 的房主状态——持久化的分享、它们持有的 Relay 注册、以及旁边记录的 fork——按宿主所在的 DSH home 寻址,而不是按服务它的进程寻址。在同一 home 上启动的第二个宿主会恢复同样的分享并把它们重新注册到 Liveshare 服务器,服务器随之把每条注册挪到新连接上。先前宿主的权限读取于是对着一条已被挪走的注册作答,围栏该分享,并连带停掉房主自己的回合。这份状态需要一个按目录命名、且不依赖各宿主自觉忽略彼此的归属者。
|
||||
|
||||
## 决定
|
||||
|
||||
`claimOwnerHost`(packages/experimental/liveshare/src/host/owner-host-claim.ts)在房主状态文件旁写 `owner-host.json`,记录服务它的进程。持有者恢复、注册并改动分享;其它宿主只加载记录,不发布任何东西。认领在挂载时只取一次:被后继者夺走的宿主会在下一次读取时发现,因为分享操作会重读该文件,而不是相信启动时取到的认领。丢失的认领会把每个会修改记录的 `liveshareShares` 操作变成类型化的拒绝 `liveshareShares/owner-state-held`,读操作保持可用,因此非持有宿主仍能向房主展示哪些内容被分享。它会导入凭据——那是它自己的登录——但不认领、也不重新注册任何东西。
|
||||
|
||||
规则沿用[会话写租约](2026-08-31-cross-process-session-write-lease.zh.md)确立的那套:所有权不设过期、竞争给出类型化回答而不是崩溃、进程已消失留下的记录会被收回。有三处不同,因为这个目录不是会话数据:
|
||||
|
||||
- **认领是建议性的,且它把关的是 Relay 注册而不是文件写入。** 状态文件自身的 registry 文件锁已防止并发写入丢掉持久条目,所以这条认领不保护任何分享数据或会话日志。它的全部目的是让一个进程在某一时刻独有服务器端的注册。
|
||||
- **刻意没有过期时限。** 时限存在的意义是夺取卡住的持有者,而卡住的宿主在这里只持有自己的注册;夺取会让分享从第二条连接重新注册,而卡住的持有者仍相信自己拥有它们。因此停止服务的持有者会一直持有该状态,直到它的进程退出。
|
||||
- **记录指向本进程时会被收回。** 同一进程内的所有宿主共享同一份房主状态,所以同一进程里的第二次挂载不能因为自己的 pid 而被挡在外面。
|
||||
|
||||
记录作为整份文件发布:先写到临时名,再硬链接到认领路径,于是该链接要么发布它所命名的记录,要么因已有认领而失败,任何读取方都看不到写了一半的认领。对活跃持有者认领会抛出 `OwnerHostClaimHeldError`;宿主报告该持有者的 pid 并在没有该状态的情况下继续,而不是启动失败。退出时最后才释放认领,即在 tunnel 与 worker 的注册停止之后,这样后继者不会在持有者仍在撤销注册时就开始注册同样的分享。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**带过期、续期与夺取的租约**——分布式锁通常的形态,也是本仓库的会话写入用内核锁替换掉的那个。续期流量和夺取竞争在这里买不到任何东西:第二个所有者不会撕裂任何写入,卡住的持有者的唯一代价是它自己的分享服务到进程退出为止。
|
||||
|
||||
**什么都不做,让每个宿主都服务这些分享**——这正是那个缺陷:最后注册的宿主赢得注册,另一个宿主围栏该分享并停掉房主的回合,于是两个运行中的宿主会让房主自己的会话在无人要求的情况下停下。
|
||||
|
||||
**持进程终身的内核锁**——会话写租约自己的机制,崩溃后无需任何记录即可恢复。它无法向一个必须继续运行并服务读的宿主表达「该宿主已被后继者取代」;而且它只能以取锁失败来表达竞争,而不是给出一个房主能据以行动的 pid。记录同时也是后来的宿主用来告诉用户该停掉哪个进程的东西。
|
||||
|
||||
**活跃持有者存在时拒绝启动**——第二个宿主是查看本机分享了什么内容的正当方式,让它的挂载失败会把该 DSH home 其余部分的启动一起拖下水。
|
||||
|
||||
## 后果
|
||||
|
||||
同一 DSH home 上的两个宿主现在对每条分享只有一条权威的服务器注册,非持有宿主对修改类操作给出点名持有者的拒绝,而不是悄悄分叉。持有者死亡后,下一次宿主启动会释放该状态;在那之前状态不可达,这是不夺取卡住的持有者所刻意付出的代价。pid 复用可能把认领的持有者认错:下一个宿主于是没有这些分享地运行,直到那个无关进程退出或记录被移除,恢复时不会有任何东西丢失。认领不比较这个 DSH home 之外的任何东西,因此它仍是一个用户状态目录的建议性守卫,而不是多宿主授权服务——没有任何机制阻止一个指向其它 home 的宿主把同样的分享注册到服务器上。
|
||||
@@ -15,11 +15,11 @@
|
||||
en: 7174fa32aa611279
|
||||
zh: e85e8142a0e9e650
|
||||
/liveshare/retries-recovery-and-revocation:
|
||||
en: 6b1346e73ab6eab9
|
||||
zh: 888cfc08c6bc8522
|
||||
en: 892231edc9b3c986
|
||||
zh: e8c07d6e1a0c084c
|
||||
/liveshare/constraining-a-shared-session:
|
||||
en: 7fbb31bbc29817d6
|
||||
zh: 0a9542ab1d48a9e6
|
||||
en: 89a9ba76a3d7db1e
|
||||
zh: d74f65e8d0e7346a
|
||||
/liveshare/viewer-states:
|
||||
en: b8bcb009e419fa25
|
||||
zh: 31c4662b52e99ea7
|
||||
@@ -32,7 +32,7 @@ Cold source and child activation uses the Host’s ordinary Agent lookup, not a
|
||||
|
||||
One logical fork request may be sent more than once. Its identity binds the trusted viewer, the share, the source, and the caller's operation id; the boundary is compared against that identity rather than folded into it, so a retry repeats the child it already produced, an identity naming another boundary conflicts instead of silently receiving the earlier child, and the reservation is durable before any child exists. The host records the child the owner's fork answer returned, and a retry of a recorded operation replays that answer. The owner's `SessionForkRequest` mints the child id, so a host that dies between creating the child and recording it cannot name that child on retry and creates a second one; closing that window needs a Session Controller request that accepts a caller-supplied child identity.
|
||||
|
||||
Child tool guards recheck the share’s current mode, expiry, viewer admission, and revocation record. Viewer withdrawal cancels affected child work and pending calls. A `write` to `view` downgrade denies later writes through the write guard without granting any new tool, and does not promise immediate cancellation of a running turn. Removing a share revokes recorded children and stops the Session's running turn; the source enforcement layer is released once no share over the Session is left, and with Agent disposal. Revoked children retain their logs, and the source’s owner-visible history is never rewritten.
|
||||
Child tool guards recheck the share’s current mode, expiry, viewer admission, and revocation record. Viewer withdrawal cancels affected child work and pending calls. A `write` to `view` downgrade denies later writes through the write guard without granting any new tool, and does not promise immediate cancellation of a running turn. Removing a share revokes recorded children and stops the Session's running turn when a share viewer started it; the source enforcement layer is released once no share over the Session is left, and with Agent disposal. Revoked children retain their logs, and the source’s owner-visible history is never rewritten.
|
||||
|
||||
## Constraining a shared Session
|
||||
|
||||
@@ -40,7 +40,7 @@ Every share lets its viewer drive the *source* Session through the normal prompt
|
||||
|
||||
The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A refusal records the same identity whether the guard or a confined tool decides: a path outside the grant is `FsError` `FS_SANDBOX_DENIED`, and other grant refusals are `LiveshareForkDeniedError` with a `FORK_*` code.
|
||||
|
||||
Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs.
|
||||
Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. Only a Relay answering that it has no such share — a 404 or a 410 — withdraws the share: it ends the grant it held and stops the turn a share viewer started. A read that the Relay refuses — a 401 or a 403 — ends admission without withdrawing the share: no further viewer input is served, the calls and streams already open are released, and the owner's own turn keeps running. A read that times out, fails with another status, or answers unreadably leaves the held statement and everything it admits alone, while viewer ingress stays refused until a read succeeds again. When a grant does end, the in-memory viewer-start marker decides what stops: a turn a share viewer started is stopped, while the owner's own turn keeps running, judged on the origin recorded for that turn in its own source Session. A reader's own Stop reaches the Session controller like any other input, so it still stops whatever turn the Session is running.
|
||||
|
||||
Confined file tools resolve every path their own arguments declare, check that the granted root contains each result, and delegate with the target’s canonical path. A pathless `glob` or `grep` searches the Session’s working directory, which the replacement supplies and checks like a named path; a `present` call checks every file it lists; the tools with no local file effect are delegated unchanged. Bounded edits run the same containment check, use `fs/edit-intent`, and publish the version `editText` returns; bounded writes use `fs/write-intent` and publish the version `writeText` returns. After the asynchronous intent wait, the Host resolves the current Session sandbox policy and rechecks share authority. It passes that policy as the fifth `editText` or `writeText` argument, after `signal`, so the sandboxing backend fences the mutation by it. Containment is checked by path, so a directory inside the grant that a local process replaces with a symlink between the check and the open can redirect the operation; anchoring operations to a directory handle is deferred to a separate change.
|
||||
|
||||
@@ -90,7 +90,7 @@ The Gateway decides each call through remote access, so a `share-viewer` Peer is
|
||||
@Remote('addSessions') addSessions(request: AddShareSessionsRequest): Promise<ShareSessions>
|
||||
|
||||
/**
|
||||
* Refresh titles and Liveshare server authority, then list this host's shares.
|
||||
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
|
||||
* @returns Every share this host publishes.
|
||||
*/
|
||||
@Remote('list') list(): Promise<OwnerShareList>
|
||||
|
||||
@@ -32,7 +32,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检
|
||||
|
||||
同一个逻辑 fork 请求可能被发送多次。其身份绑定可信 viewer、分享、源会话与调用方的操作 id;边界是与该身份比较而非折入其中,因此重试会重复它已经产生的分叉会话,同一身份指向另一个边界会冲突而不是悄悄拿到更早的分叉会话,且预留在任何分叉会话存在之前就已持久化。宿主机记录 owner 的 fork 应答返回的分叉会话,重试已记录的操作会重放该应答。owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在创建分叉会话与记录它之间崩溃的宿主机重试时无法指名该分叉会话,会再创建一个;要关闭这一窗口,需要 Session Controller 的请求接受调用方提供的分叉会话身份。
|
||||
|
||||
分叉会话工具守卫重新检查分享当前模式、有效期、查看者准入与撤销记录。撤回查看者会取消受影响的分叉会话工作与未决调用。`write` 降级为 `view` 后,写入守卫拒绝后续写入,不授予任何新工具,也不承诺立即取消正在运行的轮次。移除分享撤销已记录分叉会话并停止该会话正在运行的轮次;源执行层在该会话不再有任何分享时释放,并随 Agent 释放。已撤销分叉会话保留日志,源会话所有者可见历史绝不改写。
|
||||
分叉会话工具守卫重新检查分享当前模式、有效期、查看者准入与撤销记录。撤回查看者会取消受影响的分叉会话工作与未决调用。`write` 降级为 `view` 后,写入守卫拒绝后续写入,不授予任何新工具,也不承诺立即取消正在运行的轮次。移除分享撤销已记录分叉会话,并在该轮次由查看者发起时停止它;源执行层在该会话不再有任何分享时释放,并随 Agent 释放。已撤销分叉会话保留日志,源会话所有者可见历史绝不改写。
|
||||
|
||||
## 约束共享会话
|
||||
|
||||
@@ -40,7 +40,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检
|
||||
|
||||
安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。无论由守卫还是受限工具判定,拒绝都记录同一标识:授权范围外的路径为 `FsError` `FS_SANDBOX_DENIED`,其他授权拒绝为 `LiveshareForkDeniedError` 及 `FORK_*` code。
|
||||
|
||||
每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。
|
||||
每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。只有 Relay 明确回答没有该分享——404 或 410——才撤回分享:结束它持有的授权,并停止查看者发起的轮次。Relay 拒绝的读取——401 或 403——结束准入而不撤回分享:不再服务任何查看者输入,已打开的调用与流被释放,所有者自己的轮次继续运行。读取超时、以其它状态失败或响应无法解析时保留所持有的声明及其允许的一切,而查看者入口在读取重新成功前保持拒绝。授权确实结束时,由内存中的查看者轮次标记决定停止什么:查看者发起的轮次会被停止,所有者自己发起的轮次继续运行,并按该轮次在各自源会话中记录的来源判定。查看者自己的 Stop 与其他输入一样进入会话控制器,因此仍会停止该会话当前运行的轮次。
|
||||
|
||||
受限文件工具解析其自身参数声明的每个路径,检查获授根目录包含每个目标,再以目标的规范路径委托。无路径的 `glob` 或 `grep` 搜索会话的工作目录,由替代定义补齐并按命名路径一样检查;`present` 调用检查它列出的每个文件;无本地文件副作用的工具原样委托。有界编辑执行同样的包含检查,使用 `fs/edit-intent`,并发布 `editText` 返回的版本;有界写入使用 `fs/write-intent`,并发布 `writeText` 返回的版本。异步意图等待后,Host 解析当前会话沙箱策略并重新检查分享授权。该策略作为 `editText` 或 `writeText` 的第五个参数,位于 `signal` 之后,由沙箱后端据此限制变更。包含关系按路径检查,若本地进程在检查与打开之间把获授范围内的目录换成符号链接,操作可能被改指别处;基于目录句柄锚定操作留待单独变更引入。
|
||||
|
||||
@@ -90,7 +90,7 @@ The Gateway decides each call through remote access, so a `share-viewer` Peer is
|
||||
@Remote('addSessions') addSessions(request: AddShareSessionsRequest): Promise<ShareSessions>
|
||||
|
||||
/**
|
||||
* Refresh titles and Liveshare server authority, then list this host's shares.
|
||||
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
|
||||
* @returns Every share this host publishes.
|
||||
*/
|
||||
@Remote('list') list(): Promise<OwnerShareList>
|
||||
|
||||
@@ -36,6 +36,18 @@ export const LIVESHARE_CAPABILITIES = [
|
||||
/** One optional behavior this build offers the Relay; a peer compiles against the names it knows. */
|
||||
export type LiveshareCapability = typeof LIVESHARE_CAPABILITIES[number]
|
||||
|
||||
/**
|
||||
* Operating systems an owner may report at registration.
|
||||
*
|
||||
* A fixed enum rather than free text: the Relay matches three names instead of normalising spellings
|
||||
* that drift between peers, the picker renders an icon and a label from the same table, and the value
|
||||
* names a display class rather than a kernel, distribution, or architecture.
|
||||
*/
|
||||
export const LIVESHARE_OWNER_PLATFORMS = ['macos', 'windows', 'linux'] as const
|
||||
|
||||
/** One operating-system class an owner may report; absent means the owner reported none. */
|
||||
export type LiveshareOwnerPlatform = typeof LIVESHARE_OWNER_PLATFORMS[number]
|
||||
|
||||
/**
|
||||
* The permission facts a share publishes.
|
||||
*
|
||||
@@ -67,6 +79,13 @@ export interface TunnelShareSpec extends SharePermissions {
|
||||
readonly ownerDisplayName: string
|
||||
/** Display-only: the owner's DSH version shown on the Relay share picker. */
|
||||
readonly dshVersion?: string
|
||||
/**
|
||||
* Display-only: the operating system this owner runs on, shown beside the share title.
|
||||
*
|
||||
* Absent means this owner reports no platform: the build runs on one outside
|
||||
* {@link LIVESHARE_OWNER_PLATFORMS}, and the Relay shows no platform rather than guessing.
|
||||
*/
|
||||
readonly platform?: LiveshareOwnerPlatform
|
||||
/**
|
||||
* Stable id of the owner DSH instance that published this share. Not display-only: the Relay groups
|
||||
* shares of the same owner instance by it.
|
||||
@@ -534,6 +553,7 @@ function isTunnelShareSpec(value: unknown): value is TunnelShareSpec {
|
||||
&& (value.ownerProviderId === undefined || typeof value.ownerProviderId === 'string')
|
||||
&& (value.ownerTenantId === undefined || typeof value.ownerTenantId === 'string')
|
||||
&& (value.dshVersion === undefined || typeof value.dshVersion === 'string')
|
||||
&& isOwnerPlatform(value.platform)
|
||||
&& (value.ownerInstanceId === undefined || typeof value.ownerInstanceId === 'string')
|
||||
&& (value.allowsFork === undefined || typeof value.allowsFork === 'boolean')
|
||||
&& (mode === undefined || mode === 'view' || mode === 'write')
|
||||
@@ -546,6 +566,16 @@ function isTunnelShareSpec(value: unknown): value is TunnelShareSpec {
|
||||
|| (typeof value.expiresAt === 'string' && Number.isFinite(Date.parse(value.expiresAt))))
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a reported owner platform at the IPC parser.
|
||||
* @param value Candidate field.
|
||||
* @returns True when it is absent or names one of {@link LIVESHARE_OWNER_PLATFORMS}.
|
||||
*/
|
||||
function isOwnerPlatform(value: unknown): value is LiveshareOwnerPlatform | undefined {
|
||||
return value === undefined
|
||||
|| LIVESHARE_OWNER_PLATFORMS.some(platform => platform === value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the actor the Relay asserts on one forwarded request.
|
||||
* @param value Candidate actor.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
LIVESHARE_OWNER_PLATFORMS,
|
||||
parseRelayFrame,
|
||||
parseShareAccessState,
|
||||
parseTunnelWorkerCommand,
|
||||
@@ -197,6 +198,11 @@ describe('tunnel worker commands', () => {
|
||||
{ ...spec(), ownerProviderId: 4 },
|
||||
{ ...spec(), ownerTenantId: 4 },
|
||||
{ ...spec(), dshVersion: 4 },
|
||||
{ ...spec(), platform: 4 },
|
||||
{ ...spec(), platform: 'darwin' },
|
||||
{ ...spec(), platform: 'macOS' },
|
||||
{ ...spec(), platform: null },
|
||||
{ ...spec(), platform: '' },
|
||||
{ ...spec(), ownerInstanceId: 4 },
|
||||
{ ...spec(), ownerCredential: 4 },
|
||||
{ ...spec(), expiresAt: 4 },
|
||||
@@ -221,6 +227,14 @@ describe('tunnel worker commands', () => {
|
||||
expect(parseTunnelWorkerCommand(addShare(allOptional))).toBeDefined()
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), accessMode: 'open' }))).toBeDefined()
|
||||
})
|
||||
|
||||
it('accepts the three owner platforms and nothing else', () => {
|
||||
for (const platform of LIVESHARE_OWNER_PLATFORMS) {
|
||||
expect(parseTunnelWorkerCommand(addShare({ ...spec(), platform })), platform)
|
||||
.toMatchObject({ share: { platform } })
|
||||
}
|
||||
expect(parseTunnelWorkerCommand(addShare(spec())), 'absent').toMatchObject({ share: {} })
|
||||
})
|
||||
})
|
||||
|
||||
describe('tunnel worker events', () => {
|
||||
|
||||
@@ -30,14 +30,14 @@
|
||||
en: e1bad148f61e1e12
|
||||
zh: 0197ba5379c21cb2
|
||||
/deepseek-ai-dsh-experimental-liveshare/use-this-package/session-tiers:
|
||||
en: 2052fd7c4e9c3f98
|
||||
zh: 5ef2ac5ad9ec7990
|
||||
en: f6c3a858d5120943
|
||||
zh: 2260b9f6faacbae7
|
||||
/deepseek-ai-dsh-experimental-liveshare/understand-the-implementation:
|
||||
en: 37d649ff38fca348
|
||||
zh: c73e526eac1e3778
|
||||
/deepseek-ai-dsh-experimental-liveshare/further-exploration:
|
||||
en: 0570170704bbe5b6
|
||||
zh: 832f86024b26e5b3
|
||||
en: 7bb2e8bd8c074cd6
|
||||
zh: 6de36c3b450e61e2
|
||||
/deepseek-ai-dsh-experimental-liveshare/model-experience:
|
||||
en: 3b248c02220df02d
|
||||
zh: 9d752fb049a04e83
|
||||
@@ -45,8 +45,8 @@
|
||||
en: 22a9da7d4b23a015
|
||||
zh: 5700901ba5f655c8
|
||||
/deepseek-ai-dsh-experimental-liveshare/known-limitations-and-deferred-work:
|
||||
en: d51c0895166207f0
|
||||
zh: 82cd69842c8f74d6
|
||||
en: 78a389977c1631dc
|
||||
zh: fd66c3815ef26485
|
||||
/deepseek-ai-dsh-experimental-liveshare/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 8ec3e73528ddb1a6
|
||||
@@ -97,7 +97,7 @@ Attachment uploads are neither a tier nor part of the fork switch: they follow v
|
||||
|
||||
Shareable viewer methods come from installed plugins' live Remote methods, enumerated from the Host's Typert registry in [`shareable-catalog.ts`](src/host/shareable-catalog.ts). DSH core service namespaces are excluded ([`EXCLUDED_SHARE_NAMESPACES`](src/host/shareable-catalog.ts) lists them), and so are components of a core profile bundle as the plugin manager reports them; other user-installed and DSH experimental plugins remain. The owner may open every installed plugin at once, or set each plugin to none, all its methods, or a subset. There is no read/write distinction: a method is callable only where the live catalog and that share's own policy name it, on the resources the reader can see.
|
||||
|
||||
The Owner Gateway decides each call on the Session and Workspace it names and refuses a call whose target is missing or invalid. The viewer's Session list and workspace membership are trimmed to the source and the children that viewer owns. The page reads each Session's own answer from the reader's access snapshot, so a selection change never carries the previous Session's permission across. Unknown or unreadable modes fail closed. The Owner rechecks admission for source and child calls; revocation cancels the affected calls and streams, and a share whose admission narrows stops the shared Session's running turn. The page distinguishes authentication, access, expiry, stopped shares, offline owners, and transport failures, and retries only the failures classified as repeatable.
|
||||
The Owner Gateway decides each call on the Session and Workspace it names and refuses a call whose target is missing or invalid. The viewer's Session list and workspace membership are trimmed to the source and the children that viewer owns. The page reads each Session's own answer from the reader's access snapshot, so a selection change never carries the previous Session's permission across. Unknown or unreadable modes fail closed. The Owner rechecks admission for source and child calls; revocation cancels the affected calls and streams, and a share whose admission narrows stops the running turn a share viewer started. The page distinguishes authentication, access, expiry, stopped shares, offline owners, and transport failures, and retries only the failures classified as repeatable.
|
||||
|
||||
-----
|
||||
|
||||
@@ -139,6 +139,7 @@ The external Liveshare server's service, stores, OAuth provider, and deployment
|
||||
|
||||
- [LiveShare subsystem](../../../docs/subsystems/liveshare.md)
|
||||
- [Owner decision record](../../../.agents/notes/implemented/feature/2026-09-13-liveshare-protocol-and-owner-surfaces.md)
|
||||
- [One host claims the owner state](../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md)
|
||||
- [Web bundle](../../bundle/web-app/README.md)
|
||||
|
||||
-----
|
||||
@@ -165,10 +166,10 @@ Viewer prompts enter the shared Session as ordinary user input, so they extend t
|
||||
- Endpoint capabilities enumerate installed plugins' Remote methods from the live Typert registry in [`shareable-catalog.ts`](src/host/shareable-catalog.ts); DSH core service namespaces are excluded. There is no sandbox around a method call and no read/write classification: granting a method trusts that installed plugin's code, which runs in the Host process. A selected method is callable by every authenticated share viewer on the resources the policy binds, across the `global`, `session`, and `workspace` resource kinds.
|
||||
- The owner selects installed-plugin methods in the share panel through a global switch and per-plugin rows. The global switch is `none` (open nothing), `custom` (follow the per-plugin list), or `all` (open every method the live catalog offers). Each plugin is then off, all its methods, or a subset; a partial selection stores an explicit method list, so methods the catalog adds later stay closed until the owner saves again. Plugin rows use the package's localized title when one exists and otherwise fall back to the package segment or namespace; search and bounded scrolling keep a large catalog usable. The selection is share-wide: every admitted viewer may call a selected method on the resources the policy binds, and per-viewer method levels are not established. Method authorization is independent of the session tier; the core share roles still decide Session and Workspace calls. A selection naming a method the catalog no longer offers exposes nothing but stays stored until the owner saves again.
|
||||
- A Workspace that stops holding a Session the reader can see leaves the reader's Workspace feed only at that Workspace's or the Workspace order's next change ([remote access limitation](../../api/remote-access/README.md#known-limitations-and-deferred-work)).
|
||||
- Registry file locking prevents concurrent file writes from dropping durable entries, but each registry reads its own in-memory snapshot. Owner share-state updates and gateway ownership are not coordinated across Hosts; use one active Owner Host per home. This is not a multi-host authorization service.
|
||||
- Registry file locking prevents concurrent file writes from dropping durable entries, but each registry reads its own in-memory snapshot. One running Host claims the owner state directory through `owner-host.json`, so a second Host on the same home reads the shares without registering or changing them and refuses every `liveshareShares` operation that would change a record or contact the Liveshare server for one with `liveshareShares/owner-state-held`; adding Sources to a share in the dialog, the share list, and the audit read included. It still imports a credential, which is its own sign-in, but that import claims and re-registers nothing. A Host that a successor replaced detects it on its next share operation and refuses the same way. The claim is advisory, is reclaimed once its process is gone, and is still not a multi-host authorization service.
|
||||
- No runtime invariant companion is published: authorization is checked in the operations themselves, and this package has no separate invariant observer.
|
||||
- A worker restart re-registers retained shares but does not replay viewer streams; viewers recover through their transport. Registration refusals 401, 403, 410, and 426 stop that share’s reconnect loop until something registers it again: republishing or changing its tier does, and so does storing a credential for that Liveshare server, which registers the shares that address left offline. A restore presents the credential this host holds for the share’s Liveshare server whatever this host’s own expiry read says, because the Liveshare server renews the login behind it and only the Liveshare server decides whether that credential still authorizes; a new share is still refused on that same local read.
|
||||
- The access mode grants `view` admission, while effective fork/write authority comes from the share mode. Per-viewer execution levels and immediate cross-instance stop/cancellation completion are not established; cancellation cannot undo committed writes. A write-to-readonly snapshot denies later writes but does not promise immediate cancellation of a running child turn.
|
||||
- The access mode grants `view` admission, while effective fork/write authority comes from the share mode. Per-viewer execution levels and immediate cross-instance stop/cancellation completion are not established; cancellation cannot undo committed writes. A grant that ends stops the running turn of each source Session only when a share viewer started it, so the owner's own turn keeps running; a turn this host cannot attribute is stopped with the grant. A write-to-readonly snapshot denies later writes but does not promise immediate cancellation of a running child turn.
|
||||
- Final assembled snapshot verification remains required before the feature is ready for release.
|
||||
- On the viewer page, client reads that bypass the Connection carrier (deliverable reads, open-in-app, PDF assets, HMR events) reach the Liveshare server rather than the Owner; the index document's root-absolute manifest and icon links do not resolve under a Liveshare server prefix.
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ Liveshare 服务端地址在首次使用时设置:在分享弹窗的地址输
|
||||
|
||||
可分享给 viewer 的方法是已安装插件注册的 Remote 方法,由 Host 的 Typert registry 在 [`shareable-catalog.ts`](src/host/shareable-catalog.ts) 动态枚举。DSH 核心服务命名空间被排除([`EXCLUDED_SHARE_NAMESPACES`](src/host/shareable-catalog.ts) 列出这些命名空间),插件管理器报告为核心 profile bundle 组件的插件也被排除;其他用户安装的插件和 DSH 实验性插件保留。所有者可以一次性开放全部已安装插件,也可以按插件设为不可用、全部方法或部分方法。这里没有读写之分:只有当前目录与该 share 的策略同时点名某个方法、且资源对读者可见时,该方法才可被调用。
|
||||
|
||||
Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒绝目标缺失或无效的调用。查看页的会话列表和工作区成员裁剪为源会话及该查看者自己的分叉会话。页面从读者的访问快照读取每个会话自己的答案,因此切换选择不会把前一会话的权限带过去。未知或无法读取的模式默认拒绝。Owner 为源会话与分叉会话调用重新检查准入;撤权会取消受影响的调用和流,分享准入收窄时还会停止共享会话正在运行的轮次。页面区分认证、访问、过期、停止分享、所有者离线和传输失败,仅重试明确分类为可重试的失败。
|
||||
Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒绝目标缺失或无效的调用。查看页的会话列表和工作区成员裁剪为源会话及该查看者自己的分叉会话。页面从读者的访问快照读取每个会话自己的答案,因此切换选择不会把前一会话的权限带过去。未知或无法读取的模式默认拒绝。Owner 为源会话与分叉会话调用重新检查准入;撤权会取消受影响的调用和流,分享准入收窄时只停止由查看者发起的正在运行轮次。页面区分认证、访问、过期、停止分享、所有者离线和传输失败,仅重试明确分类为可重试的失败。
|
||||
|
||||
-----
|
||||
|
||||
@@ -139,6 +139,7 @@ Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。
|
||||
|
||||
- [LiveShare 子系统](../../../docs/subsystems/liveshare.zh.md)
|
||||
- [Owner 决策记录](../../../.agents/notes/implemented/feature/2026-09-13-liveshare-protocol-and-owner-surfaces.zh.md)
|
||||
- [单一宿主认领房主状态](../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.zh.md)
|
||||
- [Web 组合包](../../bundle/web-app/README.zh.md)
|
||||
|
||||
-----
|
||||
@@ -165,10 +166,10 @@ viewer 的 prompt 以普通用户输入进入共享会话,因此扩展的是
|
||||
- 端点能力从 Typert registry 枚举已安装插件的 Remote 方法(见 [`shareable-catalog.ts`](src/host/shareable-catalog.ts)),DSH 核心服务命名空间被排除。方法调用不经过沙箱,也没有读写分类:开放一个方法即信任该已安装插件的代码,它在 Host 进程中执行。被选中的方法会在 policy 绑定的资源上被任意已认证分享读者调用,覆盖 `global`、`session`、`workspace` 三种资源种类。
|
||||
- owner 在分享面板里通过全局开关和按插件行选择已安装插件的方法。全局开关为“不可用”(全部关闭)、“自定义”(按插件列表)或“全部允许”(开放当前目录全部方法)。每个插件再设为不可用、全部方法或部分方法;部分选择保存显式方法列表,因此目录之后新增的方法不会自动开放,直到 owner 再次保存。插件行优先显示包内本地化名称,取不到时回退到包名末段或 namespace;搜索与限高滚动让大目录仍可操作。选择是分享级的:每位已准入查看者都可以在 policy 绑定的资源上调用被选中的方法,尚未建立逐查看者方法级别。方法授权独立于会话档位,Session 与 Workspace 调用仍由核心分享角色决定。目录不再提供的方法即使留在记录里也不暴露。
|
||||
- 工作区不再包含读者可见的会话后,要到该工作区或工作区顺序下次变化时才离开读者的工作区订阅([remote access 限制](../../api/remote-access/README.zh.md#known-limitations-and-deferred-work))。
|
||||
- 注册表文件锁防止并发文件写入丢失持久条目,但每个注册表读取自身内存快照。多个 Host 之间不协调 Owner 分享状态更新与网关归属;每个 home 只使用一个活动 Owner Host。这不是多宿主授权服务。
|
||||
- 注册表文件锁防止并发文件写入丢失持久条目,但每个注册表读取自身内存快照。一个正在运行的 Host 通过 `owner-host.json` 认领 owner 状态目录,因此同一 home 上的第二个 Host 只读取分享、不再注册或修改它们,任何会改动记录或为该记录联系 Liveshare 服务端的 `liveshareShares` 操作都以 `liveshareShares/owner-state-held` 拒绝,包括在分享对话框里添加源 Session、分享列表和审计读取。它仍可导入凭据,因为那是它自己的登录,但该导入不再认领分享、也不再重新注册任何分享。被后继者取代的 Host 会在下一次分享操作时发现这一点,并以同样的方式拒绝。该认领是建议性的,持有进程消失后会被回收,也仍不是多宿主授权服务。
|
||||
- 不发布运行时 invariant 配套模块:授权在操作本身检查,本包没有单独的 invariant 观察器。
|
||||
- Worker 重启会重新注册保留分享,但不重放查看流;查看者通过传输层恢复。注册被 401、403、410 或 426 拒绝时,该分享的重连就此停止,直到有别的操作把它重新注册:重新发布或改档位都会重新注册,为该 Liveshare 服务端存入凭据也会,它会把该地址下未在线的分享重新注册。恢复分享时出示的是本机为该分享所属 Liveshare 服务端保存的凭据,与本机自己对凭据过期的判断无关,因为 Liveshare 服务端会在背后为登录续期,凭据是否仍然授权只由 Liveshare 服务端决定;新建分享时仍按本机这一判断拒绝。
|
||||
- 访问档位授予 `view` 准入,有效 fork/write 权限来自分享模式。尚未建立逐查看者执行级别或立即跨实例停止/取消完成保证;取消不能撤回已提交写入。写入降为只读的快照会拒绝后续写入,但不承诺立即取消正在运行的分叉会话轮次。
|
||||
- 访问档位授予 `view` 准入,有效 fork/write 权限来自分享模式。尚未建立逐查看者执行级别或立即跨实例停止/取消完成保证;取消不能撤回已提交写入。分享结束只停止各来源会话中由查看者发起的正在运行轮次,所有者自己的轮次会继续运行;本机无法归因的轮次随分享一起停止。写入降为只读的快照会拒绝后续写入,但不承诺立即取消正在运行的分叉会话轮次。
|
||||
- 功能达到发布条件前,仍须完成最终装配快照验证。
|
||||
- 在查看页上,绕过 Connection 载体的客户端读取(交付物读取、open-in-app、PDF 资源、HMR 事件)到达的是 Liveshare 服务端而不是 Owner;index 文档中以根路径开头的 manifest 和图标链接在 Liveshare 服务端前缀下无法解析。
|
||||
|
||||
|
||||
@@ -55,7 +55,14 @@ export function LiveshareManageSharesDialog({ shares, onOpenShare, onClose, t }:
|
||||
setError('')
|
||||
try {
|
||||
const stopped = await shares.stop({ shareId: target.shareId })
|
||||
if (!stopped.ok) throw new Error('stop refused')
|
||||
// A Host whose share state another running process holds refuses the write; the share stays
|
||||
// listed, and the owner acts on it in the process holding the state.
|
||||
if (!stopped.ok) {
|
||||
setError(stopped.error.code === 'liveshareShares/owner-state-held'
|
||||
? t('dialog.ownerStateHeld')
|
||||
: t('dialog.stopFailed'))
|
||||
return
|
||||
}
|
||||
setShareList(current => current.filter(share => share.shareId !== target.shareId))
|
||||
setStopTarget(undefined)
|
||||
setStopAcknowledged(false)
|
||||
|
||||
@@ -143,7 +143,14 @@ export function useShareCreateForm({
|
||||
sessionMode,
|
||||
allowsFork,
|
||||
})
|
||||
if (!created.ok) throw new Error('share rejected')
|
||||
// A Host whose share state another running process holds refuses the write; that is the owner's
|
||||
// to act on in the process holding it, not an unreachable share service.
|
||||
if (!created.ok) {
|
||||
onError(created.error.code === 'liveshareShares/owner-state-held'
|
||||
? t('dialog.ownerStateHeld')
|
||||
: t('dialog.hostUnavailable'))
|
||||
return
|
||||
}
|
||||
const data = created.value
|
||||
// The Host's own record is the only statement of what it stored. Its answer carries the stored
|
||||
// tier, read through this build's vocabulary, so a Host that still names the withdrawn
|
||||
|
||||
@@ -122,6 +122,7 @@ export const zh = {
|
||||
'dialog.open': '打开',
|
||||
'dialog.stop': '停止分享',
|
||||
'dialog.stopFailed': '停止分享失败,请稍后重试。',
|
||||
'dialog.ownerStateHeld': '分享状态由另一个 DSH 进程持有;请在那个进程里管理分享,或先退出它。',
|
||||
'manage.title': '分享管理',
|
||||
'manage.open': '管理',
|
||||
'manage.cancelShare': '取消分享',
|
||||
@@ -357,6 +358,7 @@ export const en: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Open',
|
||||
'dialog.stop': 'Stop sharing',
|
||||
'dialog.stopFailed': 'Failed to stop sharing. Try again.',
|
||||
'dialog.ownerStateHeld': 'Another DSH process holds the share state; manage shares there, or quit it first.',
|
||||
'manage.title': 'Share management',
|
||||
'manage.open': 'Manage',
|
||||
'manage.cancelShare': 'Cancel share',
|
||||
@@ -592,6 +594,7 @@ export const ja: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': '開く',
|
||||
'dialog.stop': '共有を停止',
|
||||
'dialog.stopFailed': '共有を停止できませんでした。しばらくしてから再試行してください。',
|
||||
'dialog.ownerStateHeld': '共有状態は別の DSH プロセスが保持しています。そのプロセスで共有を管理するか、先に終了してください。',
|
||||
'manage.title': '共有の管理',
|
||||
'manage.open': '管理',
|
||||
'manage.cancelShare': '共有をキャンセル',
|
||||
@@ -827,6 +830,7 @@ export const es: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Abrir',
|
||||
'dialog.stop': 'Dejar de compartir',
|
||||
'dialog.stopFailed': 'No se pudo dejar de compartir. Inténtalo de nuevo.',
|
||||
'dialog.ownerStateHeld': 'Otro proceso de DSH mantiene el estado de los recursos compartidos; gestiona las comparticiones allí o ciérralo primero.',
|
||||
'manage.title': 'Gestión de recursos compartidos',
|
||||
'manage.open': 'Gestionar',
|
||||
'manage.cancelShare': 'Cancelar uso compartido',
|
||||
@@ -1062,6 +1066,7 @@ export const fr: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Ouvrir',
|
||||
'dialog.stop': 'Arrêter le partage',
|
||||
'dialog.stopFailed': 'L’arrêt du partage a échoué. Réessayez.',
|
||||
'dialog.ownerStateHeld': 'Un autre processus DSH détient l’état des partages ; gérez-les dans ce processus ou quittez-le d’abord.',
|
||||
'manage.title': 'Gestion des partages',
|
||||
'manage.open': 'Gérer',
|
||||
'manage.cancelShare': 'Annuler le partage',
|
||||
@@ -1297,6 +1302,7 @@ export const de: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Öffnen',
|
||||
'dialog.stop': 'Freigabe beenden',
|
||||
'dialog.stopFailed': 'Die Freigabe konnte nicht beendet werden. Versuche es später erneut.',
|
||||
'dialog.ownerStateHeld': 'Ein anderer DSH-Prozess hält den Freigabestatus; verwalte die Freigaben dort oder beende ihn zuerst.',
|
||||
'manage.title': 'Freigabeverwaltung',
|
||||
'manage.open': 'Verwalten',
|
||||
'manage.cancelShare': 'Freigabe abbrechen',
|
||||
@@ -1532,6 +1538,7 @@ export const ru: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Открыть',
|
||||
'dialog.stop': 'Остановить доступ',
|
||||
'dialog.stopFailed': 'Не удалось остановить общий доступ. Повторите попытку позже.',
|
||||
'dialog.ownerStateHeld': 'Состояние общего доступа удерживает другой процесс DSH; управляйте общим доступом в нём или сначала завершите его.',
|
||||
'manage.title': 'Управление доступом',
|
||||
'manage.open': 'Управлять',
|
||||
'manage.cancelShare': 'Отменить общий доступ',
|
||||
@@ -1767,6 +1774,7 @@ export const pt: Record<keyof typeof zh, string> = {
|
||||
'dialog.open': 'Abrir',
|
||||
'dialog.stop': 'Parar compartilhamento',
|
||||
'dialog.stopFailed': 'Falha ao parar o compartilhamento. Tente novamente.',
|
||||
'dialog.ownerStateHeld': 'Outro processo do DSH mantém o estado do compartilhamento; gerencie os compartilhamentos lá ou encerre-o primeiro.',
|
||||
'manage.title': 'Gerenciamento de compartilhamentos',
|
||||
'manage.open': 'Gerenciar',
|
||||
'manage.cancelShare': 'Cancelar compartilhamento',
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* One running host's claim on a LiveShare owner state directory.
|
||||
*
|
||||
* Two hosts that start on the same DSH home restore the same persisted shares. A Relay registration
|
||||
* belongs to one host at a time, so the later host re-registering them makes the earlier host's
|
||||
* authority reads answer for a registration the Relay has moved: the earlier host then fences the
|
||||
* share and, with it, cancels the owner's running turn. This claim names the host that owns the
|
||||
* state: the holder restores, registers, and mutates the shares, and every other host reads them
|
||||
* without publishing anything.
|
||||
*
|
||||
* The rules follow the session write lease
|
||||
* ([Agent Note](../../../../../.agents/notes/implemented/feature/2026-08-31-cross-process-session-write-lease.md)):
|
||||
* ownership has no expiry, the arbiter outlives a holder's failure, and contention is a typed answer
|
||||
* rather than a crash. Two properties differ because this directory is not session data: the claim is
|
||||
* advisory and gates Relay registrations rather than file writes, and a record naming this process is
|
||||
* reclaimed, because every host in one process shares the same owner state. The
|
||||
* [owner state note](../../../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md)
|
||||
* records why a recorded claim beats kernel arbitration.
|
||||
*
|
||||
* The claim is created exclusively (`wx`), so at most one creator wins on a local filesystem. A
|
||||
* holder is live while its recorded pid is; a record left by a process that is gone is reclaimed by
|
||||
* the next host, and so is one that names this process. The liveness check protects no share data and
|
||||
* no Session log, and pid reuse can at worst leave a live host without its shares until its next
|
||||
* start. There is deliberately no deadline that could expropriate a stalled holder.
|
||||
* @module @deepseek-ai/dsh-experimental-liveshare/src/host/owner-host-claim
|
||||
*/
|
||||
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { base64Url } from './base64-url.ts'
|
||||
import { isRecord } from './wire-json.ts'
|
||||
|
||||
/** Base name of the claim file inside the owner state directory. */
|
||||
export const OWNER_HOST_CLAIM_FILENAME = 'owner-host.json'
|
||||
|
||||
/** Another running host already owns this owner state directory. */
|
||||
export class OwnerHostClaimHeldError extends Error {
|
||||
/**
|
||||
* @param holderPid - Process that holds the claim, or this process when its own claim blocks it.
|
||||
*/
|
||||
constructor(readonly holderPid: number) {
|
||||
super(`the LiveShare owner state is held by dsh pid ${String(holderPid)}`)
|
||||
this.name = 'OwnerHostClaimHeldError'
|
||||
}
|
||||
}
|
||||
|
||||
/** One held claim, released exactly once by the host that took it. */
|
||||
export interface OwnerHostClaim {
|
||||
/** Release the claim when this process still holds it. */
|
||||
release(): void
|
||||
/**
|
||||
* Whether the claim file still names this host.
|
||||
*
|
||||
* A successor can replace the record while this host runs, so a caller about to change or
|
||||
* re-register the state re-reads it instead of trusting the claim taken at startup.
|
||||
* @returns True while the file still names the host that took the claim.
|
||||
*/
|
||||
holds(): boolean
|
||||
/** Record this claim carries, which names the holder that took it. */
|
||||
readonly hostId: string
|
||||
}
|
||||
|
||||
/** Liveness probe a test can replace. */
|
||||
export interface OwnerHostClaimOptions {
|
||||
/** Whether the recorded holder is still running; defaults to a kernel signal-0 probe. */
|
||||
readonly alive?: (pid: number) => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Path of the claim file for one owner state directory.
|
||||
* @param dir - Directory that holds the owner state file.
|
||||
* @returns The claim file path.
|
||||
*/
|
||||
export function ownerHostClaimPath(dir: string): string {
|
||||
return join(dir, OWNER_HOST_CLAIM_FILENAME)
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim one owner state directory for this process.
|
||||
* @param dir - Directory that holds the owner state file.
|
||||
* @param options - Liveness probe override.
|
||||
* @returns The held claim.
|
||||
* @throws {OwnerHostClaimHeldError} while another live host holds the claim.
|
||||
*/
|
||||
export function claimOwnerHost(dir: string, options: OwnerHostClaimOptions = {}): OwnerHostClaim {
|
||||
const path = ownerHostClaimPath(dir)
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
||||
const hostId = base64Url(randomBytes(9))
|
||||
const record = JSON.stringify({ hostId, pid: process.pid })
|
||||
const alive = options.alive ?? processAlive
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
if (publishClaim(path, record, hostId)) {
|
||||
return {
|
||||
hostId,
|
||||
release: () => { releaseClaim(path, hostId) },
|
||||
holds: () => claimStillHeld(path, hostId),
|
||||
}
|
||||
}
|
||||
const current = readClaim(path)
|
||||
if (current === undefined) continue
|
||||
// An unreadable record states no holder to judge, and may be the one a concurrent host is still
|
||||
// publishing: it is left alone, so this host reports the state as held and never removes it.
|
||||
const holder = claimPidOf(current)
|
||||
if (holder !== undefined && holder !== process.pid && alive(holder)) {
|
||||
throw new OwnerHostClaimHeldError(holder)
|
||||
}
|
||||
removeObservedClaim(path, current)
|
||||
}
|
||||
/* v8 ignore start -- only a writer that recreates the claim between our removal and the retry reaches this. */
|
||||
const raced = readClaim(path)
|
||||
throw new OwnerHostClaimHeldError(raced === undefined ? process.pid : claimPidOf(raced) ?? process.pid)
|
||||
/* v8 ignore stop */
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish one claim record under its final name, or report that another record already holds it.
|
||||
*
|
||||
* The record is written beside the claim and then linked into place: a link publishes the whole file
|
||||
* it names or fails because the name exists, so no reader ever sees a claim that is not yet written.
|
||||
* @param path - Claim file path.
|
||||
* @param record - Claim record to publish.
|
||||
* @param hostId - Host the record names, which names the temporary file too.
|
||||
* @returns True when this call's record now sits at the claim path.
|
||||
*/
|
||||
function publishClaim(path: string, record: string, hostId: string): boolean {
|
||||
const staged = `${path}.${hostId}.tmp`
|
||||
writeFileSync(staged, record, { mode: 0o600 })
|
||||
try {
|
||||
linkSync(staged, path)
|
||||
return true
|
||||
} catch (error: unknown) {
|
||||
/* v8 ignore next -- POSIX-only failure path: a directory at the claim path refuses the write too. */
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
|
||||
return false
|
||||
} finally {
|
||||
rmSync(staged, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the claim record at one path.
|
||||
* @param path - Claim file path.
|
||||
* @returns The file's content, or undefined when no claim file is there.
|
||||
*/
|
||||
function readClaim(path: string): string | undefined {
|
||||
try {
|
||||
return readFileSync(path, 'utf8')
|
||||
} catch {
|
||||
// A claim another host already removed is gone, and the next pass publishes this host's.
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one claim record this call judged reclaimable, unless another host published one first.
|
||||
*
|
||||
* A record whose process is gone names nothing this process must respect, and neither does one naming
|
||||
* this process: every host in one process shares the same owner state. A competing host that publishes
|
||||
* between this call's verdict and its removal wins, because the reread sees the record this call
|
||||
* judged and any other record is left in place.
|
||||
* @param path - Claim file path.
|
||||
* @param observed - Record this call read and judged reclaimable.
|
||||
*/
|
||||
function removeObservedClaim(path: string, observed: string): void {
|
||||
if (readClaim(path) === observed) unlinkClaim(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one claim while the file still names the host that took it.
|
||||
* @param path - Claim file path.
|
||||
* @param hostId - Host that is releasing.
|
||||
*/
|
||||
function releaseClaim(path: string, hostId: string): void {
|
||||
let content: string
|
||||
try {
|
||||
content = readFileSync(path, 'utf8')
|
||||
} catch {
|
||||
// A claim already gone needs no release.
|
||||
return
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(content)
|
||||
} catch {
|
||||
// An unreadable record cannot name a successor, so nothing it holds is ours to release.
|
||||
return
|
||||
}
|
||||
if (!isRecord(parsed) || parsed.hostId !== hostId) return
|
||||
unlinkClaim(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the pid one claim record names.
|
||||
* @param content - Claim file content.
|
||||
* @returns The recorded pid, or undefined when the record is missing or unreadable.
|
||||
*/
|
||||
function claimPidOf(content: string): number | undefined {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(content)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (!isRecord(parsed) || typeof parsed.pid !== 'number' || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) {
|
||||
return undefined
|
||||
}
|
||||
return parsed.pid
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one claim record still names one host.
|
||||
* @param path - Claim file path.
|
||||
* @param hostId - Host that took the claim.
|
||||
* @returns True when the file parses and names that host.
|
||||
*/
|
||||
function claimStillHeld(path: string, hostId: string): boolean {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return isRecord(parsed) && parsed.hostId === hostId
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one claim file, tolerating a removal another host already made.
|
||||
* @param path - Claim file path.
|
||||
*/
|
||||
function unlinkClaim(path: string): void {
|
||||
// A claim another host already removed is not a failure; every other removal error surfaces.
|
||||
rmSync(path, { force: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one pid still runs.
|
||||
* @param pid - Recorded holder pid.
|
||||
* @returns True when the process exists, including one this user may not signal.
|
||||
*/
|
||||
function processAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error: unknown) {
|
||||
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,14 @@ export interface OwnerHttpRouteDeps {
|
||||
readonly storedCredential: () => StoredOwnerCredential | undefined
|
||||
/** Replace the credential this host holds. */
|
||||
readonly setStoredCredential: (credential: StoredOwnerCredential) => void
|
||||
/**
|
||||
* Whether another running host owns the owner state directory.
|
||||
*
|
||||
* A credential is still stored here, because it is this host's own sign-in and a successor it
|
||||
* restarts as presents it; the passes that reach the Relay for the shares belong to the host that
|
||||
* owns the state, since they re-register its registrations.
|
||||
*/
|
||||
readonly ownerStateHeld: () => boolean
|
||||
/** Whether this host has been disposed. */
|
||||
readonly disposed: () => boolean
|
||||
}
|
||||
@@ -86,6 +94,7 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
|
||||
const ownerCredentialFile = deps.ownerCredentialFile
|
||||
const currentCredential = deps.storedCredential
|
||||
const setStoredCredential = deps.setStoredCredential
|
||||
const ownerStateHeld = deps.ownerStateHeld
|
||||
const disposed = deps.disposed
|
||||
|
||||
/**
|
||||
@@ -95,6 +104,11 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
|
||||
* authorization code — so both attribute the same shares the same way. Synchronous persistence is
|
||||
* the commit point: later probes and claims use this credential and Relay even if another operation
|
||||
* commits afterwards. A changed operation is refused before persistence, never rebound to a new Relay.
|
||||
*
|
||||
* Only the host that owns the owner state claims or re-registers: its shares are the ones the Relay
|
||||
* has registered, and a host that does not own the state holds a snapshot those claims and
|
||||
* registrations would answer for. That host still stores the credential and shares nothing until it
|
||||
* takes the state over on a later start.
|
||||
* @param operation - Captured Relay, configuration revision, and host instance.
|
||||
* @param credential - Signed credential the Relay issued for this host's instance.
|
||||
* @returns This operation's identity status, or the mismatch or storage failure to report.
|
||||
@@ -119,20 +133,30 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
|
||||
}
|
||||
setStoredCredential(committed)
|
||||
delete tunnel.factsFor(relay).claim
|
||||
await tunnel.probeRelayCredentialSupport(relay)
|
||||
const claim = await tunnel.claimOwnedShares(relay, tunnel.credentialForRelay(relay, committed))
|
||||
// The credential in hand is now the one a registration presents, so every share this host holds
|
||||
// for that address that a refusal left offline reaches the Relay again on its own.
|
||||
tunnel.reregisterOfflineShares(relay, committed)
|
||||
const ownsState = !ownerStateHeld()
|
||||
// A probe asks the Relay about the credential on behalf of the whole state, and the owner actions
|
||||
// that read its answer here are refused to a host that does not own that state.
|
||||
if (ownsState) await tunnel.probeRelayCredentialSupport(relay)
|
||||
const claim = ownsState
|
||||
? await tunnel.claimOwnedShares(relay, tunnel.credentialForRelay(relay, committed))
|
||||
: undefined
|
||||
if (ownsState) {
|
||||
// The credential in hand is now the one a registration presents, so every share this host holds
|
||||
// for that address that a refusal left offline reaches the Relay again on its own.
|
||||
tunnel.reregisterOfflineShares(relay, committed)
|
||||
}
|
||||
// A claim may have adopted the horizon the Relay reported for this very token, which replaces the
|
||||
// record with an equal one; the status therefore reports whichever record is current for this Relay.
|
||||
const heldAfterCommit = currentCredential()
|
||||
/* v8 ignore next -- a claim adoption rewrites only the horizon of the same credential. */
|
||||
const effective = heldAfterCommit?.credential === committed.credential ? heldAfterCommit : committed
|
||||
if (!disposed() && currentCredential() === effective) tunnel.factsFor(relay).claim = claim
|
||||
if (claim !== undefined && !disposed() && currentCredential() === effective) tunnel.factsFor(relay).claim = claim
|
||||
const renewed = previous === undefined
|
||||
|| (effective.expiresAt !== undefined && effective.expiresAt > previous)
|
||||
return { ok: true, status: tunnel.ownerIdentityStatus(relay, { renewed, claim }, effective) }
|
||||
return {
|
||||
ok: true,
|
||||
status: tunnel.ownerIdentityStatus(relay, { renewed, ...(claim === undefined ? {} : { claim }) }, effective),
|
||||
}
|
||||
}
|
||||
|
||||
connection.fetch.register({
|
||||
@@ -195,7 +219,11 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
|
||||
if (relay === undefined) {
|
||||
return json({ error: 'owner-login-unavailable', reason: 'relay-required' }, 409)
|
||||
}
|
||||
if (tunnel.factsFor(relay).supportsCredentials === undefined) await tunnel.probeRelayCredentialSupport(relay)
|
||||
// An address whose support answer this host already read needs no second ask, and a host that
|
||||
// does not own the state reads that answer rather than prompting the Relay again.
|
||||
if (!ownerStateHeld() && tunnel.factsFor(relay).supportsCredentials === undefined) {
|
||||
await tunnel.probeRelayCredentialSupport(relay)
|
||||
}
|
||||
if (!ownerOperationCurrent(operation)) return json({ error: 'owner-login-mismatch' }, 403)
|
||||
if (tunnel.factsFor(relay).supportsCredentials === false) {
|
||||
return json({ error: 'owner-login-unavailable', reason: 'relay-upgrade-required' }, 409)
|
||||
|
||||
@@ -198,6 +198,14 @@ export interface OwnerShareOperationDeps {
|
||||
readonly relayFetch?: RelayFetch
|
||||
/** Relay rows this host stopped but has not deleted. */
|
||||
readonly pendingRemovals: Map<string, PendingRelayRemoval>
|
||||
/**
|
||||
* Whether another running host owns the owner state directory.
|
||||
*
|
||||
* That host serves these shares; a write from here would change a record it is registering, and a
|
||||
* stop would withdraw a link it is keeping alive. Also true when the claim file no longer names this
|
||||
* host, which includes one a successor deleted: the shares this host still holds are a snapshot.
|
||||
*/
|
||||
readonly ownerStateHeld: () => boolean
|
||||
/** Subjects this deployment admits to every share. */
|
||||
readonly allowedSubjectIds: readonly string[]
|
||||
/** Children this host created. */
|
||||
@@ -230,7 +238,7 @@ export interface OwnerShareOperationDeps {
|
||||
readonly sourceConfined: (shareId: string, sessionId: string) => boolean
|
||||
/** Tell remote access that reader answers may have changed. */
|
||||
readonly accessChanged: () => void
|
||||
/** Stop whatever turn one share's Session is running. */
|
||||
/** Stop the turn that admitted share-viewer input for one share's Session. */
|
||||
readonly cancelShareTurn: (shareId: string) => void
|
||||
/** Reconcile one Session's sandbox after a share stopped. */
|
||||
readonly reconcileSourceAccess: (sessionId: string) => void
|
||||
@@ -265,6 +273,19 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
const cancelShareTurn = deps.cancelShareTurn
|
||||
const cancelChildTurns = deps.cancelChildTurns
|
||||
const reconcileSourceAccess = deps.reconcileSourceAccess
|
||||
const ownerStateHeld = deps.ownerStateHeld
|
||||
|
||||
/**
|
||||
* Refuse a share write while another running host owns the state those shares live in.
|
||||
*
|
||||
* Reads stay available so the owner can see what is shared; every operation that would change a
|
||||
* record, or move its Relay registration, belongs to the host that holds the state.
|
||||
*/
|
||||
function assertOwnerStateFree(): void {
|
||||
if (!ownerStateHeld()) return
|
||||
throw new RemoteError('liveshareShares/owner-state-held',
|
||||
'another running dsh instance owns the LiveShare share state; stop it or manage the shares there', {})
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner operations behind the `liveshareShares` Remote.
|
||||
@@ -274,7 +295,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
*/
|
||||
const operations: OwnerShareOperations = {
|
||||
/**
|
||||
* Order: address gate -> credential gate -> id/token/expiry -> waitForShare -> send(add-share) ->
|
||||
* Order: owner-state gate -> address gate -> credential gate -> id/token/expiry -> waitForShare -> send(add-share) ->
|
||||
* settlement -> failure remove-share and 502 -> ownerShares.set(online) -> persist (failure removes
|
||||
* the share, clears its expiry, and sends remove-share) -> scheduleShareExpiry -> applySourceAccess.
|
||||
*
|
||||
@@ -287,6 +308,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* answer returns, or the Relay keeps a share this host never stored.
|
||||
*/
|
||||
async create(request) {
|
||||
assertOwnerStateFree()
|
||||
if (request.sessionId === '') {
|
||||
throw new RemoteError('liveshareShares/missing-session-id', 'create requires a sessionId', {})
|
||||
}
|
||||
@@ -398,15 +420,18 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: validate -> resolve the share -> add each new source -> persist (failure restores the
|
||||
* previous record) -> install each added source's layer -> accessChanged.
|
||||
* Order: owner-state gate -> validate -> resolve the share -> add each new source -> persist (failure
|
||||
* restores the previous record) -> install each added source's layer -> accessChanged.
|
||||
*
|
||||
* The Relay registration carries the primary source only and does not change, so no Relay call is
|
||||
* made: every added Session is served through the same registration, ACL, tier, lifetime, and fork
|
||||
* switch. A Session the share already serves is ignored, so a repeated call is idempotent. Adding a
|
||||
* source never removes one; stopping the share ends all of them.
|
||||
* source never removes one; stopping the share ends all of them. The persisted record is the whole
|
||||
* map, so the gate comes first: a host that does not own the state holds a snapshot that a write
|
||||
* from here would put back in place of the holder's newer records.
|
||||
*/
|
||||
async addSessions(request: AddShareSessionsRequest): Promise<ShareSessions> {
|
||||
assertOwnerStateFree()
|
||||
if (request.shareId === '') {
|
||||
throw new RemoteError('liveshareShares/missing-share-id', 'addSessions requires a shareId', {})
|
||||
}
|
||||
@@ -449,27 +474,39 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: reconcileShareTitles -> void flushPendingRemovals() -> each share's readRelayAuthority
|
||||
* (success applyRelayAccess, failure invalidateRelayAccess) -> persist when any record changed ->
|
||||
* assemble the list.
|
||||
* Order (the host that owns the state): reconcileShareTitles -> void flushPendingRemovals() -> each
|
||||
* share's readRelayAuthority (a 404/410 ends its held admission there; any other failure keeps it) ->
|
||||
* persist when a record changed -> assemble the list.
|
||||
*
|
||||
* Order (a host that does not): assemble the records this host already holds.
|
||||
*
|
||||
* Reconciling first means the persisted titles match the fields assembled below; flushing first
|
||||
* uses the same list request as the host's next Relay contact; and reading each share's authority
|
||||
* before assembling means the list carries the tier and ACL the Relay actually committed, not
|
||||
* only what this host last stored.
|
||||
*
|
||||
* A host that does not own the state reads the stored records instead: every step above acts on a
|
||||
* registration the holding host is serving, and each one also changes that host's state — the
|
||||
* title reconciliation re-registers the share and writes the state file, and the authority read
|
||||
* adopts the Relay's ACL over the record this host restored from.
|
||||
*/
|
||||
async list() {
|
||||
await tunnel.reconcileShareTitles()
|
||||
// The owner's own page polling the list is the ordinary moment this host reaches the Relay.
|
||||
void tunnel.flushPendingRemovals()
|
||||
// One read per call: the Share panel polls this method, so a per-share read would scale with
|
||||
// the share count for no extra safety inside a single answer.
|
||||
const ownsState = !ownerStateHeld()
|
||||
if (ownsState) {
|
||||
await tunnel.reconcileShareTitles()
|
||||
// The owner's own page polling the list is the ordinary moment this host reaches the Relay.
|
||||
void tunnel.flushPendingRemovals()
|
||||
}
|
||||
const views = await Promise.all([...ownerShares.values()].map(async (share) => {
|
||||
await relay.readRelayAuthority(share)
|
||||
if (ownsState) await relay.readRelayAuthority(share)
|
||||
const next = ownerShares.get(share.shareId)
|
||||
if (next === undefined) return undefined
|
||||
return { changed: next !== share, share: ownerShareView(next) }
|
||||
}))
|
||||
const live = views.flatMap(view => view === undefined ? [] : [view])
|
||||
if (live.some(view => view.changed)) {
|
||||
if (ownsState && live.some(view => view.changed)) {
|
||||
try {
|
||||
await persistOwnerState()
|
||||
} catch {
|
||||
@@ -481,7 +518,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: send(remove-share) -> closeShare -> cancel the source turn -> cancel child turns ->
|
||||
* Order: owner-state gate -> send(remove-share) -> closeShare -> cancel the source turn -> cancel child turns ->
|
||||
* forks.revokeShare -> ownerShares.delete -> accessChanged -> clearShareExpiry -> persist ->
|
||||
* deleteRelayRow -> record and arm a pending removal.
|
||||
*
|
||||
@@ -491,6 +528,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* reachable deletion is what lets the pending-removal queue stay empty.
|
||||
*/
|
||||
async stop(request) {
|
||||
assertOwnerStateFree()
|
||||
const share = ownerShares.get(request.shareId)
|
||||
if (share === undefined) {
|
||||
throw new RemoteError('liveshareShares/share-not-found', `share ${request.shareId} is not published`, {
|
||||
@@ -539,7 +577,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: look up the share -> no-op branch (reinstall the layer when it is not confined) ->
|
||||
* Order: owner-state gate -> look up the share -> no-op branch (reinstall the layer when it is not confined) ->
|
||||
* ownerShares.set -> accessChanged -> cancel pending calls on a write-to-view narrowing -> persist
|
||||
* (failure restores the previous record) -> send(remove-share) then send(add-share) -> revoke forks
|
||||
* when the switch turns off -> applySourceAccess.
|
||||
@@ -550,6 +588,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* a request admitted on the new answer must not arrive before the layer that judges it.
|
||||
*/
|
||||
async updatePermissions(request) {
|
||||
assertOwnerStateFree()
|
||||
if (request.shareId === '') {
|
||||
throw new RemoteError('liveshareShares/missing-share-id', 'updatePermissions requires a shareId', {})
|
||||
}
|
||||
@@ -582,7 +621,8 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
if (!changed) {
|
||||
// A share that already names this state may still have no usable layer: its Session was not
|
||||
// live when it was set, or this host restarted before one could be installed. Asking again
|
||||
// installs it rather than answering as if the capability were already in place.
|
||||
// installs it rather than answering as if the capability were already in place. The owner-state
|
||||
// gate above already refused this call when another host holds the state.
|
||||
for (const sessionId of current.sessionIds) {
|
||||
if (!sourceConfined(shareId, sessionId)) await applySourceAccess(current, sessionId, undefined, 'mode')
|
||||
}
|
||||
@@ -632,7 +672,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: look up the share -> validate the submission against the live plugin offers ->
|
||||
* Order: owner-state gate -> look up the share -> validate the submission against the live plugin offers ->
|
||||
* ownerShares.set -> persist (failure restores the previous record) -> accessChanged.
|
||||
*
|
||||
* The live offers are the authority, so a name no plugin currently offers is refused before the
|
||||
@@ -640,6 +680,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* snapshot recomputes from the record that was actually persisted.
|
||||
*/
|
||||
async setCapabilities(request) {
|
||||
assertOwnerStateFree()
|
||||
if (request.shareId === '') {
|
||||
throw new RemoteError('liveshareShares/missing-share-id', 'setCapabilities requires a shareId', {})
|
||||
}
|
||||
@@ -725,7 +766,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: capture the previous effective address -> store the saved address -> bump the
|
||||
* Order: owner-state gate -> capture the previous effective address -> store the saved address -> bump the
|
||||
* authorization revision when the address changed -> persist.
|
||||
*
|
||||
* The revision is bumped before persistence so a login transaction begun under the old address is
|
||||
@@ -733,6 +774,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* exactly as the route always did.
|
||||
*/
|
||||
async setRelay(request) {
|
||||
assertOwnerStateFree()
|
||||
const previousRelay = effectiveRelay()
|
||||
if (request.relayUrl === null || request.relayUrl.trim() === '') {
|
||||
selectRelayAddress(undefined)
|
||||
@@ -760,7 +802,9 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* credential support when this address has not answered yet -> report identity.
|
||||
*
|
||||
* Probing before reporting keeps an address this host has not asked from borrowing another
|
||||
* address's support answer; the credential itself never enters the report.
|
||||
* address's support answer; the credential itself never enters the report. The probe asks the
|
||||
* Relay about the credential, not about a share registration, so a host that does not own the
|
||||
* state reports what it holds there without a second ask instead of prompting the Relay again.
|
||||
*/
|
||||
async identity(request) {
|
||||
const relay = request.relay === undefined || request.relay === '' ? effectiveRelay() : request.relay
|
||||
@@ -776,19 +820,23 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
// Support is per address, so an address this host has not probed yet is probed now rather than
|
||||
// borrowing another address's answer. A credential the signed token says is stale is probed
|
||||
// too: the Relay renews the login behind it, and only its answer can move the local horizon.
|
||||
if (tunnel.factsFor(relay).supportsCredentials === undefined || status.state !== 'verified') {
|
||||
if (!ownerStateHeld()
|
||||
&& (tunnel.factsFor(relay).supportsCredentials === undefined || status.state !== 'verified')) {
|
||||
await tunnel.probeRelayCredentialSupport(relay)
|
||||
}
|
||||
return tunnel.ownerIdentityStatus(relay, {}, credential)
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: resolve the share -> forward the audit read to the Relay -> parse a successful answer.
|
||||
* Order: owner-state gate -> resolve the share -> forward the audit read to the Relay -> parse a
|
||||
* successful answer.
|
||||
*
|
||||
* The Relay's own status and body are preserved on refusal, because the owner page classifies them;
|
||||
* a body this host cannot parse is reported as an unavailable audit rather than silently flattened.
|
||||
* The read presents the share's management token to the holder's Relay, so it is the holder's call.
|
||||
*/
|
||||
async audit(request) {
|
||||
assertOwnerStateFree()
|
||||
const share = ownerShares.get(request.shareId)
|
||||
if (share === undefined) {
|
||||
throw new RemoteError('liveshareShares/share-not-found', `share ${request.shareId} is not published`, {
|
||||
@@ -807,11 +855,12 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: flush owed Relay deletions -> run the anonymous connectivity check.
|
||||
* Order: owner-state gate -> flush owed Relay deletions -> run the anonymous connectivity check.
|
||||
*
|
||||
* Asking whether the Relay answers is the other moment this host learns it can deliver a deletion.
|
||||
*/
|
||||
async testRelay() {
|
||||
assertOwnerStateFree()
|
||||
void tunnel.flushPendingRemovals()
|
||||
// Nothing is in force before the owner saves an address, and a probe of no address is not a fact
|
||||
// about any Relay: the answer states the missing address instead of inventing a failure.
|
||||
@@ -825,7 +874,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
},
|
||||
|
||||
/**
|
||||
* Order: read the session id -> resolve the credential and identity row -> register one throwaway
|
||||
* Order: owner-state gate -> read the session id -> resolve the credential and identity row -> register one throwaway
|
||||
* share -> remove it after settlement.
|
||||
*
|
||||
* The permission step runs after authorization, so a host that holds no credential for the
|
||||
@@ -834,6 +883,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
|
||||
* real share would, so the Relay decides it the same way.
|
||||
*/
|
||||
async testPublish(request) {
|
||||
assertOwnerStateFree()
|
||||
if (request.sessionId === '') {
|
||||
throw new RemoteError('liveshareShares/missing-session-id', 'testPublish requires a sessionId', {})
|
||||
}
|
||||
|
||||
@@ -23,11 +23,20 @@ import type { ViewerReadService } from './viewer-read.ts'
|
||||
import { isRecord, json } from './wire-json.ts'
|
||||
import { relayFetch, type RelayFetch } from './relay-fetch.ts'
|
||||
|
||||
/** What one authoritative Relay read of a share produced. */
|
||||
export interface RelayAuthorityRead {
|
||||
readonly ok: boolean
|
||||
readonly accessState?: ShareAccessStateFrame
|
||||
}
|
||||
/**
|
||||
* What one authoritative Relay read of a share produced.
|
||||
*
|
||||
* A read that fails states nothing the previous one did not: only the Relay answering that it has no
|
||||
* such share ends the work admitted against it. Unavailability closes no stream and stops no turn,
|
||||
* because a timeout or a restart of the Relay says nothing about the owner's own Session. A refusal —
|
||||
* 401 or 403 — does end admission without ending the owner's turn: the Relay will not admit anything
|
||||
* else through this share, while the turn the owner started runs against the owner's own tools.
|
||||
* Every failure reports `ok: false`; the difference is what this host already did about it, not a
|
||||
* caller's decision.
|
||||
*/
|
||||
export type RelayAuthorityRead =
|
||||
| { readonly ok: true; readonly accessState: ShareAccessStateFrame }
|
||||
| { readonly ok: false }
|
||||
|
||||
/**
|
||||
* Whether one requester still holds access to one share this host publishes.
|
||||
@@ -95,8 +104,10 @@ export interface RelayAuthority {
|
||||
/**
|
||||
* Fence off one share's held authority and release the work admitted against it.
|
||||
* @param shareId - Share whose authority ended.
|
||||
* @param stopTurn - Whether the turn this share started is stopped too; a withdrawn share is, a
|
||||
* refused one is not, because the owner's own turn there keeps running.
|
||||
*/
|
||||
invalidateRelayAccess(shareId: string): void
|
||||
invalidateRelayAccess(shareId: string, options?: { readonly stopTurn?: boolean }): void
|
||||
/**
|
||||
* Adopt one Relay's statement of a share's access.
|
||||
* @param shareId - Share the frame describes.
|
||||
@@ -107,7 +118,7 @@ export interface RelayAuthority {
|
||||
* Read one share's authority from its Relay and adopt what it states.
|
||||
* @param share - Share to read.
|
||||
* @param signal - Cancellation of the forwarded request.
|
||||
* @returns The snapshot that was adopted, or an unavailable read.
|
||||
* @returns The adopted snapshot, or a read that ended the share's work or changed nothing.
|
||||
*/
|
||||
readRelayAuthority(share: OwnerShare, signal?: AbortSignal): Promise<RelayAuthorityRead>
|
||||
/**
|
||||
@@ -169,21 +180,35 @@ async function relayRequests(
|
||||
}
|
||||
}
|
||||
|
||||
/** What one HTTP answer from a Relay states about one share. */
|
||||
type RelayAuthorityAnswer =
|
||||
| { readonly kind: 'state'; readonly accessState: ShareAccessStateFrame }
|
||||
| { readonly kind: 'missing' }
|
||||
| { readonly kind: 'refused' }
|
||||
| { readonly kind: 'unavailable' }
|
||||
|
||||
async function relayAuthorityRead(
|
||||
defaultRelay: string,
|
||||
share: OwnerShare,
|
||||
signal: AbortSignal | undefined,
|
||||
fetchRelay: RelayFetch,
|
||||
): Promise<RelayAuthorityRead> {
|
||||
): Promise<RelayAuthorityAnswer> {
|
||||
try {
|
||||
const response = await relayRequests(defaultRelay, share, signal, fetchRelay)
|
||||
if (!response.ok) return { ok: false }
|
||||
// Only "this Relay has no such share" states that the grant ended. A refused, failed, or
|
||||
// unreadable answer is an unavailable one: relayRequests already turns a transport failure or
|
||||
// its deadline into 502, so a local stall cannot be mistaken for a revocation.
|
||||
if (response.status === 404 || response.status === 410) return { kind: 'missing' }
|
||||
// The Relay decides a credential or a share it will not serve this host, and repeating the read
|
||||
// with this token reaches the same answer, so the share serves no further viewer input.
|
||||
if (response.status === 401 || response.status === 403) return { kind: 'refused' }
|
||||
if (!response.ok) return { kind: 'unavailable' }
|
||||
const data: unknown = await response.json()
|
||||
if (!isRecord(data)) return { ok: false }
|
||||
if (!isRecord(data)) return { kind: 'unavailable' }
|
||||
const accessState = parseShareAccessState({ ...data, type: 'share-access-state' })
|
||||
return { ok: true, ...(accessState === undefined ? {} : { accessState }) }
|
||||
return accessState === undefined ? { kind: 'unavailable' } : { kind: 'state', accessState }
|
||||
} catch {
|
||||
return { ok: false }
|
||||
return { kind: 'unavailable' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,10 +295,10 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
|
||||
deps.accessChanged()
|
||||
}
|
||||
|
||||
function invalidateRelayAccess(shareId: string): void {
|
||||
function invalidateRelayAccess(shareId: string, options: { readonly stopTurn?: boolean } = {}): void {
|
||||
relayGenerations.set(shareId, generationOf(shareId) + 1)
|
||||
const heldAuthority = relayAccess.delete(shareId)
|
||||
if (heldAuthority || deps.ownerShares.get(shareId)?.online === true) {
|
||||
if (options.stopTurn !== false && (heldAuthority || deps.ownerShares.get(shareId)?.online === true)) {
|
||||
deps.cancelShareTurn(shareId)
|
||||
deps.cancelChildTurns(shareId)
|
||||
}
|
||||
@@ -324,10 +349,10 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
|
||||
deps.viewerRead().closeViewerStreams(shareId, child.creator)
|
||||
}
|
||||
}
|
||||
// An admission that narrowed can have ended a viewer's grant, and the host no longer attributes a
|
||||
// turn to a requester: it stops whatever the Session runs now rather than leave input admitted
|
||||
// under a grant that ended driving the owner's machine. A tier narrowing alone ends no turn,
|
||||
// because every execution re-reads the share's current tier before writing.
|
||||
// An admission that narrowed can have ended a viewer's grant: every source Session's recorded turn
|
||||
// origin decides, so a turn a viewer started is stopped rather than left to keep driving the owner's
|
||||
// machine, and the owner's own turn keeps running. A tier narrowing alone ends no turn, because
|
||||
// every execution re-reads the share's current tier before writing.
|
||||
if (admissionNarrowed(previous, state)) deps.cancelShareTurn(shareId)
|
||||
// The Session's sandbox follows its shares: a narrowed tier re-installs the read-only layer, and a
|
||||
// deadline that just passed releases it.
|
||||
@@ -339,17 +364,30 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
|
||||
async function readRelayAuthority(share: OwnerShare, signal?: AbortSignal): Promise<RelayAuthorityRead> {
|
||||
signal?.throwIfAborted()
|
||||
const generation = generationOf(share.shareId)
|
||||
const snapshot = await relayAuthorityRead(share.relay, share, signal, deps.relayFetch ?? relayFetch)
|
||||
const answer = await relayAuthorityRead(share.relay, share, signal, deps.relayFetch ?? relayFetch)
|
||||
signal?.throwIfAborted()
|
||||
const current = deps.ownerShares.get(share.shareId)
|
||||
if (deps.disposed() || generation !== generationOf(share.shareId) || current?.gatewayToken !== share.gatewayToken
|
||||
|| current.relay !== share.relay) return { ok: false }
|
||||
if (!snapshot.ok || snapshot.accessState === undefined) {
|
||||
if (answer.kind === 'missing') {
|
||||
invalidateRelayAccess(share.shareId)
|
||||
return { ok: false }
|
||||
}
|
||||
applyRelayAccess(share.shareId, snapshot.accessState)
|
||||
return snapshot
|
||||
// A refusal ends admission while the owner's turn keeps running: the Relay would not serve this
|
||||
// host for the share, so it admits no further viewer input there. Calls and streams already open
|
||||
// are released now, rather than at their next poll against the snapshot this read dropped.
|
||||
if (answer.kind === 'refused') {
|
||||
invalidateRelayAccess(share.shareId, { stopTurn: false })
|
||||
for (const child of deps.forks.listForShare(share.shareId)) {
|
||||
deps.viewerRead().closeViewerStreams(share.shareId, child.creator)
|
||||
}
|
||||
return { ok: false }
|
||||
}
|
||||
// An unavailable Relay read ends nothing here: the held statement stays, and every viewer path
|
||||
// that needs a fresh admission is refused by refreshRelayAccess until a read succeeds again.
|
||||
if (answer.kind === 'unavailable') return { ok: false }
|
||||
applyRelayAccess(share.shareId, answer.accessState)
|
||||
return { ok: true, accessState: answer.accessState }
|
||||
}
|
||||
|
||||
async function refreshRelayAccess(shareId: string, signal?: AbortSignal): Promise<void> {
|
||||
|
||||
@@ -17,6 +17,7 @@ import { createRelayAuthority } from './relay-authority.ts'
|
||||
import { createOwnerShareOperations } from './owner-share-operations.ts'
|
||||
import { registerOwnerHttpRoutes } from './owner-http-routes.ts'
|
||||
import { createTunnelSupervision } from './tunnel-supervision.ts'
|
||||
import { claimOwnerHost, OwnerHostClaimHeldError, type OwnerHostClaim } from './owner-host-claim.ts'
|
||||
import { activateSession, createSourceAccess, type SourceAccess } from './source-access.ts'
|
||||
import { LiveshareShares } from './share-remote.ts'
|
||||
import type { OwnerRelayState } from '../share-api-types.ts'
|
||||
@@ -161,6 +162,23 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
throw new Error('liveshare-share-host: ownerStateFile must not be empty')
|
||||
}
|
||||
const ownerState = loadOwnerState(ownerStateFile)
|
||||
// One host owns this state at a time. A second host that restored the same shares would move their
|
||||
// Relay registrations away from the holder, whose next authority read would then fence them and
|
||||
// stop the owner's turn; that host reads the records and publishes nothing.
|
||||
const ownerHostClaim: OwnerHostClaim | undefined = takeOwnerStateClaim(dirname(ownerStateFile))
|
||||
// Re-read on every use: a successor can replace the record while this host runs, and a host that
|
||||
// no longer holds the state must stop registering and changing shares. Both a claim that was never
|
||||
// taken and one whose file no longer names this host answer false.
|
||||
const ownsOwnerState = (): boolean => ownerHostClaim !== undefined && ownerHostClaim.holds()
|
||||
// A host that fails to finish mounting must not leave the claim naming its pid: this effect runs
|
||||
// when the plugin's fiber disposes, including a load that rejects below. The ordinary teardown
|
||||
// releases the claim only once the worker has stopped, so the effect releases only when the host
|
||||
// never reached that teardown; releasing an already-freed claim is a no-op either way.
|
||||
let claimReleasedByTeardown = false
|
||||
if (ownerHostClaim !== undefined) {
|
||||
const claimed = ownerHostClaim
|
||||
ctx.effect(() => () => { if (!claimReleasedByTeardown) claimed.release() })
|
||||
}
|
||||
const ownerCredentialFile = config.ownerCredentialFile
|
||||
?? nonEmpty(process.env.LIVESHARE_OWNER_CREDENTIAL_FILE)
|
||||
?? join(dirname(ownerStateFile), OWNER_CREDENTIAL_FILENAME)
|
||||
@@ -339,6 +357,10 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
disposed: () => disposed,
|
||||
accessChanged,
|
||||
confinedExecution,
|
||||
// The same record the sandbox reads, with the same rule for an unattributable turn: work this
|
||||
// host cannot place may be the work the ended grant admitted. A turn that has not admitted its
|
||||
// first step yet still reads the previous turn's record; that window is one step wide.
|
||||
turnIsViewerDriven: sessionId => viewerTurns.get(sessionId)?.confined !== false,
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -477,8 +499,9 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
|
||||
// A reader's input is re-checked here rather than before it entered the queue: the step about to run
|
||||
// reads the viewer from each entering message's own source, so input admitted under a grant that ended
|
||||
// since is refused before it reaches the model. A shared Session's own turns are not attributed, so the
|
||||
// sandbox on the Session — not this admission check — is what confines them.
|
||||
// since is refused before it reaches the model. This listener also records whether the turn admitted
|
||||
// share-viewer input, which decides both the tool surface the turn runs and whether ending a share's
|
||||
// grant stops it.
|
||||
ctx.on('agent/pre-step', async ({ agent, signal, turn }, next) => {
|
||||
const decision = await next()
|
||||
if (decision.kind !== 'enter') return decision
|
||||
@@ -516,16 +539,20 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
writeOwnerState(ownerStateFile, relayOverride, ownerState.instanceId, ownerShares, pendingRemovals)
|
||||
|
||||
// A restored share keeps its own deadline, so the cancel that stops its running turn when the deadline
|
||||
// passes is armed again from the record rather than remembered anywhere else.
|
||||
for (const share of ownerShares.values()) tunnel.scheduleShareExpiry(share)
|
||||
// passes is armed again from the record rather than remembered anywhere else. Only the holder arms it:
|
||||
// both the record it restored and the shares over its Sessions can be stale, because the holder has
|
||||
// changed them since, so a second host's deadline would end work the holder still serves.
|
||||
if (ownsOwnerState()) {
|
||||
for (const share of ownerShares.values()) tunnel.scheduleShareExpiry(share)
|
||||
}
|
||||
// A host that starts with write-mode shares installs their access layers before serving any request for
|
||||
// them, so a restored share is never briefly writable without the layer that judges its turns.
|
||||
void Promise.all([...ownerShares.values()].flatMap(share =>
|
||||
share.sessionIds.map(sessionId => sourceAccess.apply(share, sessionId, undefined, 'restore'))))
|
||||
// Reconnecting a share, refreshing its title, and probing or claiming at the Relay all need an address
|
||||
// the owner saved. A host that has none still serves the sharing surfaces and stops its shares' turns
|
||||
// on their deadlines, but contacts no Relay: there is no address to ask, and the dialog states that.
|
||||
if (effectiveRelay !== undefined) {
|
||||
// the owner saved. A host that has none still serves the sharing surfaces, but contacts no Relay: there
|
||||
// is no address to ask, and the dialog states that.
|
||||
if (effectiveRelay !== undefined && ownsOwnerState()) {
|
||||
for (const share of ownerShares.values()) tunnel.send({ type: 'add-share', share: tunnel.shareSpec(share, storedCredential) })
|
||||
// The shares this profile reconnected with keep their recorded titles until the title folds answer,
|
||||
// so the refresh runs beside mounting rather than holding it up.
|
||||
@@ -567,6 +594,7 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
relayFetch: relayTransport.fetch,
|
||||
ownerShares,
|
||||
pendingRemovals,
|
||||
ownerStateHeld: () => !ownsOwnerState(),
|
||||
allowedSubjectIds,
|
||||
forks,
|
||||
viewerRead,
|
||||
@@ -599,11 +627,13 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
ownerCredentialFile,
|
||||
storedCredential: () => storedCredential,
|
||||
setStoredCredential: (credential) => { storedCredential = credential },
|
||||
ownerStateHeld: () => !ownsOwnerState(),
|
||||
disposed: () => disposed,
|
||||
})
|
||||
|
||||
// One attempt at startup: a host that restarted with rows still owed delivers them as soon as it can.
|
||||
void tunnel.flushPendingRemovals()
|
||||
// A host that does not own the state must not touch the Relay rows the holder is serving.
|
||||
if (ownsOwnerState()) void tunnel.flushPendingRemovals()
|
||||
|
||||
return async () => {
|
||||
for (const shareId of ownerShares.keys()) {
|
||||
@@ -611,8 +641,35 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
|
||||
sourceAccess.cancelChildTurns(shareId)
|
||||
}
|
||||
disposed = true
|
||||
await tunnel.dispose(() => { viewerRead.close() })
|
||||
await relayTransport.close()
|
||||
// The claim goes last: a successor that took it now would register the same shares while this
|
||||
// host's worker is still stopping its registrations, and the handshake it is finishing would
|
||||
// then overwrite the successor's registration.
|
||||
try {
|
||||
await tunnel.dispose(() => { viewerRead.close() })
|
||||
await relayTransport.close()
|
||||
} finally {
|
||||
claimReleasedByTeardown = true
|
||||
ownerHostClaim?.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Take this host's claim on the owner state directory.
|
||||
*
|
||||
* A second host on the same DSH home reads the shares without publishing them: it must not move the
|
||||
* holder's Relay registrations, and a share operation there would otherwise run against a state
|
||||
* another process is serving.
|
||||
* @param dir - Directory that holds the owner state file.
|
||||
* @returns The held claim, or undefined while another live host holds it.
|
||||
*/
|
||||
function takeOwnerStateClaim(dir: string): OwnerHostClaim | undefined {
|
||||
try {
|
||||
return claimOwnerHost(dir)
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof OwnerHostClaimHeldError)) throw error
|
||||
console.warn(`[liveshare] the owner state is held by dsh pid ${String(error.holderPid)}; this instance reads the shares without registering them`)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ export class LiveshareShares extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh titles and Liveshare server authority, then list this host's shares.
|
||||
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
|
||||
* @returns Every share this host publishes.
|
||||
*/
|
||||
@Remote('list')
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* The layer is registered into the Session's own scope and confines the turns a share viewer starts while
|
||||
* any share over the Session is active; the owner's own turns keep the deployment's tools. It belongs to
|
||||
* the Session rather than to one share, so several shares over it share one installation, and the host
|
||||
* releases it once no share is left. Stopping a share stops whatever turn the Session is running, with
|
||||
* the owner's own cancellation, without asking which turn or which requester it was.
|
||||
* releases it once no share is left. Stopping a share stops the turn that admitted share-viewer input,
|
||||
* with the owner's own cancellation; an owner-started turn keeps running, and a turn this host cannot
|
||||
* attribute stops with the share.
|
||||
* @module @deepseek-ai/dsh-experimental-liveshare/src/host/source-access
|
||||
*/
|
||||
|
||||
@@ -144,6 +145,13 @@ export interface SourceAccessDeps {
|
||||
* this is the per-execution authority both the guard and the replacements read.
|
||||
*/
|
||||
readonly confinedExecution: (execution: ForkToolExecution) => boolean
|
||||
/**
|
||||
* Whether the turn one Session is running was started by a share viewer.
|
||||
*
|
||||
* A grant that ends stops the work it admitted, not the owner's own work: the same recorded turn
|
||||
* origin the sandbox reads decides whether there is anything of the share's to stop.
|
||||
*/
|
||||
readonly turnIsViewerDriven: (sessionId: string) => boolean
|
||||
}
|
||||
|
||||
/** The confined access layer and turn control one host's source Sessions carry. */
|
||||
@@ -197,11 +205,11 @@ export interface SourceAccess {
|
||||
*/
|
||||
childToolAuthorized(childSessionId: string, tool: string): boolean
|
||||
/**
|
||||
* Stop whatever turn one share's Session is running, when the share stops driving it.
|
||||
* Stop whatever turns one share's source Sessions are running, when the share stops driving them.
|
||||
*
|
||||
* The host records only whether a turn was viewer-started, not which viewer admitted it, so it cannot
|
||||
* tell a revoked viewer's turn from the owner's: a share that ends its grant stops the running turn
|
||||
* itself.
|
||||
* The host records whether each turn was started by a share viewer, so a turn the owner started keeps
|
||||
* running when a grant ends. A turn this host cannot attribute is stopped, because it may be the work
|
||||
* the ended grant admitted. Each source Session is judged on its own origin record.
|
||||
* @param shareId - Share whose capability just ended.
|
||||
*/
|
||||
cancelShareTurn(shareId: string): void
|
||||
@@ -537,12 +545,13 @@ export function createSourceAccess(deps: SourceAccessDeps): SourceAccess {
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop whatever turn one share's Session is running.
|
||||
* Stop whatever turn one share's source Sessions are running, when those turns belong to the share.
|
||||
*
|
||||
* Revoking a share's capability unestablishes the work it admitted, but the host does not attribute a
|
||||
* turn to the requester that admitted it: the running turn is stopped with the same cancellation the
|
||||
* owner's own Stop command uses. Nothing already written is undone; a turn that has not started yet is
|
||||
* refused by the sandbox instead.
|
||||
* Revoking a share's capability unestablishes the work it admitted. A turn the owner started is not
|
||||
* that work, so it keeps running; a turn this host cannot attribute is stopped with the same
|
||||
* cancellation the owner's own Stop command uses, because it may be the work the grant admitted.
|
||||
* The owner records that origin per Session, so each source Session of the share is judged on its own.
|
||||
* Nothing already written is undone; a turn that has not started yet is refused by the sandbox instead.
|
||||
* @param shareId - Share whose capability just ended.
|
||||
*/
|
||||
const cancelShareTurn = (shareId: string): void => {
|
||||
@@ -554,6 +563,7 @@ export function createSourceAccess(deps: SourceAccessDeps): SourceAccess {
|
||||
for (const sessionId of share.sessionIds) {
|
||||
const live = agents?.get?.(sessionId)
|
||||
if (live === undefined || live.status !== 'running') continue
|
||||
if (!deps.turnIsViewerDriven(sessionId)) continue
|
||||
console.warn(`[liveshare] cancelling source turn share=${shareId} session=${sessionId}`)
|
||||
live.cancel?.({ kind: 'user' }, { keepInbox: true })
|
||||
}
|
||||
|
||||
@@ -12,7 +12,12 @@ import { base64Url } from './base64-url.ts'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { IdentityActor, TunnelShareSpec, TunnelWorkerEvent } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import type {
|
||||
IdentityActor,
|
||||
LiveshareOwnerPlatform,
|
||||
TunnelShareSpec,
|
||||
TunnelWorkerEvent,
|
||||
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import type {
|
||||
ClaimOutcome,
|
||||
OwnerIdentityStatus,
|
||||
@@ -118,7 +123,7 @@ export interface TunnelSupervisionDeps {
|
||||
readonly viewerRead: () => ViewerReadService
|
||||
/** Tell remote access that reader answers may have changed. */
|
||||
readonly accessChanged: () => void
|
||||
/** Stop whatever turn one share's Session is running. */
|
||||
/** Stop the turn that admitted share-viewer input for one share's Session. */
|
||||
readonly cancelShareTurn: (shareId: string) => void
|
||||
/** Reconcile one Session's sandbox after a share stopped or expired. */
|
||||
readonly reconcileSourceAccess: (sessionId: string) => void
|
||||
@@ -278,6 +283,23 @@ function bundleVersion(): string | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Map this owner's runtime platform onto the wire enum.
|
||||
*
|
||||
* The enum names a display class, not a kernel: a system outside it reports nothing, so the Relay
|
||||
* shows no platform instead of receiving a name neither peer agreed on.
|
||||
* @param platform - Runtime platform to map, defaulting to the one this process reports.
|
||||
* @returns The matching enum value, or undefined when the system is outside the enum.
|
||||
*/
|
||||
export function ownerPlatform(platform: NodeJS.Platform = process.platform): LiveshareOwnerPlatform | undefined {
|
||||
switch (platform) {
|
||||
case 'darwin': return 'macos'
|
||||
case 'win32': return 'windows'
|
||||
case 'linux': return 'linux'
|
||||
default: return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Title one share should adopt after reading its Session.
|
||||
* @param recorded - Title stored on the share when it was created or last refreshed.
|
||||
@@ -595,13 +617,17 @@ export function createTunnelSupervision(deps: TunnelSupervisionDeps): TunnelSupe
|
||||
* the shares this profile reconnected with, and a reader's admission is derived from these fields
|
||||
* either way, so both sites build the row here instead of keeping two copies in step by hand.
|
||||
*/
|
||||
const ownerIdentityRow = (relay: string, credential: StoredOwnerCredential | undefined) => ({
|
||||
...deps.ownerContext,
|
||||
ownerDisplayName: readerFacingOwnerName(relay, credential),
|
||||
/* v8 ignore next -- the version is read from the package manifest beside this module. */
|
||||
...(dshVersion === undefined ? {} : { dshVersion }),
|
||||
ownerInstanceId: deps.instanceId,
|
||||
})
|
||||
const ownerIdentityRow = (relay: string, credential: StoredOwnerCredential | undefined) => {
|
||||
const platform = ownerPlatform()
|
||||
return {
|
||||
...deps.ownerContext,
|
||||
ownerDisplayName: readerFacingOwnerName(relay, credential),
|
||||
/* v8 ignore next -- the version is read from the package manifest beside this module. */
|
||||
...(dshVersion === undefined ? {} : { dshVersion }),
|
||||
...(platform === undefined ? {} : { platform }),
|
||||
ownerInstanceId: deps.instanceId,
|
||||
}
|
||||
}
|
||||
|
||||
const shareSpec = (share: ShareRegistrationSource, credential: StoredOwnerCredential | undefined): TunnelShareSpec => {
|
||||
const ownerCredential = registrableCredentialForRelay(share.relay, credential)
|
||||
|
||||
@@ -35,6 +35,9 @@ export function registrationUrl(spec: TunnelShareSpec): URL {
|
||||
if (spec.dshVersion !== undefined && spec.dshVersion !== '') {
|
||||
url.searchParams.set('dshVersion', spec.dshVersion)
|
||||
}
|
||||
if (spec.platform !== undefined) {
|
||||
url.searchParams.set('platform', spec.platform)
|
||||
}
|
||||
if (spec.ownerInstanceId !== undefined && spec.ownerInstanceId !== '') {
|
||||
url.searchParams.set('ownerInstanceId', spec.ownerInstanceId)
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'liveshareShares/relay-unavailable': { readonly relay: string; readonly reason?: string }
|
||||
/** The owner state file could not be written; the previous record is still in force. */
|
||||
'liveshareShares/owner-state-unavailable': Record<string, never>
|
||||
/** Another running host owns the owner state, so this host refuses to change the shares. */
|
||||
'liveshareShares/owner-state-held': Record<string, never>
|
||||
/** A submitted capability names a plugin that offers no viewer endpoints. */
|
||||
'liveshareShares/unknown-plugin': { readonly plugin: string }
|
||||
/** A submitted policy names an endpoint the platform catalog does not offer. */
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { LIVESHARE_CAPABILITIES, LIVESHARE_PROTOCOL_VERSION } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import {
|
||||
LIVESHARE_CAPABILITIES,
|
||||
LIVESHARE_OWNER_PLATFORMS,
|
||||
LIVESHARE_PROTOCOL_VERSION,
|
||||
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import { registrationUrl } from '../src/owner-gateway/registration-url.ts'
|
||||
import type { TunnelShareSpec } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
|
||||
@@ -54,11 +58,17 @@ describe('Liveshare registration handshake', () => {
|
||||
it('leaves every optional fact absent until the share states it', () => {
|
||||
const url = registrationUrl(minimal)
|
||||
|
||||
for (const absent of ['sessionMode', 'allowsFork', 'dshVersion', 'ownerInstanceId', 'expiresAt', 'ownerProviderId', 'ownerTenantId', 'allowedSubjectId']) {
|
||||
for (const absent of ['sessionMode', 'allowsFork', 'dshVersion', 'platform', 'ownerInstanceId', 'expiresAt', 'ownerProviderId', 'ownerTenantId', 'allowedSubjectId']) {
|
||||
expect(url.searchParams.get(absent), absent).toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('sends the platform this owner reports', () => {
|
||||
for (const platform of LIVESHARE_OWNER_PLATFORMS) {
|
||||
expect(registrationUrl({ ...minimal, platform }).searchParams.get('platform'), platform).toBe(platform)
|
||||
}
|
||||
})
|
||||
|
||||
it('carries exactly the optionals the share states', () => {
|
||||
const url = registrationUrl({
|
||||
...minimal,
|
||||
|
||||
@@ -156,6 +156,15 @@ describe('Liveshare gateway worker IPC', () => {
|
||||
expect(worker.events.at(-1)).toEqual({ type: 'share-connected', registrationToken: token, shareId: 'share' })
|
||||
})
|
||||
|
||||
it('registers the platform this owner reports and nothing when it reports none', () => {
|
||||
worker = startWorker()
|
||||
worker.command({ type: 'add-share', registrationToken: registrationToken(), share: shareSpec({ platform: 'linux' }) })
|
||||
expect(latest().url.searchParams.get('platform')).toBe('linux')
|
||||
|
||||
worker.command({ type: 'add-share', registrationToken: registrationToken(), share: shareSpec() })
|
||||
expect(latest().url.searchParams.has('platform')).toBe(false)
|
||||
})
|
||||
|
||||
it('omits an absent owner credential and treats an identical registration as a no-op', () => {
|
||||
worker = startWorker()
|
||||
const token = registrationToken()
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { createServer, type AddressInfo } from 'node:net'
|
||||
import { createServer as createHttpServer } from 'node:http'
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import { WebSocketServer } from 'ws'
|
||||
import { apply, type Config } from '../src/host/share-host.ts'
|
||||
import { TunnelWorker, type TunnelWorkerInput } from '../src/host/tunnel-worker.ts'
|
||||
import type {} from '../src/index.ts'
|
||||
|
||||
interface GatewayUpgrade {
|
||||
@@ -321,14 +325,56 @@ describe('liveshare owner host', () => {
|
||||
// The first snapshot states access this host already held, so nothing is cancelled.
|
||||
expect(cancel).not.toHaveBeenCalled()
|
||||
|
||||
// The Relay narrows the share to a stored allowlist that does not name this viewer: the host cannot
|
||||
// attribute the running turn, so it stops the turn the Session is running now.
|
||||
// The Relay narrows the share to a stored allowlist that does not name this viewer, and this turn has
|
||||
// no origin record, so the host cannot place it: it stops the turn the Session is running now.
|
||||
authority = { version: 2, accessMode: 'selected', allowedSubjectIds: [], sessionMode: 'write' }
|
||||
await host.liveshareShares.list()
|
||||
await expect.poll(() => cancel.mock.calls.length, { timeout: 5_000 }).toBe(1)
|
||||
expect(cancel).toHaveBeenCalledWith({ kind: 'user' }, { keepInbox: true })
|
||||
}, 20_000)
|
||||
|
||||
it('keeps an owner-started turn when a share narrows', async () => {
|
||||
const cancel = vi.fn()
|
||||
const live = liveAgent('session-1', cancel)
|
||||
let authority: Record<string, unknown> = {
|
||||
version: 1, accessMode: 'open', allowedSubjectIds: [], sessionMode: 'write',
|
||||
}
|
||||
const relay = createHttpServer((request, response) => {
|
||||
response.writeHead(200, { 'content-type': 'application/json' })
|
||||
response.end(JSON.stringify(request.url?.includes('owner-credential') === true
|
||||
? { supported: true }
|
||||
: authority))
|
||||
})
|
||||
await new Promise<void>((resolve) => { relay.listen(0, '127.0.0.1', resolve) })
|
||||
closers.push(async () => { await new Promise<void>((resolve) => { relay.close(() => { resolve() }) }) })
|
||||
const port = (relay.address() as AddressInfo).port
|
||||
const { host } = ownerRoutes({ agents: { get: () => live } })
|
||||
const dispose = await apply(host, {
|
||||
ownerIdentity: { providerId: 'mock', tenantId: 'tenant-a', subjectId: 'owner', displayName: 'Owner' },
|
||||
ownerStateFile: ownerStateFile(`http://127.0.0.1:${String(port)}`,
|
||||
[storedRecord('share-1', { sessionId: 'session-1', sessionMode: 'write', allowsFork: true })]),
|
||||
} satisfies Config)
|
||||
closers.push(dispose)
|
||||
|
||||
await host.liveshareShares.list()
|
||||
// The owner starts turn 7 and its first step admits no share-viewer input, which the host records
|
||||
// before the narrowing read below.
|
||||
const ownerMessage = createUserMessage({ content: [{ type: 'text', text: 'owner' }], source: { kind: 'user' } })
|
||||
await host.waterfall('agent/pre-step', {
|
||||
modelSelection: { provider: 'mock', model: 'mock' },
|
||||
agent: live as never,
|
||||
turn: 7,
|
||||
step: 1,
|
||||
messages: [ownerMessage],
|
||||
signal: new AbortController().signal,
|
||||
}, async () => ({ kind: 'enter', messages: [ownerMessage] }))
|
||||
|
||||
authority = { version: 2, accessMode: 'selected', allowedSubjectIds: [], sessionMode: 'write' }
|
||||
await host.liveshareShares.list()
|
||||
// The narrowed grant stops only work the share admitted, so the owner's turn keeps running.
|
||||
expect(cancel).not.toHaveBeenCalled()
|
||||
}, 20_000)
|
||||
|
||||
it('registers no route for the retired approval flow', async () => {
|
||||
const { routes, host } = ownerRoutes()
|
||||
const dispose = await apply(host, { ownerStateFile: ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, []),
|
||||
@@ -436,4 +482,122 @@ describe('liveshare owner host', () => {
|
||||
// The stored ACL travels with the revived registration, so the mode change never widens it.
|
||||
expect(upgrade?.search.getAll('allowedSubjectId')).toEqual(['mock:acceptance-tenant:viewer'])
|
||||
}, 20_000)
|
||||
|
||||
it('keeps the claim until the worker has stopped registering its shares', async () => {
|
||||
// A successor that takes the claim while this worker is still stopping would register the same
|
||||
// shares, and the handshake this host is finishing could overwrite that registration.
|
||||
const upgrades: GatewayUpgrade[] = []
|
||||
const relay = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
||||
await new Promise<void>((resolve) => { relay.once('listening', resolve) })
|
||||
relay.on('connection', (_socket, request) => {
|
||||
const url = new URL(request.url ?? '/', 'http://relay.local')
|
||||
upgrades.push({ shareId: url.searchParams.get('shareId') ?? '', authorization: request.headers.authorization, search: url.searchParams })
|
||||
})
|
||||
closers.push(async () => {
|
||||
await new Promise<void>((resolve) => { relay.close(() => { resolve() }) })
|
||||
})
|
||||
const port = (relay.address() as AddressInfo).port
|
||||
const file = ownerStateFile(`http://127.0.0.1:${String(port)}`, [storedRecord('held-share', {})])
|
||||
const { host } = ownerRoutes()
|
||||
const dispose = await apply(host, { ownerStateFile: file } satisfies Config)
|
||||
closers.push(dispose)
|
||||
await expect.poll(() => upgrades.length, { timeout: 15_000 }).toBeGreaterThan(0)
|
||||
|
||||
const claimPath = ownerHostClaimPath(dirname(file))
|
||||
// The claim names this host for as long as the worker that registers the shares is stopping, and
|
||||
// the teardown has not resolved while it does.
|
||||
const running = dispose()
|
||||
let settled = false
|
||||
void running.then(() => { settled = true })
|
||||
await vi.waitFor(() => {
|
||||
expect(settled).toBe(false)
|
||||
expect(JSON.parse(readFileSync(claimPath, 'utf8'))).toMatchObject({ pid: process.pid })
|
||||
}, { timeout: 5_000, interval: 1 })
|
||||
await running
|
||||
expect(existsSync(claimPath)).toBe(false)
|
||||
}, 20_000)
|
||||
|
||||
it('refuses to start when the owner state cannot be claimed', async () => {
|
||||
// The state directory is a file, so the claim cannot be created and that is not a second host.
|
||||
const root = mkdtempSync(join(tmpdir(), 'liveshare-claim-failure-'))
|
||||
temporaryRoots.push(root)
|
||||
const blocked = join(root, 'state')
|
||||
writeFileSync(blocked, '')
|
||||
await expect(apply(ownerRoutes().host, { ownerStateFile: join(blocked, 'owner-shares.json') } satisfies Config))
|
||||
.rejects.toThrow(/EEXIST|ENOTDIR|not a directory/)
|
||||
})
|
||||
|
||||
it('releases the claim when the host fails to finish mounting', async () => {
|
||||
// A setup step that throws after the claim must not leave owner-host.json naming this live pid:
|
||||
// another host would stay read-only until this process exited.
|
||||
const root = mkdtempSync(join(tmpdir(), 'liveshare-mount-failure-'))
|
||||
temporaryRoots.push(root)
|
||||
const file = join(root, 'owner-shares.json')
|
||||
writeFileSync(file, JSON.stringify({ shares: [] }))
|
||||
const { host } = ownerRoutes()
|
||||
const mounting = {
|
||||
apply: async (context: Context, config: Config) => {
|
||||
await apply(context, config)
|
||||
// The claim is held at this point, so this stands for any later setup step that throws.
|
||||
throw new Error('mount aborted after the claim')
|
||||
},
|
||||
}
|
||||
const fiber = host.plugin(mounting, { ownerStateFile: file } satisfies Config)
|
||||
await fiber.inertia
|
||||
await vi.waitFor(() => { expect(existsSync(ownerHostClaimPath(root))).toBe(false) })
|
||||
// The claim names no holder, so the next start takes the state over instead of reading it.
|
||||
closers.push(await apply(ownerRoutes().host, { ownerStateFile: file } satisfies Config))
|
||||
expect(JSON.parse(readFileSync(ownerHostClaimPath(root), 'utf8'))).toMatchObject({ pid: process.pid })
|
||||
}, 20_000)
|
||||
|
||||
it('leaves restored shares unregistered while another live host holds the owner state', async () => {
|
||||
// A second dsh on the same home must not move the holder's Relay registrations: the holder's next
|
||||
// authority read would then answer for a registration the Relay has already replaced.
|
||||
const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
|
||||
await new Promise<void>((resolve) => { holder.once('spawn', resolve) })
|
||||
onTestFinished(() => { holder.kill() })
|
||||
const file = ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, [storedRecord('held-share', {})])
|
||||
writeFileSync(ownerHostClaimPath(dirname(file)), JSON.stringify({ hostId: 'other-host', pid: holder.pid }))
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
onTestFinished(() => { warn.mockRestore() })
|
||||
// A registration reaches the Relay only as a tunnel command, so the command is what this case
|
||||
// watches: a host that sent none never starts the worker, and no upgrade can follow from it.
|
||||
const commands: TunnelWorkerInput[] = []
|
||||
const send = vi.spyOn(TunnelWorker.prototype, 'send').mockImplementation((command) => { commands.push(command) })
|
||||
|
||||
const { host } = ownerRoutes()
|
||||
closers.push(await apply(host, { ownerStateFile: file } satisfies Config))
|
||||
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining(`pid ${String(holder.pid)}`))
|
||||
// The claim still names the holder while this host serves: it did not take the state over.
|
||||
expect(JSON.parse(readFileSync(ownerHostClaimPath(dirname(file)), 'utf8'))).toMatchObject({ hostId: 'other-host' })
|
||||
// The owner page lists shares while it is open, which is the read a working host is seen through.
|
||||
await host.liveshareShares.list()
|
||||
expect(commands).toEqual([])
|
||||
send.mockRestore()
|
||||
}, 20_000)
|
||||
|
||||
it('arms no restored deadline while another live host holds the owner state', async () => {
|
||||
// The restored record can name a deadline the holder has since changed, so this host must not stop the
|
||||
// Sessions sharing it: only the holder knows when the State's shares end.
|
||||
const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
|
||||
await new Promise<void>((resolve) => { holder.once('spawn', resolve) })
|
||||
onTestFinished(() => { holder.kill() })
|
||||
const cancel = vi.fn()
|
||||
const file = ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, [
|
||||
storedRecord('held-share', { sessionMode: 'write', expiresAt: '2026-09-02T00:00:00.000Z' }),
|
||||
])
|
||||
writeFileSync(ownerHostClaimPath(dirname(file)), JSON.stringify({ hostId: 'other-host', pid: holder.pid }))
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
onTestFinished(() => { warn.mockRestore() })
|
||||
|
||||
const { host } = ownerRoutes({ agents: { get: () => liveAgent('session-held-share', cancel) } })
|
||||
closers.push(await apply(host, { ownerStateFile: file } satisfies Config))
|
||||
|
||||
await host.liveshareShares.list()
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining(`pid ${String(holder.pid)}`))
|
||||
// The stored deadline has already passed; an armed timer would have stopped this turn by now.
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
expect(cancel).not.toHaveBeenCalled()
|
||||
}, 20_000)
|
||||
})
|
||||
@@ -1,6 +1,17 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { apply, type Config } from '../src/host/share-host.ts'
|
||||
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
|
||||
|
||||
/** An owner state directory outside the real DSH home, which takes a host claim when a host starts. */
|
||||
function isolatedState(): { config: Config; dir: string } {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'liveshare-host-share-'))
|
||||
onTestFinished(() => { rmSync(dir, { recursive: true, force: true }) })
|
||||
return { config: { ownerStateFile: join(dir, 'owner-shares.json') }, dir }
|
||||
}
|
||||
|
||||
describe('liveshare owner host routes', () => {
|
||||
it('registers body-mode metadata required by the connection Fetch contract', async () => {
|
||||
@@ -18,8 +29,7 @@ describe('liveshare owner host routes', () => {
|
||||
webServer: { port: 3092 },
|
||||
})
|
||||
|
||||
const config: Config = {}
|
||||
await apply(host, config)
|
||||
await apply(host, isolatedState().config)
|
||||
|
||||
expect(paths).toEqual([
|
||||
// Share management is the `liveshareShares` Remote; these four are the sign-in and credential
|
||||
@@ -42,10 +52,27 @@ describe('liveshare owner host routes', () => {
|
||||
webServer: { port: 3092 },
|
||||
})
|
||||
|
||||
await apply(host, {} satisfies Config)
|
||||
await apply(host, isolatedState().config satisfies Config)
|
||||
|
||||
for (const gone of ['/api/liveshare.requests', '/api/liveshare.grantView', '/api/liveshare.revokeView']) {
|
||||
expect(paths, gone).not.toContain(gone)
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses share writes after a successor replaces the claim', async () => {
|
||||
const { config, dir } = isolatedState()
|
||||
const host = Object.assign(new Context(), {
|
||||
connection: {
|
||||
authenticatedUrl: () => 'http://127.0.0.1:3092/?token=test',
|
||||
fetch: { register: () => Promise.resolve(async () => {}) },
|
||||
},
|
||||
webServer: { port: 3092 },
|
||||
})
|
||||
const dispose = await apply(host, config)
|
||||
onTestFinished(() => dispose())
|
||||
// A record naming another live host ends this host's ownership without restarting it.
|
||||
writeFileSync(ownerHostClaimPath(dir), JSON.stringify({ hostId: 'successor', pid: process.pid + 100_000 }))
|
||||
await expect(host.liveshareShares.create({ sessionId: 'session-1' }))
|
||||
.rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
|
||||
})
|
||||
})
|
||||
@@ -128,6 +128,44 @@ describe('Liveshare global share manager', () => {
|
||||
expect(screen.getByText('First session')).toBeDefined()
|
||||
})
|
||||
|
||||
it('states a stop the holder of the share state refused, not a failed stop', async () => {
|
||||
await showManager(async () => accepted({ shares: ROWS as never }), undefined, () => {}, {
|
||||
stop: async () => refused('liveshareShares/owner-state-held', {}),
|
||||
})
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getAllByRole('button', { name: en['manage.cancelShare'] })[0]!)
|
||||
})
|
||||
const confirm = screen.getByRole('dialog', { name: en['manage.stop.title'] })
|
||||
await act(async () => {
|
||||
fireEvent.click(within(confirm).getByRole('checkbox', { name: en['manage.stop.acknowledge'] }))
|
||||
})
|
||||
await act(async () => {
|
||||
fireEvent.click(within(confirm).getByRole('button', { name: en['dialog.stop'] }))
|
||||
})
|
||||
// The owner acts in the process holding the state, so this page names it instead of the failure.
|
||||
expect(screen.getByRole('alert').textContent).toBe(en['dialog.ownerStateHeld'])
|
||||
expect(screen.getByText('First session')).toBeDefined()
|
||||
})
|
||||
|
||||
it('cancels the stop as failed when the call itself rejects', async () => {
|
||||
await showManager(async () => accepted({ shares: ROWS as never }), undefined, () => {}, {
|
||||
stop: async () => { throw new Error('gateway lost') },
|
||||
})
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getAllByRole('button', { name: en['manage.cancelShare'] })[0]!)
|
||||
})
|
||||
const confirm = screen.getByRole('dialog', { name: en['manage.stop.title'] })
|
||||
await act(async () => {
|
||||
fireEvent.click(within(confirm).getByRole('checkbox', { name: en['manage.stop.acknowledge'] }))
|
||||
})
|
||||
await act(async () => {
|
||||
fireEvent.click(within(confirm).getByRole('button', { name: en['dialog.stop'] }))
|
||||
})
|
||||
// A lost channel states the same failure as a refused stop; the share stays listed either way.
|
||||
expect(screen.getByRole('alert').textContent).toBe(en['dialog.stopFailed'])
|
||||
expect(screen.getByText('First session')).toBeDefined()
|
||||
})
|
||||
|
||||
it('cancels the stop confirmation without stopping the share', async () => {
|
||||
await showManager(async () => accepted({ shares: ROWS as never }))
|
||||
await act(async () => {
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/** The claim one running host takes on a LiveShare owner state directory. */
|
||||
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import {
|
||||
claimOwnerHost,
|
||||
ownerHostClaimPath,
|
||||
OwnerHostClaimHeldError,
|
||||
} from '../src/host/owner-host-claim.ts'
|
||||
|
||||
const created: string[] = []
|
||||
|
||||
function tempDir(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-owner-claim-'))
|
||||
created.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of created.splice(0)) rmSync(dir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
/** A record this process did not write. */
|
||||
function writeClaim(dir: string, value: string): void {
|
||||
writeFileSync(ownerHostClaimPath(dir), value)
|
||||
}
|
||||
|
||||
describe('one claim per owner state directory', () => {
|
||||
it('creates the directory it claims and releases what it took', () => {
|
||||
const dir = join(tempDir(), 'nested')
|
||||
const claim = claimOwnerHost(dir)
|
||||
expect(existsSync(ownerHostClaimPath(dir))).toBe(true)
|
||||
claim.release()
|
||||
expect(existsSync(ownerHostClaimPath(dir))).toBe(false)
|
||||
})
|
||||
|
||||
it('reports whether the claim file still names this host', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
expect(claim.holds()).toBe(true)
|
||||
// A successor's record ends this host's ownership without touching this process.
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'successor-host', pid: process.pid + 1 }))
|
||||
expect(claim.holds()).toBe(false)
|
||||
writeClaim(dir, '[]')
|
||||
expect(claim.holds()).toBe(false)
|
||||
writeClaim(dir, 'not json')
|
||||
expect(claim.holds()).toBe(false)
|
||||
rmSync(ownerHostClaimPath(dir), { force: true })
|
||||
expect(claim.holds()).toBe(false)
|
||||
claim.release()
|
||||
})
|
||||
|
||||
it('reclaims a record this process left behind', () => {
|
||||
const dir = tempDir()
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'earlier-host', pid: process.pid }))
|
||||
const claim = claimOwnerHost(dir)
|
||||
onTestFinished(() => { claim.release() })
|
||||
// Every host in one process shares the state, so a record naming this process is not a second owner.
|
||||
const record = JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8')) as { hostId: string; pid: number }
|
||||
expect(record.pid).toBe(process.pid)
|
||||
expect(record.hostId).not.toBe('earlier-host')
|
||||
})
|
||||
|
||||
it('refuses a claim another live host holds', () => {
|
||||
const dir = tempDir()
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'other-host', pid: process.pid + 100_000 }))
|
||||
expect(() => claimOwnerHost(dir, { alive: () => true })).toThrow(OwnerHostClaimHeldError)
|
||||
})
|
||||
|
||||
it('reads a holder this user cannot signal as alive', () => {
|
||||
const dir = tempDir()
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'other-host', pid: process.pid + 1 }))
|
||||
vi.spyOn(process, 'kill').mockImplementation(() => {
|
||||
throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' })
|
||||
})
|
||||
expect(() => claimOwnerHost(dir)).toThrow(OwnerHostClaimHeldError)
|
||||
})
|
||||
|
||||
it('reclaims a claim whose process is gone', () => {
|
||||
const dir = tempDir()
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'dead-host', pid: 999_999 }))
|
||||
const claim = claimOwnerHost(dir, { alive: () => false })
|
||||
onTestFinished(() => { claim.release() })
|
||||
const record = JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8')) as { hostId: string; pid: number }
|
||||
expect(record.pid).toBe(process.pid)
|
||||
expect(record.hostId).not.toBe('dead-host')
|
||||
})
|
||||
|
||||
it('reclaims a record whose holder field cannot be read', () => {
|
||||
for (const value of ['not json', '{}', '{"pid":"7"}', '{"pid":0}', '{"pid":-1}', '{"pid":1.5}']) {
|
||||
const dir = tempDir()
|
||||
writeClaim(dir, value)
|
||||
const claim = claimOwnerHost(dir)
|
||||
onTestFinished(() => { claim.release() })
|
||||
expect(JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8'))).toMatchObject({ pid: process.pid })
|
||||
}
|
||||
})
|
||||
|
||||
it('publishes its record beside the claim and leaves no staging file', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
onTestFinished(() => { claim.release() })
|
||||
expect(readdirSync(dir)).toEqual(['owner-host.json'])
|
||||
expect(JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8'))).toMatchObject({ pid: process.pid })
|
||||
// The record is whole the moment the claim name exists, so a reader never sees an empty claim.
|
||||
expect(claim.holds()).toBe(true)
|
||||
})
|
||||
|
||||
// A permission denial is the only portable-to-POSIX way to fail this write; Windows cannot stage it.
|
||||
it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('surfaces a claim it cannot create', () => {
|
||||
const dir = tempDir()
|
||||
chmodSync(dir, 0o500)
|
||||
try {
|
||||
// A directory that refuses the file names a failure other than contention.
|
||||
expect(() => claimOwnerHost(dir)).toThrow()
|
||||
} finally {
|
||||
chmodSync(dir, 0o700)
|
||||
}
|
||||
expect(existsSync(ownerHostClaimPath(dir))).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves a record another host publishes after this call judged the earlier one', () => {
|
||||
const dir = tempDir()
|
||||
const path = ownerHostClaimPath(dir)
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'dead-host', pid: 999_999 }))
|
||||
// The competing host publishes after this call read and judged the dead record, so the reread before
|
||||
// the removal sees a record this call never judged. That record is its owner's, so the removal skips
|
||||
// it; the retry then finds the same claim refused and this host reports the state as held.
|
||||
let published = false
|
||||
expect(() => claimOwnerHost(dir, {
|
||||
alive: () => {
|
||||
if (published) return true
|
||||
published = true
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'raced-host', pid: 999_999 }))
|
||||
return false
|
||||
},
|
||||
})).toThrow(OwnerHostClaimHeldError)
|
||||
expect(readFileSync(path, 'utf8')).toContain('raced-host')
|
||||
})
|
||||
|
||||
it('rethrows a claim that cannot be created for a reason other than an existing file', () => {
|
||||
const dir = tempDir()
|
||||
mkdirSync(ownerHostClaimPath(dir))
|
||||
expect(() => claimOwnerHost(dir)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('release', () => {
|
||||
it('leaves a claim that now names a successor alone', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
writeClaim(dir, JSON.stringify({ hostId: 'successor-host', pid: 4_242 }))
|
||||
claim.release()
|
||||
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toContain('successor-host')
|
||||
})
|
||||
|
||||
it('does nothing when the claim file is already gone', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
rmSync(ownerHostClaimPath(dir))
|
||||
expect(() => { claim.release() }).not.toThrow()
|
||||
})
|
||||
|
||||
it('does nothing when the claim file no longer parses', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
writeClaim(dir, 'not json')
|
||||
claim.release()
|
||||
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toBe('not json')
|
||||
})
|
||||
|
||||
it('does nothing when the claim file is no longer a record', () => {
|
||||
const dir = tempDir()
|
||||
const claim = claimOwnerHost(dir)
|
||||
writeClaim(dir, '[]')
|
||||
claim.release()
|
||||
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toBe('[]')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The owner sign-in routes against the host state they share with the owner-state claim.
|
||||
*
|
||||
* A credential is this host's own sign-in and commits on every host. The passes that act for the
|
||||
* shares — the identity probe, the claim, and the offline re-registration — reach the holder's Relay
|
||||
* registrations, so a host that does not own the owner state runs none of them.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { OwnerAuthorizations } from '../src/host/owner-authorization.ts'
|
||||
import { registerOwnerHttpRoutes } from '../src/host/owner-http-routes.ts'
|
||||
|
||||
const RELAY = 'https://relay.example.test/liveshare'
|
||||
const CREDENTIAL = 'payload.signature'
|
||||
|
||||
/** One host's owner sign-in routes over stub worker passes. */
|
||||
interface Harness {
|
||||
readonly call: (path: string, body: unknown) => Promise<Response>
|
||||
readonly tunnel: Record<keyof ReturnType<typeof stubTunnel>, ReturnType<typeof vi.fn>>
|
||||
readonly dispose: () => void
|
||||
}
|
||||
|
||||
function stubTunnel(): {
|
||||
probeRelayCredentialSupport: (relay: string) => Promise<void>
|
||||
claimOwnedShares: (relay: string, credential: string | undefined) => Promise<{ claimed: number; skipped: number }>
|
||||
reregisterOfflineShares: (relay: string, credential: unknown) => void
|
||||
credentialForRelay: (relay: string, credential: unknown) => string | undefined
|
||||
ownerIdentityStatus: (relay: string, extra: object, credential: unknown) => object
|
||||
factsFor: (relay: string) => { supportsCredentials?: boolean; claim?: { claimed: number; skipped: number } }
|
||||
} {
|
||||
return {
|
||||
probeRelayCredentialSupport: async () => {},
|
||||
claimOwnedShares: async () => ({ claimed: 1, skipped: 0 }),
|
||||
reregisterOfflineShares: () => {},
|
||||
credentialForRelay: () => CREDENTIAL,
|
||||
ownerIdentityStatus: (relay: string) => ({ state: 'verified', relay }),
|
||||
factsFor: () => ({}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Temporary directories this spec created, removed once every host is closed. */
|
||||
const roots: string[] = []
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
/**
|
||||
* Build the routes over one stub worker.
|
||||
* @param ownerStateHeld Whether another running host owns the owner state.
|
||||
*/
|
||||
function harness(ownerStateHeld: boolean): Harness {
|
||||
const root = mkdtempSync(join(tmpdir(), 'liveshare-owner-http-'))
|
||||
roots.push(root)
|
||||
const routes = new Map<string, (request: Request) => Promise<Response>>()
|
||||
const tunnel = Object.fromEntries(Object.entries(stubTunnel()).map(([name, value]) => [name, vi.fn(value)]))
|
||||
// These routes only register Fetch handlers, so the registry is the whole Connection this spec supplies.
|
||||
const ctx = new Context()
|
||||
ctx.provide('connection', {
|
||||
fetch: {
|
||||
register: (route: { readonly path: string; readonly fetch: (request: Request) => Promise<Response> }) => {
|
||||
routes.set(route.path, route.fetch)
|
||||
return async () => {}
|
||||
},
|
||||
},
|
||||
})
|
||||
const connection = ctx.connection
|
||||
registerOwnerHttpRoutes({
|
||||
connection,
|
||||
tunnel: tunnel as never,
|
||||
captureOwnerOperation: () => ({
|
||||
relay: RELAY,
|
||||
relayRevision: 0,
|
||||
instanceKey: 'instance',
|
||||
}),
|
||||
ownerOperationCurrent: () => true,
|
||||
ownerAuthorizations: new OwnerAuthorizations(),
|
||||
ownerCredentialFile: join(root, 'owner-credential.json'),
|
||||
storedCredential: () => undefined,
|
||||
setStoredCredential: () => {},
|
||||
ownerStateHeld: () => ownerStateHeld,
|
||||
disposed: () => false,
|
||||
})
|
||||
return {
|
||||
tunnel: tunnel as Harness['tunnel'],
|
||||
dispose: () => {},
|
||||
call: (path, body) => routes.get(path)!(new Request(`http://owner.local${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
describe('a credential imported by one host', () => {
|
||||
it('probes, claims, and re-registers when this host owns the owner state', async () => {
|
||||
const h = harness(false)
|
||||
const stored = await h.call('/api/liveshare.ownerCredential', { credential: CREDENTIAL })
|
||||
|
||||
expect(stored.status).toBe(200)
|
||||
expect(h.tunnel.probeRelayCredentialSupport).toHaveBeenCalledWith(RELAY)
|
||||
expect(h.tunnel.claimOwnedShares).toHaveBeenCalledWith(RELAY, CREDENTIAL)
|
||||
expect(h.tunnel.reregisterOfflineShares).toHaveBeenCalledWith(RELAY, expect.objectContaining({ credential: CREDENTIAL }))
|
||||
})
|
||||
|
||||
it('stores the credential without reaching the holder\'s Relay when another host owns the state', async () => {
|
||||
const h = harness(true)
|
||||
const stored = await h.call('/api/liveshare.ownerCredential', { credential: CREDENTIAL })
|
||||
|
||||
// The sign-in is this host's own, so it commits and reports the identity it now holds.
|
||||
expect(stored.status).toBe(200)
|
||||
await expect(stored.json()).resolves.toMatchObject({ state: 'verified' })
|
||||
// Registering these shares would replace the registrations the holder is serving.
|
||||
expect(h.tunnel.probeRelayCredentialSupport).not.toHaveBeenCalled()
|
||||
expect(h.tunnel.claimOwnedShares).not.toHaveBeenCalled()
|
||||
expect(h.tunnel.reregisterOfflineShares).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -68,6 +68,7 @@ interface Harness {
|
||||
readonly sourceConfined: ReturnType<typeof vi.fn>
|
||||
readonly storedCredential: ReturnType<typeof vi.fn>
|
||||
readonly effectiveRelay: ReturnType<typeof vi.fn>
|
||||
readonly holdOwnerState: (held: boolean) => void
|
||||
}
|
||||
|
||||
function harness(): Harness {
|
||||
@@ -109,9 +110,11 @@ function harness(): Harness {
|
||||
const sourceConfined = vi.fn(() => true)
|
||||
const storedCredential = vi.fn(() => undefined)
|
||||
const effectiveRelay = vi.fn(() => effective)
|
||||
let ownerStateHeld = false
|
||||
const operations = createOwnerShareOperations({
|
||||
ownerShares,
|
||||
pendingRemovals,
|
||||
ownerStateHeld: () => ownerStateHeld,
|
||||
allowedSubjectIds: [],
|
||||
forks,
|
||||
viewerRead,
|
||||
@@ -136,6 +139,7 @@ function harness(): Harness {
|
||||
operations, ownerShares, pendingRemovals, tunnel, relay, viewerRead, forks, offeredCapabilities, workspaces,
|
||||
persistOwnerState, applySourceAccess, accessChanged, cancelShareTurn, cancelChildTurns, reconcileSourceAccess,
|
||||
selectRelayAddress, bumpRelayRevision, sourceConfined, storedCredential, effectiveRelay,
|
||||
holdOwnerState: (held: boolean) => { ownerStateHeld = held },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -866,3 +870,59 @@ describe('Relay checks', () => {
|
||||
expect(h.tunnel.probeRelayPublish).toHaveBeenCalledWith(RELAY, expect.objectContaining({ shareId: '' }))
|
||||
})
|
||||
})
|
||||
|
||||
describe('reading the owner identity without the state', () => {
|
||||
it('reports what this host holds without asking the Relay for support', async () => {
|
||||
const h = harness()
|
||||
h.holdOwnerState(true)
|
||||
// The credential it reports is the one a login commits here; the probe would ask the holder's
|
||||
// Relay on this host's behalf, and the owner-state-held case refuses the actions that read it.
|
||||
await expect(h.operations.identity({})).resolves.toMatchObject({ relay: RELAY })
|
||||
expect(h.tunnel.ownerIdentityStatus).toHaveBeenCalledWith(RELAY, {}, undefined)
|
||||
expect(h.tunnel.probeRelayCredentialSupport).not.toHaveBeenCalled()
|
||||
expect(h.persistOwnerState).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a state another live host owns', () => {
|
||||
it('refuses every write and still lists what is shared', async () => {
|
||||
const h = harness()
|
||||
h.ownerShares.set('share-1', storedShare())
|
||||
h.holdOwnerState(true)
|
||||
|
||||
for (const write of [
|
||||
() => h.operations.create({ sessionId: 'session-1' }),
|
||||
// The persisted record is the whole map, so an addition from a stale snapshot rolls back every
|
||||
// share the holder created, changed, or stopped since this host restored its own.
|
||||
() => h.operations.addSessions({ shareId: 'share-1', sessionIds: ['session-2'] }),
|
||||
() => h.operations.stop({ shareId: 'share-1' }),
|
||||
() => h.operations.updatePermissions({ shareId: 'share-1', sessionMode: 'write' }),
|
||||
// A request that repeats the stored state installs an access layer instead of returning.
|
||||
() => h.operations.updatePermissions({ shareId: 'share-1' }),
|
||||
() => h.operations.setCapabilities({ shareId: 'share-1', viewerPlugins: [], viewerPluginAccess: 'none' }),
|
||||
() => h.operations.setRelay({ relayUrl: null }),
|
||||
// Relay probes change state as well: testRelay persists owed removals from this host's stale
|
||||
// maps, testPublish registers a throwaway share on the holder's Relay, and audit presents a
|
||||
// management token.
|
||||
() => h.operations.testRelay(),
|
||||
() => h.operations.testPublish({ sessionId: 'session-1' }),
|
||||
() => h.operations.audit({ shareId: 'share-1' }),
|
||||
]) {
|
||||
await expect(write()).rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
|
||||
}
|
||||
// No write reached a Relay, a stored record, an installed layer, or the state file.
|
||||
expect(h.tunnel.send).not.toHaveBeenCalled()
|
||||
expect(h.ownerShares.get('share-1')).toBeDefined()
|
||||
expect(h.persistOwnerState).not.toHaveBeenCalled()
|
||||
expect(h.applySourceAccess).not.toHaveBeenCalled()
|
||||
expect(h.tunnel.probeRelayPublish).not.toHaveBeenCalled()
|
||||
|
||||
const listed = await h.operations.list()
|
||||
expect(listed.shares.map(share => share.shareId)).toEqual(['share-1'])
|
||||
// Everything that acts on the holder's Relay registration, including the title reconciliation that
|
||||
// re-registers a renamed share, stays with the holder.
|
||||
expect(h.relay.readRelayAuthority).not.toHaveBeenCalled()
|
||||
expect(h.tunnel.reconcileShareTitles).not.toHaveBeenCalled()
|
||||
expect(h.tunnel.flushPendingRemovals).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1204,6 +1204,15 @@ describe('Liveshare dialog stored-record branches', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('states a create the holder of the share state refused, not an unreachable Host', async () => {
|
||||
await showControlled({ overrides: { create: async () => refused('liveshareShares/owner-state-held', {}) } })
|
||||
const button = screen.getByRole('button', { name: 'Create share' })
|
||||
await vi.waitFor(() => { expect(button).toHaveProperty('disabled', false) })
|
||||
await act(async () => { fireEvent.click(button) })
|
||||
|
||||
expect(screen.getByRole('alert').textContent).toBe(en['dialog.ownerStateHeld'])
|
||||
})
|
||||
|
||||
it('adopts a created share whose Host reported no session permission', async () => {
|
||||
await showControlled({
|
||||
overrides: {
|
||||
|
||||
@@ -168,8 +168,8 @@ describe('relay access adoption', () => {
|
||||
expect(h.viewerRead.recheckAdmission).toHaveBeenCalledWith('share-1')
|
||||
expect(h.viewerRead.closeViewerStreams).toHaveBeenCalledWith('share-1', revoked)
|
||||
expect(h.cancelChildTurns).toHaveBeenCalledWith('share-1', revoked)
|
||||
// A narrower admission can have ended a viewer's grant, and the host attributes no turn to a
|
||||
// requester: it stops whatever the Session runs now.
|
||||
// A narrower admission can have ended a viewer's grant, so the host stops the turns a viewer
|
||||
// started; the owner's own turn keeps running.
|
||||
expect(h.cancelShareTurn).toHaveBeenCalledWith('share-1')
|
||||
// The Session's sandbox follows its shares, so the host reconciles it after the change.
|
||||
expect(h.reconcileSourceAccess).toHaveBeenCalledWith('session-1')
|
||||
@@ -252,15 +252,16 @@ describe('relay authority reads', () => {
|
||||
expect(h.cancelShareTurn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('invalidates held authority for an answer whose JSON cannot be read', async () => {
|
||||
it('keeps held authority for an answer whose JSON cannot be read', async () => {
|
||||
const h = harness()
|
||||
h.ownerShares.set('share-1', storedShare())
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
|
||||
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
|
||||
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
|
||||
expect(h.viewerRead.closeShare).not.toHaveBeenCalled()
|
||||
expect(h.cancelShareTurn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('invalidates held authority for a refused or unreadable answer', async () => {
|
||||
it('keeps held authority for a failed or unreadable answer', async () => {
|
||||
for (const answer of [
|
||||
() => Promise.resolve(new Response('no', { status: 500 })),
|
||||
() => Promise.resolve(Response.json('not a record')),
|
||||
@@ -271,8 +272,42 @@ describe('relay authority reads', () => {
|
||||
h.ownerShares.set('share-1', storedShare({ online: true }))
|
||||
vi.stubGlobal('fetch', vi.fn(answer))
|
||||
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
|
||||
expect(h.viewerRead.closeShare).not.toHaveBeenCalled()
|
||||
expect(h.cancelShareTurn).not.toHaveBeenCalled()
|
||||
expect(h.cancelChildTurns).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('ends admission but not the owner turn when the Relay refuses this host', async () => {
|
||||
for (const status of [401, 403]) {
|
||||
const h = harness()
|
||||
h.ownerShares.set('share-1', storedShare({ online: true }))
|
||||
h.authority.applyRelayAccess('share-1', frame())
|
||||
// A fork a viewer started stays listed here, so its streams are released with the admission.
|
||||
h.forks.listForShare.mockReturnValue([{ childSessionId: 'child', creator: VIEWER }] as never)
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('no', { status })))
|
||||
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
|
||||
// No viewer input is served through the share any more: open calls and streams are released.
|
||||
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
|
||||
expect(h.viewerRead.closeViewerStreams).toHaveBeenCalledWith('share-1', VIEWER)
|
||||
expect(h.authority.viewerAdmitted('share-1', { providerId: 'mock', tenantId: 'tenant', subjectId: 'viewer' }))
|
||||
.toBe(false)
|
||||
await expect(h.authority.refreshRelayAccess('share-1')).rejects.toThrow('unavailable')
|
||||
// The owner's own turn keeps running, which is the difference from a withdrawn share.
|
||||
expect(h.cancelShareTurn).not.toHaveBeenCalled()
|
||||
expect(h.cancelChildTurns).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('ends held authority when the Relay states the share is gone', async () => {
|
||||
for (const status of [404, 410]) {
|
||||
const h = harness()
|
||||
h.ownerShares.set('share-1', storedShare({ online: true }))
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('gone', { status })))
|
||||
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
|
||||
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
|
||||
expect(h.cancelShareTurn).toHaveBeenCalledWith('share-1')
|
||||
expect(h.cancelChildTurns).toHaveBeenCalledWith('share-1')
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import { join } from 'node:path'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { WebSocketServer } from 'ws'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
|
||||
import { apply, type Config } from '../src/host/share-host.ts'
|
||||
import type {} from '../src/index.ts'
|
||||
|
||||
@@ -259,3 +260,45 @@ describe('restoring a share with a credential this host reads as expired', () =>
|
||||
await expect.poll(async () => (await listedShares(host))[0]?.online, { timeout: 15_000 }).toBe(true)
|
||||
}, 40_000)
|
||||
})
|
||||
|
||||
describe('a credential imported by a host that does not own the owner state', () => {
|
||||
it('is stored without re-registering or claiming the shares the holder serves', async () => {
|
||||
// The shares a second host holds are its restore snapshot and all offline, so re-registering them
|
||||
// would send an add-share for every one and move the registrations away from the holder.
|
||||
const relay = await relayStandIn(() => true)
|
||||
const directory = stateDirectory()
|
||||
const stateFile = ownerStateFile(directory, relay.origin)
|
||||
// Another live host holds the claim: the record names a process this spec did not start.
|
||||
writeFileSync(ownerHostClaimPath(directory), JSON.stringify({ hostId: 'holder', pid: process.ppid }))
|
||||
const { routes, host } = ownerRoutes()
|
||||
const dispose = await apply(host, {
|
||||
ownerStateFile: stateFile,
|
||||
ownerCredentialFile: join(directory, 'owner-credential.json'),
|
||||
} satisfies Config)
|
||||
disposers.push(async () => { await dispose(); await relay.close() })
|
||||
const holderClaim = readFileSync(ownerHostClaimPath(directory), 'utf8')
|
||||
|
||||
const imported = await routes.get('/api/liveshare.ownerCredential')?.(new Request(
|
||||
'http://owner.local/api/liveshare.ownerCredential',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ credential: RENEWED_TOKEN }),
|
||||
},
|
||||
))
|
||||
expect(imported?.status).toBe(200)
|
||||
// The sign-in is this host's own, so it commits and reads back as the credential it holds.
|
||||
expect(JSON.parse(readFileSync(join(directory, 'owner-credential.json'), 'utf8'))).toMatchObject({
|
||||
relay: relay.origin,
|
||||
credential: RENEWED_TOKEN,
|
||||
})
|
||||
// The identity this host reports is its own sign-in, which it can read; every owner action that
|
||||
// would change the shares is refused, and nothing it did reached the Relay.
|
||||
await expect(host.liveshareShares.identity({ relay: relay.origin }))
|
||||
.resolves.toMatchObject({ state: 'verified' })
|
||||
await expect(host.liveshareShares.addSessions({ shareId: SHARE_ID, sessionIds: [SESSION_ID] }))
|
||||
.rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
|
||||
expect(readFileSync(ownerHostClaimPath(directory), 'utf8')).toBe(holderClaim)
|
||||
expect(relay.upgrades).toHaveLength(0)
|
||||
}, 20_000)
|
||||
})
|
||||
@@ -93,6 +93,7 @@ function harness(options: Options = {}) {
|
||||
invalidateRelayAccess: vi.fn(),
|
||||
}
|
||||
const state = { disposed: false }
|
||||
const turnIsViewerDriven = vi.fn(() => true)
|
||||
const access = createSourceAccess({
|
||||
ctx: base,
|
||||
ownerShares,
|
||||
@@ -100,9 +101,10 @@ function harness(options: Options = {}) {
|
||||
relay,
|
||||
disposed: () => state.disposed,
|
||||
accessChanged: vi.fn(),
|
||||
turnIsViewerDriven,
|
||||
} as never)
|
||||
return {
|
||||
access, base, ownerShares, forks, relay, state,
|
||||
access, base, ownerShares, forks, relay, state, turnIsViewerDriven,
|
||||
live, agents, scope, tools, fs, sandboxPolicy, registered, scoped, session, typertLookup,
|
||||
}
|
||||
}
|
||||
@@ -281,7 +283,7 @@ describe('source layer installation refusals', () => {
|
||||
})
|
||||
|
||||
describe('turn and tool helpers', () => {
|
||||
it('stops the running turn of a share that ends, whoever started it', () => {
|
||||
it('stops the running turn of a share that ends when the share started it', () => {
|
||||
const h = harness()
|
||||
h.access.cancelShareTurn('absent')
|
||||
h.ownerShares.set('share-1', share())
|
||||
@@ -294,6 +296,15 @@ describe('turn and tool helpers', () => {
|
||||
expect(h.live.cancel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves a turn the owner started running when a share ends its grant', () => {
|
||||
const h = harness()
|
||||
h.ownerShares.set('share-1', share())
|
||||
h.turnIsViewerDriven.mockReturnValue(false)
|
||||
h.access.cancelShareTurn('share-1')
|
||||
expect(h.turnIsViewerDriven).toHaveBeenCalledWith('session-1')
|
||||
expect(h.live.cancel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('releases the Session’s layer once none of its shares is active', async () => {
|
||||
const h = harness()
|
||||
const granted = share()
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TunnelShareSpec } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
|
||||
import type { ViewerAnswer } from '../src/viewer-channel.ts'
|
||||
import { createTunnelSupervision, gatewayWorkerCommand, refreshedShareTitle } from '../src/host/tunnel-supervision.ts'
|
||||
import { createTunnelSupervision, gatewayWorkerCommand, ownerPlatform, refreshedShareTitle } from '../src/host/tunnel-supervision.ts'
|
||||
import { FakeTunnelWorker } from './tunnel-supervision-fake-worker.ts'
|
||||
|
||||
vi.mock('../src/host/tunnel-worker.ts', async () => {
|
||||
@@ -317,6 +317,16 @@ describe('registration payloads', () => {
|
||||
expect(host.supervision.shareSpec(spec() as never, undefined)).toMatchObject({ ownerDisplayName: 'relay.example.test' })
|
||||
})
|
||||
|
||||
it('reports the platform this process runs on and none outside the enum', () => {
|
||||
const reported = ownerPlatform()
|
||||
const h = harness()
|
||||
const payload = h.supervision.shareSpec(spec() as never, undefined)
|
||||
expect(payload.platform).toBe(reported)
|
||||
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('freebsd')
|
||||
expect(h.supervision.shareSpec(spec() as never, undefined)).not.toHaveProperty('platform')
|
||||
})
|
||||
|
||||
it('re-registers only offline shares of the credential relay', () => {
|
||||
const h = harness({
|
||||
shares: [
|
||||
@@ -646,3 +656,17 @@ describe('relay probes and claims', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('owner platform reporting', () => {
|
||||
it('maps the three systems the wire enum names', () => {
|
||||
expect(ownerPlatform('darwin')).toBe('macos')
|
||||
expect(ownerPlatform('win32')).toBe('windows')
|
||||
expect(ownerPlatform('linux')).toBe('linux')
|
||||
})
|
||||
|
||||
it('reports nothing for a system outside the enum', () => {
|
||||
for (const platform of ['freebsd', 'aix', 'sunos', 'android'] as const) {
|
||||
expect(ownerPlatform(platform), platform).toBeUndefined()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -2069,7 +2069,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
signature: '@Remote(\'list\') list(): Promise<OwnerShareList>',
|
||||
description: 'Refresh titles and Liveshare server authority, then list this host\'s shares.',
|
||||
description: 'List this host\'s shares, refreshing titles and Liveshare server authority when this host owns the state.',
|
||||
parameters: [],
|
||||
returns: 'Every share this host publishes.',
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user