Merge pull request #8323 from deepseek-harness/fix/forge-github-status-batches
fix(forge): bound status queries, share polls, and drop repeated reads
This commit is contained in:
commit
b87a481bcf
66 files changed
+4073
-510
No files matched your search
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-12-forge-status-briefs.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/architecture/2026-11-12-forge-status-briefs.md
|
||||
/agent-note-forge-status-briefs:
|
||||
en: 51cd3647298126c4
|
||||
zh: 07f18bcd7bd2a7c3
|
||||
/agent-note-forge-status-briefs/problem:
|
||||
en: f99803963e0818f4
|
||||
zh: b4aba14e12cdeede
|
||||
/agent-note-forge-status-briefs/decision:
|
||||
en: 847ad02b06062771
|
||||
zh: ce8747cbc2b15545
|
||||
/agent-note-forge-status-briefs/alternatives-considered:
|
||||
en: 4dfbe3ae83d89e7a
|
||||
zh: 74ded5f0f1b8c5b3
|
||||
/agent-note-forge-status-briefs/consequences:
|
||||
en: 2b4e5ebfef68df7e
|
||||
zh: 72e774ad90908f21
|
||||
@@ -0,0 +1,67 @@
|
||||
# Agent Note: Forge status briefs
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-12-forge-status-briefs.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The Session list shows a state glyph for every change request that a listed Session binds, and read the full snapshot of each one for it: up to 100 check contexts, reviewers, review threads, linked issues, and the repository's merge settings. The registry batches every due change request of a forge, and the GitHub provider put a host's whole batch in one GraphQL query. GitHub ends a request after 10 seconds of processing: a snapshot query of 20 deepseek-harness pull requests took 10.2 s, one of 30 answered HTTP 504, and one of 61 HTTP 502. Every watch of a new list run was due at once, so the list of a user with about 30 bound pull requests failed as a whole and retried as a whole. Opening a Session whose change request the list already watched read nothing, so its panel waited up to one idle interval for a newer status.
|
||||
|
||||
Other reads repeated without need. Change requests shared a fetch only when they became due in the same millisecond, so 14 list watches cost 30 queries an hour while they stayed aligned and 415 once they had drifted apart. Each time a Session's panel was shown again, the Host probed sign-in and looked the branch up again, and the client forced a second status read. Each saved viewed mark made every open changes view read all marks and all review threads again. A push or a `gh pr merge` by the agent started no status read.
|
||||
|
||||
## Decision
|
||||
|
||||
**Two levels of status.** A brief holds what a list shows: title, state, draft flag, mergeability, review decision, and combined check outcome. `ctx.forge.watchBrief` watches it; `ctx.forge.watch` watches the snapshot. A watched change request is polled for its snapshot while it has a snapshot watcher and for its brief otherwise. A snapshot holds a brief, so brief watchers receive every result. Providers read briefs through the optional `fetchBriefs`; the registry reads snapshots from a provider without it.
|
||||
|
||||
**GitHub brief query.** forge-github reads a brief from the pull request's own scalars and the `statusCheckRollup.state` of its head commit, 25 pull requests per query (`briefBatchSize`). Measured on deepseek-harness pull requests through `gh`, a query of 10 took 1.6 to 2.0 s, one of 25 took 2.5 to 3.4 s, and one of 50 took 2.9 to 6.8 s, at a rate-limit cost of 1 point each; 25 leaves a wider margin to GitHub's 10 seconds than 50 does. In a snapshot query the check contexts are the largest part: 174 of 186 KB and 1.4 of 3.8 s for 8 pull requests.
|
||||
|
||||
**GitHub snapshot queries of bounded size.** A Session can bind many pull requests, and its panel watches the snapshot of each. forge-github puts at most 8 pull requests of a host in one snapshot query (`snapshotBatchSize`): measured the same way, a query of 5 took 3.6 s, one of 8 took 4.4 to 6.3 s, and one of 10 took 5.8 s. Queries are sent one after another, because GitHub asks an account to send its requests serially. A query whose `gh` run fails, and one GitHub refuses, fails only its own pull requests.
|
||||
|
||||
**One provider call per query.** A provider may name `snapshotBatchSize` and `briefBatchSize` to the registry, and forge-github does. The registry then calls the provider once per that many due change requests of a host, one call after another, each within its own `fetchTimeoutMs`, and settles the watches of a call when it returns. A call that fails or outlives its deadline fails only its own change requests, and the results of earlier calls stay published. A provider that names no size, as forge-gitlab, is called once with every due change request of the forge.
|
||||
|
||||
**One fetch in flight per forge and level.** A snapshot fetch for an open panel does not wait behind the brief fetch of a long list, and a host sees at most two status requests of one registry at a time.
|
||||
|
||||
**Polls that share a fetch.** A fetch reads the due change requests of its forge and level, and also those past the midpoint of the wait after their latest status. Change requests that became due at different times therefore return to one fetch: the 14 list watches cost 30 queries an hour at the earlier intervals whether they were bound together, one after another, or had checks running for a while. A change request waits out the backoff after a failed read in full.
|
||||
|
||||
**Intervals.** An open change request is polled every 15 seconds while its checks run and every 60 seconds otherwise (`activeIntervalMs`, `idleIntervalMs`), at both levels. A status that first reports an unknown mergeability earns one poll at the active interval; one that reports it again waits the idle interval, because 11 of 98 open pull requests measured, all drafts stacked on another pull request's branch, kept reporting it.
|
||||
|
||||
**What the list already knows.** The list's run passes the state it stored for a change request as `known`. The registry times the first poll as it would after a read at `known.fetchedAt`, so a merged change request is not read again, and a run that follows another in the same process waits for the interval. Read times stay in memory; a state stored by an earlier process counts as read at the epoch.
|
||||
|
||||
**A status newer than the latest one.** A snapshot watcher and `refresh` may pass `maxAgeMs`. The Session panel and the review page pass `statusMaxAgeMs` (10 seconds) when they start, so opening a Session reads its change requests at once unless they were just read; showing the panel again and focusing the window call the `revisit` Remote, which polls with the same bound, while the reader's refresh stays forced. The installed desktop apps of two peer products do the same: Codex refetches a thread's pull request when the thread mounts with data older than 15 seconds, and Claude prefetches a session's pull request when its row is pressed, with a freshness of 10 seconds.
|
||||
|
||||
**Reads after the agent's commands.** After a push result, forge-session calls `ctx.forge.expectChange` for the visible change requests in the pushed repository: a watched one is polled at once and then at the active interval until a status reports running checks, for at most one idle interval. When a turn that had a tool result ends, forge-session refreshes the Session's visible change requests with the age of that result as `maxAgeMs`.
|
||||
|
||||
**Nothing read for a hidden page.** The client closes the panel streams, the list's state stream, and the review count stream once the page has been hidden for 30 seconds, and opens them again when it shows. The Host polls only while a stream is open, so it needs no report of the page's visibility, and it keeps polling while any tab of the page is visible.
|
||||
|
||||
**Panel state kept between followers.** A Session's panel leaves its last state, snapshots, and branch lookup when its last follower leaves, and the next panel of that Session starts from them unless the Session moved to another directory. It repeats neither the sign-in probe of a host found ready nor the branch lookup of a Session that shows a change request; a status read refused as unauthenticated starts one probe.
|
||||
|
||||
**Viewed marks kept on the Host.** The Host keeps the viewed marks read for a change request by head commit, under the bounds of the kept review threads. A saved mark replaces the kept state of its file and leaves the kept threads, so a save costs the provider's write and no further read.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Bounding snapshot queries only** keeps each query short, but a list of 61 pull requests then needs 8 queries and 38 s for fields the list never shows.
|
||||
|
||||
**A longer `fetchTimeoutMs` or concurrent snapshot queries** leave GitHub's processing time per query unchanged, and GitHub allows one account 60 s of GraphQL CPU time per 60 s.
|
||||
|
||||
**REST with conditional requests** returns HTTP 304 without rate-limit cost through `gh`, but takes one `gh` process per pull request, about 1.2 s each, and carries no combined check state.
|
||||
|
||||
**Webhooks** need a server that receives them; the Host is a local process that reads through the user's `gh`.
|
||||
|
||||
**A `level` option on `watch`** would give one method two listener types; two methods keep each listener's update type exact.
|
||||
|
||||
**Storing read times** would save the first brief read after a Host restart only when the restart falls within one poll interval, at the cost of a change to the stored record.
|
||||
|
||||
**A queue per host with a lane for user actions** would let a refresh pass a fetch in flight. The two levels already keep an open panel apart from the list, and a snapshot query takes 2 to 6 s, so the queue would save that much on a refresh at the cost of a second scheduler.
|
||||
|
||||
**A random offset on each interval** spreads requests over time, which is the opposite of what the measured cost needs: it would separate change requests that one query reads together.
|
||||
|
||||
**Pausing a host after a refused read** saves little: 14 change requests that were all refused as unauthenticated backed off together and cost 10 queries in an hour.
|
||||
|
||||
**A budget of one background query per interval** matters only past the size one fetch reads in time; 100 pull requests took two brief queries of 50 and 7.6 s.
|
||||
|
||||
**A faster cadence after a push**, 5 seconds for a minute as one peer product uses, needs two more settings; the active interval shows new checks at most about 10 seconds later.
|
||||
|
||||
## Consequences
|
||||
|
||||
For the case measured, 14 open and 17 merged bound pull requests, a poll of the list is one request of about 1.7 s in place of one query of 31 snapshots, which GitHub answered with HTTP 504, and the merged ones are not read. At the 60-second idle interval that is 59 queries an hour while the page is visible, and none while it is hidden. A change request past the midpoint of its wait is read with any fetch of its lane, so one whose neighbor has running checks is read up to twice as often as its own interval asks; the number of queries does not grow with it. A brief reports GitHub's combined check state, while a snapshot with a complete check list derives its own from the newest run of each check; the two agreed for all 61 open pull requests measured, and nothing reconciles them when they differ. One snapshot query and the continuation pages of its pull requests share one deadline, so a pull request with many review threads can fail the up to 8 pull requests of its query. A viewed mark changed on the code host itself shows after `reviewRefreshMs` or the reader's refresh. A page that stays visible without a reader keeps polling.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Agent Note: Forge 状态简报
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-12-forge-status-briefs.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
会话列表为每个已列出 Session 绑定的变更请求显示一个状态图标,此前为此读取每个变更请求的完整快照:最多 100 个检查 context、评审人、评审讨论、关联 issue 以及仓库的合并设置。注册表把同一个 forge 所有到期的变更请求合成一批,GitHub 提供方此前把一个主机的整批放进同一个 GraphQL 查询。GitHub 在处理一个请求超过 10 秒后终止它:包含 20 个 deepseek-harness pull request 的快照查询耗时 10.2 s,30 个的返回 HTTP 504,61 个的返回 HTTP 502。列表每次新的运行会让所有监听同时到期,所以绑定了约 30 个 pull request 的用户,列表会整批失败、整批重试。打开一个 Session 时,如果列表已经在监听它的变更请求,就不会触发任何读取,面板最长要等一个空闲间隔才有更新的状态。
|
||||
|
||||
还有一些读取是不必要的重复。变更请求只有在同一毫秒到期时才共用一次读取,所以 14 个列表监听在保持对齐时每小时 30 个查询,错开之后是 415 个。每次重新显示 Session 的面板,Host 都重新检查登录状态、重新按分支查找,客户端还会强制再读一次状态。每保存一个已审阅标记,所有打开的变更视图都会重读全部标记和全部评审讨论。Agent 的推送或 `gh pr merge` 不会触发状态读取。
|
||||
|
||||
## Decision
|
||||
|
||||
**两个层级的状态。** 简报包含列表显示的内容:标题、状态、草稿标记、可合并性、评审结论与检查汇总结果。`ctx.forge.watchBrief` 监听简报;`ctx.forge.watch` 监听快照。被监听的变更请求在有快照监听方时轮询快照,否则轮询简报。快照包含简报,所以简报监听方能收到每一次结果。提供方通过可选的 `fetchBriefs` 读取简报;提供方没有该方法时,注册表从它读取快照。
|
||||
|
||||
**GitHub 简报查询。** forge-github 从 pull request 自身的标量字段和 head 提交的 `statusCheckRollup.state` 读出简报,每个查询 25 个 pull request(`briefBatchSize`)。通过 `gh` 在 deepseek-harness 的 pull request 上实测,10 个的查询用 1.6 至 2.0 s,25 个的用 2.5 至 3.4 s,50 个的用 2.9 至 6.8 s,速率配额各消耗 1 点;25 个比 50 个离 GitHub 的 10 秒上限更远。快照查询里检查 context 占比最大:8 个 pull request 时占 186 KB 中的 174 KB、3.8 s 中的 1.4 s。
|
||||
|
||||
**大小有上限的 GitHub 快照查询。** 一个 Session 可以绑定多个 pull request,它的面板监听其中每一个的快照。forge-github 在一个快照查询里最多放同一主机的 8 个 pull request(`snapshotBatchSize`):用同样的方式实测,5 个的查询用 3.6 s,8 个的用 4.4 至 6.3 s,10 个的用 5.8 s。查询依次发送,因为 GitHub 要求同一账号串行发送请求。某个查询的 `gh` 运行失败或被 GitHub 拒绝时,只有该查询内的 pull request 失败。
|
||||
|
||||
**每个查询一次提供方调用。** 提供方可以向注册表声明 `snapshotBatchSize` 与 `briefBatchSize`,forge-github 声明了这两项。这时注册表为同一主机每这么多个到期的变更请求调用提供方一次,依次调用,每次调用有自己的 `fetchTimeoutMs`,并在调用返回时结算它的监听。某次调用失败或超过时限时,只有它读取的变更请求失败,之前各次调用的结果保持已发布。没有声明大小的提供方(如 forge-gitlab)仍然一次调用读取该 forge 所有到期的变更请求。
|
||||
|
||||
**每个 forge、每个层级同时只有一次读取。** 为打开的面板读取快照,不用排在长列表的简报读取后面;一个主机同时最多看到同一个注册表的两个状态请求。
|
||||
|
||||
**共用一次读取的轮询。** 一次读取除了读它的 forge 和层级上到期的变更请求,还读距上一次状态的等待已过半的变更请求。所以在不同时刻到期的变更请求会回到同一次读取里:14 个列表监听在此前的间隔下每小时 30 个查询,不论它们是同时绑定、逐个绑定,还是中途有检查运行过一阵。读取失败后的退避时间,变更请求会完整等完。
|
||||
|
||||
**间隔。** 打开状态的变更请求在检查运行时每 15 秒轮询一次,否则每 60 秒一次(`activeIntervalMs`、`idleIntervalMs`),两个层级相同。状态第一次报告可合并性未知时,按活跃间隔再轮询一次;再次报告未知时等待空闲间隔,因为实测的 98 个打开的 pull request 里有 11 个一直报告未知,它们都是叠在另一个 pull request 分支上的草稿。
|
||||
|
||||
**列表已经知道的状态。** 列表的运行把它为变更请求存下的状态作为 `known` 传入。注册表按“在 `known.fetchedAt` 读过一次”来安排首次轮询,所以已合并的变更请求不再读取,同一进程里紧接着的下一次运行会等到间隔到期。读取时间只保存在内存中;更早的进程存下的状态按在纪元时刻读取处理。
|
||||
|
||||
**比最近一次更新的状态。** 快照监听方和 `refresh` 都可以传入 `maxAgeMs`。会话面板和评审页开始时传入 `statusMaxAgeMs`(10 秒),所以打开 Session 会立即读取它的变更请求,除非刚刚读过;再次显示面板和窗口获得焦点时调用 `revisit` Remote,它按同样的上限轮询,读者手动刷新则仍然强制读取。两个同类产品已安装的桌面应用也是这样做的:Codex 在线程挂载且数据超过 15 秒时重新读取它的 pull request,Claude 在会话行被按下时预读它的 pull request,新鲜期为 10 秒。
|
||||
|
||||
**Agent 的命令之后的读取。** 收到推送结果后,forge-session 为被推送仓库里可见的变更请求调用 `ctx.forge.expectChange`:被监听的变更请求立即轮询,之后按活跃间隔轮询,直到状态报告检查正在运行为止,最长持续一个空闲间隔。有过工具结果的回合结束时,forge-session 刷新该 Session 可见的变更请求,以那个结果距今的时间作为 `maxAgeMs`。
|
||||
|
||||
**不为隐藏的页面读取。** 页面隐藏满 30 秒后,客户端关闭面板流、列表的状态流和评审计数流,页面再次显示时重新打开。Host 只在有流打开时轮询,所以不需要页面上报可见性;只要页面有一个标签页可见,它就继续轮询。
|
||||
|
||||
**在关注方之间保留面板状态。** Session 的面板在最后一个关注方离开时留下它最后的状态、快照和分支查找结果,该 Session 的下一个面板从它们开始,除非 Session 换到了其他目录。它不重复已确认就绪的托管平台的登录检查,也不重复已显示变更请求的 Session 的分支查找;状态读取被以未登录拒绝时会触发一次登录检查。
|
||||
|
||||
**Host 保留已审阅标记。** Host 按 head 提交保留为变更请求读到的已审阅标记,受与所保留评审讨论相同的限制。保存一个标记会替换所保留的对应文件状态,并保留评审讨论,所以一次保存只需要提供方的那次写入,不再读取。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只限制快照查询的大小**能让每个查询足够短,但 61 个 pull request 的列表仍需要 8 个查询和 38 s,而读回的字段列表根本不显示。
|
||||
|
||||
**调大 `fetchTimeoutMs` 或并发发送快照查询**不改变 GitHub 处理每个查询的时间,而且 GitHub 只允许一个账号每 60 s 使用 60 s 的 GraphQL CPU 时间。
|
||||
|
||||
**带条件请求的 REST** 经 `gh` 返回 HTTP 304 时不消耗速率配额,但每个 pull request 要启动一个 `gh` 进程,各约 1.2 s,而且没有检查汇总状态。
|
||||
|
||||
**Webhook** 需要一个接收它的服务端;Host 是本地进程,通过用户自己的 `gh` 读取。
|
||||
|
||||
**给 `watch` 加 `level` 选项**会让一个方法有两种监听方类型;分成两个方法,每种监听方的更新类型都是确定的。
|
||||
|
||||
**存储读取时间**只有在 Host 重启恰好落在一个轮询间隔之内时,才能省下重启后的第一次简报读取,代价是改动已存记录。
|
||||
|
||||
**每个主机一个队列、用户操作单独一条通道**能让刷新越过正在进行的读取。两个层级已经把打开的面板和列表分开,一个快照查询耗时 2 至 6 s,所以这个队列在一次刷新上最多省下这么多时间,代价是第二套调度。
|
||||
|
||||
**给每个间隔加随机偏移**会把请求在时间上摊开,这和实测的开销所需要的正相反:它会把一个查询本可以一起读的变更请求分开。
|
||||
|
||||
**读取被拒绝后暂停整个主机**省不下多少:14 个全部被以未登录拒绝的变更请求一起退避,一小时只花 10 个查询。
|
||||
|
||||
**每个间隔只发一个后台查询的预算**只在超出一次读取能及时读完的规模时才有意义;100 个 pull request 用了两个各 50 个的简报查询,共 7.6 s。
|
||||
|
||||
**推送之后用更快的节奏**(一个同类产品用 5 秒、持续一分钟)需要再加两个配置项;按活跃间隔,看到新检查最多晚约 10 秒。
|
||||
|
||||
## Consequences
|
||||
|
||||
在实测的场景里(绑定了 14 个打开、17 个已合并的 pull request),列表的一次轮询是一个约 1.7 s 的请求,取代原来包含 31 个快照、被 GitHub 以 HTTP 504 拒绝的查询,已合并的不再读取。按 60 秒的空闲间隔,页面可见时每小时 59 个查询,隐藏时没有。等待已过半的变更请求会随它所在通道的任何一次读取一起读,所以相邻的变更请求有检查在运行时,它被读取的频率最高是自身间隔的两倍;查询个数不会因此增加。简报报告 GitHub 的检查汇总状态,检查列表完整的快照则根据每个检查的最新一次运行自行得出结果;实测的 61 个打开的 pull request 两者全部一致,不一致时没有机制去对齐。一个快照查询和它的 pull request 的续页共用一个时限,所以评审讨论很多的 pull request 可能让它所在查询的最多 8 个 pull request 一起失败。在代码托管平台上直接改动的已审阅标记,要等到 `reviewRefreshMs` 之后或读者刷新时才显示。一直可见但没有人看的页面会继续轮询。
|
||||
@@ -878,6 +878,9 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
await captureStableAria(page, '[data-forge-session-hover]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE)
|
||||
await page.mouse.move(0, 0)
|
||||
await rowHover.waitFor({ state: 'detached' })
|
||||
// The Host's sign-in probe has answered once the panel state names a readiness, so a later probe would come from showing the panel.
|
||||
for await (const state of scaffold.ctx.forgePanel.follow(session, AbortSignal.timeout(20_000))) if (state.readiness !== null) break
|
||||
const probes = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.startsWith('["auth"')).length
|
||||
const panel = await showSessionPanel(page)
|
||||
const checkout = panel.locator('[data-forge-checkout]')
|
||||
const checkoutName = checkout.getByText(branch, { exact: true })
|
||||
@@ -898,6 +901,8 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
}), MODE)
|
||||
const beforeChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
|
||||
expect(beforeChecks.some(args => args.includes('id=rollup-7'))).toBe(false)
|
||||
// Showing the panel revisited it on the Host, which probes sign-in again only while the host is not ready.
|
||||
expect(beforeChecks.filter(args => args[0] === 'auth')).toHaveLength(probes)
|
||||
const checksRow = change.getByRole('button', { name: /^检查/ })
|
||||
await checksRow.click()
|
||||
const checks = page.getByRole('menu')
|
||||
@@ -1631,6 +1636,9 @@ it.skipIf(MODE === 'record')('opens a comment from the hover plus in one press w
|
||||
return { start: { x, y: start.y + start.height / 2 }, end: { x, y: end.y + end.height / 2 } }
|
||||
}
|
||||
await number('R3').waitFor()
|
||||
// The strip after README.md's last hunk leaves once the file's text was read for highlighting, which moves the rows
|
||||
// of notes.txt below it up; the positions this test measures for a drag hold only after that.
|
||||
await file.locator('[data-forge-diff-gap]').waitFor({ state: 'detached', timeout: 20_000 })
|
||||
|
||||
// The plus appears only on the hovered side of the hovered row, for the code as for the line number.
|
||||
expect(await plus('R3').isVisible()).toBe(false)
|
||||
@@ -2456,6 +2464,17 @@ it.skipIf(MODE === 'record')('reads and saves the viewed files of a change reque
|
||||
await expect.poll(() => panel.getAttribute('data-viewed')).toBe('changed')
|
||||
await panel.getByText('有新改动', { exact: true }).waitFor()
|
||||
await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 6')
|
||||
/** How many times the viewed marks and the review threads were read from the code host so far. */
|
||||
const reviewReads = async (): Promise<{ readonly marks: number; readonly threads: number }> => {
|
||||
const queries = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0)
|
||||
.map(line => (JSON.parse(line) as string[]).find(arg => arg.startsWith('query=')) ?? '')
|
||||
return {
|
||||
marks: queries.filter(query => query.includes('files(first: $first')).length,
|
||||
threads: queries.filter(query => query.includes('reviewThreads(first: $first')).length,
|
||||
}
|
||||
}
|
||||
await expect.poll(reviewReads, { timeout: 20_000 }).toEqual({ marks: 1, threads: 1 })
|
||||
const readsBefore = await reviewReads()
|
||||
|
||||
await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).check()
|
||||
await expect.poll(() => manifest.getAttribute('data-viewed')).toBe('viewed')
|
||||
@@ -2465,6 +2484,9 @@ it.skipIf(MODE === 'record')('reads and saves the viewed files of a change reque
|
||||
await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed')
|
||||
await expect.poll(async () => (JSON.parse(await readFile(join(root, 'state.json'), 'utf8')) as { readonly viewed?: Record<string, string> }).viewed)
|
||||
.toEqual({ 'package.json': 'VIEWED', 'docs/panel.md': 'UNVIEWED' })
|
||||
// The Host applies each saved mark to the marks it keeps and keeps the threads, so neither is read again.
|
||||
await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed')
|
||||
expect(await reviewReads()).toEqual(readsBefore)
|
||||
|
||||
// A refused mark returns to what GitHub keeps and says why.
|
||||
await writeFile(join(root, 'viewed.refused'), 'Resource not accessible by integration')
|
||||
|
||||
+22
-6
@@ -1272,13 +1272,22 @@ export interface Config {
|
||||
* `testPaths` and before the built-in rules.
|
||||
*/
|
||||
interfacePaths?: string[]
|
||||
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
|
||||
/**
|
||||
* Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit
|
||||
* and update time, and, counted apart, of viewed marks kept for later reads at the same head commit.
|
||||
*/
|
||||
maxCachedReviewBytes?: number
|
||||
/**
|
||||
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
|
||||
* request's update time does not change when a thread is resolved.
|
||||
* Age in milliseconds at which review threads and viewed marks kept in memory are read from the code host again; a
|
||||
* GitHub pull request's update time does not change when a thread is resolved, and nothing announces a mark changed
|
||||
* on the code host itself.
|
||||
*/
|
||||
reviewRefreshMs?: number
|
||||
/**
|
||||
* Age in milliseconds past which the status of a change request is read at once when a Session's panel or the
|
||||
* review page starts to show it.
|
||||
*/
|
||||
statusMaxAgeMs?: number
|
||||
/** Deadline in milliseconds for one lens `classify` call. */
|
||||
lensTimeoutMs?: number
|
||||
/** Most UTF-8 bytes of file text one lens `classify` call may read. */
|
||||
@@ -1328,18 +1337,18 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:833`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
export interface Config {
|
||||
/** Poll interval in milliseconds while checks run or mergeability is unknown. */
|
||||
/** Poll interval in milliseconds while checks run, and for one poll after a status first reports an unknown mergeability. */
|
||||
activeIntervalMs?: number
|
||||
/** Poll interval in milliseconds for a closed request or an open request whose checks have settled. */
|
||||
idleIntervalMs?: number
|
||||
/** Largest delay in milliseconds between polls after consecutive failures. */
|
||||
maxBackoffMs?: number
|
||||
/** Deadline in milliseconds for one provider fetch. */
|
||||
/** Deadline in milliseconds for one provider fetch: one polling call, or one read of complete checks. */
|
||||
fetchTimeoutMs?: number
|
||||
}
|
||||
```
|
||||
@@ -1369,6 +1378,13 @@ export interface Config {
|
||||
* one review read, which reports itself truncated past it.
|
||||
*/
|
||||
maxReviewThreads?: number
|
||||
/**
|
||||
* Most pull requests one snapshot query reads. The forge registry polls that many pull requests of a host per call,
|
||||
* each call within its own fetch deadline; a read of more pull requests on one host sends several queries in turn.
|
||||
*/
|
||||
snapshotBatchSize?: number
|
||||
/** The same bound for one brief query. */
|
||||
briefBatchSize?: number
|
||||
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
|
||||
@@ -1274,13 +1274,22 @@ export interface Config {
|
||||
* `testPaths` and before the built-in rules.
|
||||
*/
|
||||
interfacePaths?: string[]
|
||||
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
|
||||
/**
|
||||
* Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit
|
||||
* and update time, and, counted apart, of viewed marks kept for later reads at the same head commit.
|
||||
*/
|
||||
maxCachedReviewBytes?: number
|
||||
/**
|
||||
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
|
||||
* request's update time does not change when a thread is resolved.
|
||||
* Age in milliseconds at which review threads and viewed marks kept in memory are read from the code host again; a
|
||||
* GitHub pull request's update time does not change when a thread is resolved, and nothing announces a mark changed
|
||||
* on the code host itself.
|
||||
*/
|
||||
reviewRefreshMs?: number
|
||||
/**
|
||||
* Age in milliseconds past which the status of a change request is read at once when a Session's panel or the
|
||||
* review page starts to show it.
|
||||
*/
|
||||
statusMaxAgeMs?: number
|
||||
/** Deadline in milliseconds for one lens `classify` call. */
|
||||
lensTimeoutMs?: number
|
||||
/** Most UTF-8 bytes of file text one lens `classify` call may read. */
|
||||
@@ -1330,18 +1339,18 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:833`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
export interface Config {
|
||||
/** Poll interval in milliseconds while checks run or mergeability is unknown. */
|
||||
/** Poll interval in milliseconds while checks run, and for one poll after a status first reports an unknown mergeability. */
|
||||
activeIntervalMs?: number
|
||||
/** Poll interval in milliseconds for a closed request or an open request whose checks have settled. */
|
||||
idleIntervalMs?: number
|
||||
/** Largest delay in milliseconds between polls after consecutive failures. */
|
||||
maxBackoffMs?: number
|
||||
/** Deadline in milliseconds for one provider fetch. */
|
||||
/** Deadline in milliseconds for one provider fetch: one polling call, or one read of complete checks. */
|
||||
fetchTimeoutMs?: number
|
||||
}
|
||||
```
|
||||
@@ -1371,6 +1380,13 @@ export interface Config {
|
||||
* one review read, which reports itself truncated past it.
|
||||
*/
|
||||
maxReviewThreads?: number
|
||||
/**
|
||||
* Most pull requests one snapshot query reads. The forge registry polls that many pull requests of a host per call,
|
||||
* each call within its own fetch deadline; a read of more pull requests on one host sends several queries in turn.
|
||||
*/
|
||||
snapshotBatchSize?: number
|
||||
/** The same bound for one brief query. */
|
||||
briefBatchSize?: number
|
||||
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
|
||||
@@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
|
||||
@@ -49,8 +49,8 @@
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 8df1bf8a6d294252
|
||||
zh: 79ba96596739569f
|
||||
/forges/status-polling:
|
||||
en: 26ccfa2e342e3e67
|
||||
zh: fe6cc2a622757c48
|
||||
en: 33640257c4f9197d
|
||||
zh: b0f435bc3e03cfa4
|
||||
/forges/change-request-actions:
|
||||
en: ae735fbdbdf2d870
|
||||
zh: 9903fcc571104ad8
|
||||
|
||||
+141
-19
@@ -93,6 +93,23 @@ interface ForgeProvider {
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>>
|
||||
/**
|
||||
* Read the briefs of several change requests, returning one result per requested key. Omission declares that the
|
||||
* provider reads briefs as snapshots through {@link ForgeProvider.fetch}.
|
||||
*/
|
||||
fetchBriefs?(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>>
|
||||
/**
|
||||
* Most change requests of one host that one polling call of {@link ForgeProvider.fetch} reads, a positive safe
|
||||
* integer. The registry then calls `fetch` once for every that many due change requests of a host, one call after
|
||||
* another, each within its own fetch deadline, and publishes the results of a call when it returns. Omission
|
||||
* declares that one call reads every due change request of the forge.
|
||||
*/
|
||||
readonly snapshotBatchSize?: number
|
||||
/** The same bound for one polling call of {@link ForgeProvider.fetchBriefs}. */
|
||||
readonly briefBatchSize?: number
|
||||
/** Read all checks for one change request on demand; omission declares that only the polling preview is available. */
|
||||
fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure>
|
||||
/** Find open change requests whose head is `branch` in `repository`, excluding the default branch and forks. */
|
||||
@@ -230,7 +247,7 @@ interface ForgeDescription {
|
||||
|
||||
## Status polling
|
||||
|
||||
`ctx.forge.watch` shares one polling loop among the watchers of a change request and delivers every result as an update. Each forge has at most one fetch in flight. The [registry README](../../packages/experimental/forge/README.md#use-this-package) owns the poll cadence, backoff, and timeout rules.
|
||||
`ctx.forge.watch` and `ctx.forge.watchBrief` share one polling loop among the watchers of a change request. A poll reads the snapshot while the change request has a snapshot watcher and the brief otherwise, and delivers its result as an update to each kind of watcher it serves. Each forge has at most one snapshot fetch and one brief fetch in flight. The [registry README](../../packages/experimental/forge/README.md#use-this-package) owns the poll cadence, backoff, and timeout rules.
|
||||
|
||||
```ts type-equiv
|
||||
/** Lifecycle state of a change request. */
|
||||
@@ -397,6 +414,65 @@ type ChangeRequestUpdate = {
|
||||
type ChangeRequestListener = (update: ChangeRequestUpdate) => void
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* The fields of a {@link ChangeRequestSnapshot} that name a change request and its state in a list. A provider can
|
||||
* read them for many change requests in one request, without the checks, reviewers, and merge rules of a snapshot.
|
||||
*/
|
||||
type ChangeRequestBrief = Pick<
|
||||
ChangeRequestSnapshot, 'ref' | 'url' | 'title' | 'state' | 'draft' | 'mergeability' | 'reviewDecision' | 'checksRollup'
|
||||
>
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Latest brief delivered to brief watchers of one change request, from a brief read or from a snapshot read. */
|
||||
type ChangeRequestBriefUpdate = {
|
||||
/** Canonical identity of the watched change request. */
|
||||
readonly key: ChangeRequestKey
|
||||
/** Epoch milliseconds when the result settled. */
|
||||
readonly fetchedAt: number
|
||||
} & ({
|
||||
/** Brief read from the host. */
|
||||
readonly brief: ChangeRequestBrief
|
||||
} | {
|
||||
/** Reason the brief could not be read. */
|
||||
readonly failure: ForgeFailure
|
||||
})
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* Receives every polling result for one change request watched for its brief.
|
||||
* @param update - the settled result.
|
||||
*/
|
||||
type ChangeRequestBriefListener = (update: ChangeRequestBriefUpdate) => void
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** When a watcher that joins a watched change request, or a refresh of one, needs a status newer than the latest one. */
|
||||
interface ChangeRequestWatchOptions {
|
||||
/**
|
||||
* Age in milliseconds past which the latest status is too old. A watcher that joins a change request whose
|
||||
* snapshot was already read polls at once when the latest snapshot or failure is older and no snapshot poll is in
|
||||
* flight; without it, the watcher waits for the regular poll. A refresh polls at once unless the change request is
|
||||
* merged or its latest poll at either level, in flight or settled, started within it; without it, a refresh always
|
||||
* polls.
|
||||
*/
|
||||
readonly maxAgeMs?: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* The state a brief watcher last saw for a change request it starts to watch, which times the first poll as a brief
|
||||
* read at `fetchedAt` would: a merged change request is not polled, and any other one once its interval has passed.
|
||||
*/
|
||||
interface ChangeRequestKnownState extends Pick<ChangeRequestBrief, 'state' | 'mergeability' | 'checksRollup'> {
|
||||
/** Epoch milliseconds when the state was read. */
|
||||
readonly fetchedAt: number
|
||||
}
|
||||
```
|
||||
|
||||
## Change request actions
|
||||
|
||||
`ctx.forge.markReady` marks a draft ready for review, and `ctx.forge.merge` merges a change request only while its head is still the commit the user confirmed. Both resolve to a `ForgeActionFailure` instead of throwing when the host refuses, and poll a watched change request at once afterwards. A snapshot's `mergeReady` and `mergeMethods` tell a consumer when to offer a merge and with which methods; the [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub answers both.
|
||||
@@ -1652,7 +1728,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
|
||||
|
||||
### `ctx.forge` — `ForgeService`
|
||||
|
||||
Registry of forge providers. Watchers of one change request share a single polling loop; each forge has at most one fetch in flight, which batches every due change request of that forge.
|
||||
Registry of forge providers. Watchers of one change request share a single polling loop, which reads its snapshot while a snapshot watcher remains and its brief otherwise. Each forge has at most one snapshot fetch and one brief fetch in flight; each batches every due change request of that forge at its level, and those past the midpoint of the wait after a status, so change requests that became due at different times come to share one fetch. A fetch calls a provider that names a batch size once per that many change requests of a host, and settles the results of each call when it returns.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -1662,7 +1738,8 @@ Registry of forge providers. Watchers of one change request share a single polli
|
||||
* results from the withdrawn registration are discarded.
|
||||
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case, and
|
||||
* when the provider names a batch size that is not a positive safe integer.
|
||||
*/
|
||||
register(provider: ForgeProvider): () => Promise<void>
|
||||
|
||||
@@ -1950,28 +2027,55 @@ async fileText(ref: ChangeRequestRef, commit: string, path: string, signal: Abor
|
||||
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string
|
||||
|
||||
/**
|
||||
* Watch one change request as an effect on the calling fiber. The first
|
||||
* watcher starts polling at once; listeners receive every later result,
|
||||
* and `latest` returns the current one. Polling stops when the last watcher
|
||||
* leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* Watch the snapshot of one change request as an effect on the calling fiber. Its first snapshot watcher polls it at
|
||||
* once, and a later one does when `options.maxAgeMs` is given and the latest result is older. Listeners receive every
|
||||
* later snapshot poll result, and `latest` returns the current one. While a snapshot watcher remains, polls read the
|
||||
* snapshot; polling stops when the last watcher of the snapshot and the brief leaves. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives each polling result.
|
||||
* @param listener - receives each snapshot poll result.
|
||||
* @param options - when the watcher needs a status newer than the latest one.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener): () => void
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener, options: ChangeRequestWatchOptions = {}): () => void
|
||||
|
||||
/**
|
||||
* Watch the brief of one change request as an effect on the calling fiber. Listeners receive the brief of every
|
||||
* later poll result: of a brief read while only brief watchers remain, and of a snapshot read otherwise. The first
|
||||
* watcher of a change request polls it at once, or as `known` times it. Polling stops when the last watcher of the
|
||||
* snapshot and the brief leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives the brief of each poll result.
|
||||
* @param known - the state the caller last saw, which times the first poll of a change request without a watcher.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watchBrief(ref: ChangeRequestRef, listener: ChangeRequestBriefListener, known?: ChangeRequestKnownState): () => void
|
||||
|
||||
/**
|
||||
* Poll a watched change request at once, including after a terminal state.
|
||||
* A fetch already in flight is followed immediately by another fetch; an
|
||||
* unwatched change request is unchanged.
|
||||
* unwatched change request is unchanged. With `options.maxAgeMs`, the caller
|
||||
* needs a status no older than that many milliseconds: a change request
|
||||
* whose latest poll at either level, in flight or settled, started within
|
||||
* them is left alone, and so is a merged one, whose status is final.
|
||||
* @param ref - change request to poll.
|
||||
* @param options - when the caller needs a status newer than the latest one.
|
||||
*/
|
||||
refresh(ref: ChangeRequestRef): void
|
||||
refresh(ref: ChangeRequestRef, options: ChangeRequestWatchOptions = {}): void
|
||||
|
||||
/**
|
||||
* Read the latest polling result of a watched change request.
|
||||
* Announce that a watched change request is about to change, as after a push to its head branch. It is polled at
|
||||
* once and then every `activeIntervalMs`, until a status reports running checks or a closed or merged change
|
||||
* request, and for at most `idleIntervalMs`; after that the regular cadence applies. A fetch already in flight is
|
||||
* followed immediately by another fetch; an unwatched change request is unchanged.
|
||||
* @param ref - change request the caller expects to change.
|
||||
*/
|
||||
expectChange(ref: ChangeRequestRef): void
|
||||
|
||||
/**
|
||||
* Read the latest snapshot poll result of a watched change request.
|
||||
* @param ref - change request to read.
|
||||
* @returns the latest result, or undefined before the first result or without a watch.
|
||||
* @returns the latest result, or undefined before the first snapshot poll settled or without a watch.
|
||||
*/
|
||||
latest(ref: ChangeRequestRef): ChangeRequestUpdate | undefined
|
||||
```
|
||||
@@ -2142,15 +2246,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async reviewText(url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows.
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows, as
|
||||
* {@link ForgePanelController.changeRequestViewed} keeps them.
|
||||
* @param url - web URL of the change request.
|
||||
* @param headSha - head commit of the shown diff.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or
|
||||
* `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does.
|
||||
*/
|
||||
@Remote async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
@Remote async reviewViewed(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request the review page shows.
|
||||
@@ -2292,6 +2398,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async refresh(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Bring a followed Session's panel up to date after its surface showed again: reinspect the checkout, poll the
|
||||
* change requests whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found
|
||||
* the host ready, and look the upstream branch up again while the Session shows no change request; an unfollowed
|
||||
* Session is unchanged.
|
||||
* @param sessionId - Session whose panel is revisited; revisiting neither loads nor resumes it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
|
||||
*/
|
||||
@Remote async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory, with Git using the Session's sandbox policy.
|
||||
@@ -2433,17 +2550,20 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
|
||||
* whole change request.
|
||||
* whole change request. Marks read at the same head are kept in memory and returned until they are `reviewRefreshMs`
|
||||
* old or `maxCachedReviewBytes` evicts them; a mark saved through `ctx.forge` at that head replaces the kept state
|
||||
* of its file, so the read after a save costs no request.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param headSha - head commit of the shown diff; marks read at another head are refused.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks at `headSha`, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
* `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed`
|
||||
* when the host does not provide the marks otherwise.
|
||||
*/
|
||||
@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
@Remote async changeRequestViewed( session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal, ): Promise<ForgeViewedFiles | null>
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request of a Session.
|
||||
@@ -2736,15 +2856,17 @@ dismiss(session: Session, url: string): void
|
||||
/**
|
||||
* Watch a Session's visible change requests as an effect on the calling
|
||||
* fiber. Every visible change request that a provider recognizes is polled
|
||||
* through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* for its snapshot through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* complete list after each later binding or provider change, or polling result; read the
|
||||
* current list with {@link changeRequests}. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param session - Session to watch.
|
||||
* @param listener - receives the complete visible list.
|
||||
* @param options - when the Session's first watcher needs a status newer than the latest one; a later watcher's
|
||||
* options change nothing.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(session: Session, listener: SessionChangeRequestsListener): () => void
|
||||
watch(session: Session, listener: SessionChangeRequestsListener, options: ChangeRequestWatchOptions = {}): () => void
|
||||
```
|
||||
|
||||
Types: [Session](session.md)
|
||||
|
||||
+141
-19
@@ -93,6 +93,23 @@ interface ForgeProvider {
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>>
|
||||
/**
|
||||
* Read the briefs of several change requests, returning one result per requested key. Omission declares that the
|
||||
* provider reads briefs as snapshots through {@link ForgeProvider.fetch}.
|
||||
*/
|
||||
fetchBriefs?(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>>
|
||||
/**
|
||||
* Most change requests of one host that one polling call of {@link ForgeProvider.fetch} reads, a positive safe
|
||||
* integer. The registry then calls `fetch` once for every that many due change requests of a host, one call after
|
||||
* another, each within its own fetch deadline, and publishes the results of a call when it returns. Omission
|
||||
* declares that one call reads every due change request of the forge.
|
||||
*/
|
||||
readonly snapshotBatchSize?: number
|
||||
/** The same bound for one polling call of {@link ForgeProvider.fetchBriefs}. */
|
||||
readonly briefBatchSize?: number
|
||||
/** Read all checks for one change request on demand; omission declares that only the polling preview is available. */
|
||||
fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure>
|
||||
/** Find open change requests whose head is `branch` in `repository`, excluding the default branch and forks. */
|
||||
@@ -230,7 +247,7 @@ interface ForgeDescription {
|
||||
|
||||
## 状态轮询
|
||||
|
||||
`ctx.forge.watch` 让同一变更请求的所有监听方共享一个轮询循环,并把每次结果作为更新送达。每个 forge 同时最多只有一次读取在进行。轮询节奏、退避与超时规则见[注册表 README](../../packages/experimental/forge/README.zh.md#use-this-package)。
|
||||
`ctx.forge.watch` 与 `ctx.forge.watchBrief` 让同一变更请求的所有监听方共享一个轮询循环。变更请求有快照监听方时轮询读取快照,否则读取简报,并把结果作为更新送达它所服务的各类监听方。每个 forge 同时最多有一次快照读取和一次简报读取在进行。轮询节奏、退避与超时规则见[注册表 README](../../packages/experimental/forge/README.zh.md#use-this-package)。
|
||||
|
||||
```ts type-equiv
|
||||
/** Lifecycle state of a change request. */
|
||||
@@ -397,6 +414,65 @@ type ChangeRequestUpdate = {
|
||||
type ChangeRequestListener = (update: ChangeRequestUpdate) => void
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* The fields of a {@link ChangeRequestSnapshot} that name a change request and its state in a list. A provider can
|
||||
* read them for many change requests in one request, without the checks, reviewers, and merge rules of a snapshot.
|
||||
*/
|
||||
type ChangeRequestBrief = Pick<
|
||||
ChangeRequestSnapshot, 'ref' | 'url' | 'title' | 'state' | 'draft' | 'mergeability' | 'reviewDecision' | 'checksRollup'
|
||||
>
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Latest brief delivered to brief watchers of one change request, from a brief read or from a snapshot read. */
|
||||
type ChangeRequestBriefUpdate = {
|
||||
/** Canonical identity of the watched change request. */
|
||||
readonly key: ChangeRequestKey
|
||||
/** Epoch milliseconds when the result settled. */
|
||||
readonly fetchedAt: number
|
||||
} & ({
|
||||
/** Brief read from the host. */
|
||||
readonly brief: ChangeRequestBrief
|
||||
} | {
|
||||
/** Reason the brief could not be read. */
|
||||
readonly failure: ForgeFailure
|
||||
})
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* Receives every polling result for one change request watched for its brief.
|
||||
* @param update - the settled result.
|
||||
*/
|
||||
type ChangeRequestBriefListener = (update: ChangeRequestBriefUpdate) => void
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** When a watcher that joins a watched change request, or a refresh of one, needs a status newer than the latest one. */
|
||||
interface ChangeRequestWatchOptions {
|
||||
/**
|
||||
* Age in milliseconds past which the latest status is too old. A watcher that joins a change request whose
|
||||
* snapshot was already read polls at once when the latest snapshot or failure is older and no snapshot poll is in
|
||||
* flight; without it, the watcher waits for the regular poll. A refresh polls at once unless the change request is
|
||||
* merged or its latest poll at either level, in flight or settled, started within it; without it, a refresh always
|
||||
* polls.
|
||||
*/
|
||||
readonly maxAgeMs?: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* The state a brief watcher last saw for a change request it starts to watch, which times the first poll as a brief
|
||||
* read at `fetchedAt` would: a merged change request is not polled, and any other one once its interval has passed.
|
||||
*/
|
||||
interface ChangeRequestKnownState extends Pick<ChangeRequestBrief, 'state' | 'mergeability' | 'checksRollup'> {
|
||||
/** Epoch milliseconds when the state was read. */
|
||||
readonly fetchedAt: number
|
||||
}
|
||||
```
|
||||
|
||||
## 变更请求操作
|
||||
|
||||
`ctx.forge.markReady` 把草稿标记为可评审,`ctx.forge.merge` 只在 head 仍是用户确认的提交时合并变更请求。主机拒绝时,两者都 resolve 为 `ForgeActionFailure` 而不是抛错,并在结束后立即轮询被监听的变更请求。快照的 `mergeReady` 与 `mergeMethods` 告诉消费方何时提供合并、可用哪些合并方式;GitHub 如何给出这两项由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。
|
||||
@@ -1656,7 +1732,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
|
||||
|
||||
### `ctx.forge` — `ForgeService`
|
||||
|
||||
Registry of forge providers. Watchers of one change request share a single polling loop; each forge has at most one fetch in flight, which batches every due change request of that forge.
|
||||
Registry of forge providers. Watchers of one change request share a single polling loop, which reads its snapshot while a snapshot watcher remains and its brief otherwise. Each forge has at most one snapshot fetch and one brief fetch in flight; each batches every due change request of that forge at its level, and those past the midpoint of the wait after a status, so change requests that became due at different times come to share one fetch. A fetch calls a provider that names a batch size once per that many change requests of a host, and settles the results of each call when it returns.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
@@ -1666,7 +1742,8 @@ Registry of forge providers. Watchers of one change request share a single polli
|
||||
* results from the withdrawn registration are discarded.
|
||||
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case, and
|
||||
* when the provider names a batch size that is not a positive safe integer.
|
||||
*/
|
||||
register(provider: ForgeProvider): () => Promise<void>
|
||||
|
||||
@@ -1954,28 +2031,55 @@ async fileText(ref: ChangeRequestRef, commit: string, path: string, signal: Abor
|
||||
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string
|
||||
|
||||
/**
|
||||
* Watch one change request as an effect on the calling fiber. The first
|
||||
* watcher starts polling at once; listeners receive every later result,
|
||||
* and `latest` returns the current one. Polling stops when the last watcher
|
||||
* leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* Watch the snapshot of one change request as an effect on the calling fiber. Its first snapshot watcher polls it at
|
||||
* once, and a later one does when `options.maxAgeMs` is given and the latest result is older. Listeners receive every
|
||||
* later snapshot poll result, and `latest` returns the current one. While a snapshot watcher remains, polls read the
|
||||
* snapshot; polling stops when the last watcher of the snapshot and the brief leaves. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives each polling result.
|
||||
* @param listener - receives each snapshot poll result.
|
||||
* @param options - when the watcher needs a status newer than the latest one.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener): () => void
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener, options: ChangeRequestWatchOptions = {}): () => void
|
||||
|
||||
/**
|
||||
* Watch the brief of one change request as an effect on the calling fiber. Listeners receive the brief of every
|
||||
* later poll result: of a brief read while only brief watchers remain, and of a snapshot read otherwise. The first
|
||||
* watcher of a change request polls it at once, or as `known` times it. Polling stops when the last watcher of the
|
||||
* snapshot and the brief leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives the brief of each poll result.
|
||||
* @param known - the state the caller last saw, which times the first poll of a change request without a watcher.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watchBrief(ref: ChangeRequestRef, listener: ChangeRequestBriefListener, known?: ChangeRequestKnownState): () => void
|
||||
|
||||
/**
|
||||
* Poll a watched change request at once, including after a terminal state.
|
||||
* A fetch already in flight is followed immediately by another fetch; an
|
||||
* unwatched change request is unchanged.
|
||||
* unwatched change request is unchanged. With `options.maxAgeMs`, the caller
|
||||
* needs a status no older than that many milliseconds: a change request
|
||||
* whose latest poll at either level, in flight or settled, started within
|
||||
* them is left alone, and so is a merged one, whose status is final.
|
||||
* @param ref - change request to poll.
|
||||
* @param options - when the caller needs a status newer than the latest one.
|
||||
*/
|
||||
refresh(ref: ChangeRequestRef): void
|
||||
refresh(ref: ChangeRequestRef, options: ChangeRequestWatchOptions = {}): void
|
||||
|
||||
/**
|
||||
* Read the latest polling result of a watched change request.
|
||||
* Announce that a watched change request is about to change, as after a push to its head branch. It is polled at
|
||||
* once and then every `activeIntervalMs`, until a status reports running checks or a closed or merged change
|
||||
* request, and for at most `idleIntervalMs`; after that the regular cadence applies. A fetch already in flight is
|
||||
* followed immediately by another fetch; an unwatched change request is unchanged.
|
||||
* @param ref - change request the caller expects to change.
|
||||
*/
|
||||
expectChange(ref: ChangeRequestRef): void
|
||||
|
||||
/**
|
||||
* Read the latest snapshot poll result of a watched change request.
|
||||
* @param ref - change request to read.
|
||||
* @returns the latest result, or undefined before the first result or without a watch.
|
||||
* @returns the latest result, or undefined before the first snapshot poll settled or without a watch.
|
||||
*/
|
||||
latest(ref: ChangeRequestRef): ChangeRequestUpdate | undefined
|
||||
```
|
||||
@@ -2146,15 +2250,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async reviewText(url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows.
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows, as
|
||||
* {@link ForgePanelController.changeRequestViewed} keeps them.
|
||||
* @param url - web URL of the change request.
|
||||
* @param headSha - head commit of the shown diff.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or
|
||||
* `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does.
|
||||
*/
|
||||
@Remote async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
@Remote async reviewViewed(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request the review page shows.
|
||||
@@ -2296,6 +2402,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async refresh(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Bring a followed Session's panel up to date after its surface showed again: reinspect the checkout, poll the
|
||||
* change requests whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found
|
||||
* the host ready, and look the upstream branch up again while the Session shows no change request; an unfollowed
|
||||
* Session is unchanged.
|
||||
* @param sessionId - Session whose panel is revisited; revisiting neither loads nor resumes it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
|
||||
*/
|
||||
@Remote async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory, with Git using the Session's sandbox policy.
|
||||
@@ -2437,17 +2554,20 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
|
||||
* whole change request.
|
||||
* whole change request. Marks read at the same head are kept in memory and returned until they are `reviewRefreshMs`
|
||||
* old or `maxCachedReviewBytes` evicts them; a mark saved through `ctx.forge` at that head replaces the kept state
|
||||
* of its file, so the read after a save costs no request.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param headSha - head commit of the shown diff; marks read at another head are refused.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks at `headSha`, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
* `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed`
|
||||
* when the host does not provide the marks otherwise.
|
||||
*/
|
||||
@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>
|
||||
@Remote async changeRequestViewed( session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal, ): Promise<ForgeViewedFiles | null>
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request of a Session.
|
||||
@@ -2740,15 +2860,17 @@ dismiss(session: Session, url: string): void
|
||||
/**
|
||||
* Watch a Session's visible change requests as an effect on the calling
|
||||
* fiber. Every visible change request that a provider recognizes is polled
|
||||
* through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* for its snapshot through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* complete list after each later binding or provider change, or polling result; read the
|
||||
* current list with {@link changeRequests}. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param session - Session to watch.
|
||||
* @param listener - receives the complete visible list.
|
||||
* @param options - when the Session's first watcher needs a status newer than the latest one; a later watcher's
|
||||
* options change nothing.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(session: Session, listener: SessionChangeRequestsListener): () => void
|
||||
watch(session: Session, listener: SessionChangeRequestsListener, options: ChangeRequestWatchOptions = {}): () => void
|
||||
```
|
||||
|
||||
Types: [Session](session.zh.md)
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: b09c31932092f0a0
|
||||
zh: b16598d5f50baab6
|
||||
en: 44e46809de624c40
|
||||
zh: 934dd10fbc7b7b14
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: 5876ab4a46ee5e65
|
||||
zh: b5ea47ac9665530e
|
||||
en: ea018cbd4c2357cb
|
||||
zh: 1a73b620bf7ad1a0
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
@@ -30,8 +30,8 @@
|
||||
en: c1b5bfb0e5a1801e
|
||||
zh: 2bbe1a2845aa5d20
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work:
|
||||
en: 739fee52b50d04d1
|
||||
zh: 6550f24b8fd52791
|
||||
en: bd19347052d20055
|
||||
zh: b9fe5cb782d2d534
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -50,7 +50,7 @@ The checks row initially shows the polling preview. While it is incomplete, the
|
||||
|
||||
The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior.
|
||||
|
||||
`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, `maxAnnotationsPerFile`, `reviewListIntervalMs`, `reviewCountIntervalMs`, `reviewMaxBackoffMs`, and `reviewPageSize` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge).
|
||||
`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `statusMaxAgeMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, `maxAnnotationsPerFile`, `reviewListIntervalMs`, `reviewCountIntervalMs`, `reviewMaxBackoffMs`, and `reviewPageSize` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge).
|
||||
|
||||
All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree, which stays at least as wide as the lens above it needs to show the layer names whole. Files and folders reserve the same disclosure column so each child is indented from its parent. The tree already shows each directory, so only a renamed file names both paths, in a tooltip after 500ms of hover; a name its row clips crawls into view while the pointer rests on the row. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the split button adds the comment to the user's pending review on the code host, starting one when there is none; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately and is absent while the user has a pending review. Agent references and published comments remain beside their code as cards that name their lines and state; Remove in a card's menu takes the card out of the view, leaves the main composer and the code host unchanged, and shows a notice that offers Undo. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. Decisions the code host does not let the user record are unavailable, such as Approve and Request changes on the user's own pull request on GitHub; when only Comment remains, the dialog says so. The view's copy names the code host and its word for a change request, such as GitHub and PR, after the change request's provider. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted after a confirmation, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission.
|
||||
|
||||
@@ -62,7 +62,7 @@ All files opens a searchable directory tree with the selected file scrolled to i
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later.
|
||||
`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves, keeping its last state, the latest snapshots, and the branch it looked up while the Session stays loaded. A panel starts with the Session's working directory and bindings, or with what the Session's previous panel kept unless the Session has moved to another directory, re-inspects after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh, or until a panel starts or is revisited while the Session shows no change request. A sign-in probe runs within `readinessTimeoutMs` when the recognized host changes, on refresh, after the first inspection of a panel whose previous panel did not find the host ready, on a revisit while the host is not ready, and once when status reads on a host shown as ready start to be refused as unauthenticated; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. `revisit` reinspects the checkout and polls only the change requests whose latest poll is older than `statusMaxAgeMs`.
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes/<remote>/HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when the checkout lies inside the canonical workspace root of the Session's sandbox policy and the common Git directory lies inside that root or one of the policy's additional writable directories.
|
||||
|
||||
@@ -73,13 +73,15 @@ Restoration records `restoring` before mutation and `restored` only after succes
|
||||
|
||||
Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. Commands in the source repository run under the Session's policy bounded by that repository, since the Session's own root is the missing directory.
|
||||
|
||||
`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes row hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :<path>` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to thLine truncated
|
||||
`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes row hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :<path>` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to thLine truncated
|
||||
|
||||
`changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it.
|
||||
`changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. It keeps one read per change request, keyed by head commit, under the same `maxCachedReviewBytes` and `reviewRefreshMs` bounds as the threads, and a mark saved through `ctx.forge` at that head replaces the kept state of its file, so saving a mark costs the provider's write and no further read; the reader's refresh passes `fresh` and reads the host again. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it.
|
||||
|
||||
`changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service.
|
||||
`changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and watches the brief of each bound change request through `ctx.forge.watchBrief`, naming the state it holds for it: a merged change request is not read again, one that an earlier run of this process read waits for its interval, and any other stored one is read at once. Closed requests use the idle polling cadence, and merged requests remain watched for explicit refresh and for a snapshot read by a panel. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service.
|
||||
|
||||
The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so it runs the automatic refresh on mount and on window `focus` and `visibilitychange`, throttled per Session by the shared panel store; a refresh asked for before the first panel state arrives runs once that state arrives, because the Host refreshes only a panel it follows. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.<Session>`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host.
|
||||
`follow` and `reviewChangeRequest` watch the snapshot of each change request they show and ask `ctx.forge` for a status no older than `statusMaxAgeMs` (default 10 seconds). A Session's panel or a review page stream that starts while the latest snapshot result is older reads the status at once; one that starts with a newer result, or with none yet read by another snapshot watcher, follows the regular poll.
|
||||
|
||||
The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so on mount and on window `focus` and `visibilitychange` it calls `revisit`, throttled per Session by the shared panel store; a revisit asked for before the first panel state arrives runs once that state arrives, because the Host revisits only a panel it follows. The panel streams, the change request state stream, and the review count stream close once the page has been hidden for 30 seconds and open again when it shows, so the Host polls no code host for a page nobody sees; their last values stay readable. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.<Session>`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host.
|
||||
|
||||
| Source | Responsibility |
|
||||
|---|---|
|
||||
@@ -153,7 +155,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- **Filtered files and submodules** — local diffs bypass clean/process filters; Git's built-in newline, ident, and encoding conversions still apply. Materialized LFS files and other filtered files can appear changed even when ordinary Git considers them clean; pointer-only checkouts compare normally. The panel does not request LFS downloads. Filter overrides rely on Git 2.31 or newer; older Git can ignore them and run helpers under Session permissions. Drivers added between enumeration and diff are not covered by the overrides. Submodule commit changes remain visible; internal uncommitted changes are omitted.
|
||||
- **Polling while shown** — status is polled only while a Session list row or an active panel surface for the Session subscribes; retained hidden changes bodies do not subscribe; there are no notifications for checks that finish meanwhile.
|
||||
- **Polling while shown** — status is polled only while a Session list row or an active panel surface for the Session subscribes, as a brief for the list and as a snapshot for the panel; retained hidden changes bodies do not subscribe; there are no notifications for checks that finish meanwhile.
|
||||
- **Unopened Sessions in the list** — the Session list reads the worktree and bindings of a Session that is not loaded from its cached summary: a Session without one shows neither, and one last used before this version shows its worktree only after it is opened.
|
||||
- **Inspection triggers** — the checkout is inspected after Session tool results and directory changes; a change made outside the Session appears when the Session panel opens or the window regains focus, at most once every 10 seconds, or after the next tool result.
|
||||
- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Generated branch names come from the Session id and random digits, not from the Session title, which does not exist yet; a name chosen in the naming dialog replaces them.
|
||||
|
||||
@@ -50,7 +50,7 @@ kind: "package-reference"
|
||||
|
||||
diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。
|
||||
|
||||
`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes`、`maxAnnotationsPerFile`、`reviewListIntervalMs`、`reviewCountIntervalMs`、`reviewMaxBackoffMs` 与 `reviewPageSize` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。
|
||||
`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`statusMaxAgeMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes`、`maxAnnotationsPerFile`、`reviewListIntervalMs`、`reviewCountIntervalMs`、`reviewMaxBackoffMs` 与 `reviewPageSize` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。
|
||||
|
||||
“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度;文件树至少保持上方透镜完整显示各层名称所需的宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。树已经表示了目录,所以只有重命名的文件会在悬停 500ms 后用提示显示新旧两条路径;文件名放不下时,指针停在这一行上会滚动显示全文。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,分段按钮会把这条评论加入用户在代码托管平台上的待提交评审,没有时先开始一个;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时没有该菜单。Agent 引用和已发布的评论以卡片保留在对应代码旁,卡片标出行范围和状态;卡片菜单里的“移除”把卡片从视图中去掉,不改动主输入框和代码托管平台,随后的提示提供“撤销”。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。代码托管平台不允许用户记录的结论不可用,例如在 GitHub 上用户自己的 PR 里,“批准”和“请求更改”不可用;只剩“评论”时,对话框会说明。视图中的文案按变更请求的提供方称呼代码托管平台及其对变更请求的叫法,例如 GitHub 和 PR。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、确认后删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。
|
||||
|
||||
@@ -62,7 +62,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。
|
||||
`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它,并在 Session 保持加载期间保留它最后的状态、最近的快照和查找过的分支。面板从 Session 的工作目录与绑定开始;Session 的上一个面板留下了这些内容、且 Session 没有换到其他目录时,从它们开始。面板在每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次;面板开始或被重新访问时 Session 没有显示任何变更请求的,会再查找一次。以下情况会在 `readinessTimeoutMs` 内检查登录状态:识别出的托管平台变化时,刷新时,上一个面板没有确认托管平台已就绪的面板完成第一次检查后,重新访问时托管平台尚未就绪,以及显示为已就绪的托管平台上的状态读取开始被以未登录拒绝时(只检查一次);一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。`revisit` 重新检查 checkout,并且只轮询最近一次轮询早于 `statusMaxAgeMs` 的变更请求。
|
||||
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes/<remote>/HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下,只有检出目录位于 Session 沙箱策略的规范工作区根内,且公共 Git 目录位于该根或策略的某个额外可写目录内时才可用。
|
||||
|
||||
@@ -73,13 +73,15 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo
|
||||
|
||||
每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。源仓库中的命令在 Session 的策略下运行,边界是该仓库,因为 Session 自身的根就是那个缺失的目录。
|
||||
|
||||
Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更行保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :<path>` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支Line truncated
|
||||
Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更行保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :<path>` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支Line truncated
|
||||
|
||||
`changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。
|
||||
`changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。每个变更请求保留一次读取结果,以 head 提交为键,受与讨论相同的 `maxCachedReviewBytes` 和 `reviewRefreshMs` 限制;经 `ctx.forge` 在该 head 上保存的标记会替换所保留的对应文件状态,所以保存一个标记只需要提供方的那次写入,不再读取;读者刷新时传入 `fresh`,重新从托管平台读取。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。
|
||||
|
||||
`changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。
|
||||
`changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watchBrief` 监听每个已绑定变更请求的简报,同时告知自己持有的状态:已合并的不再读取,本进程此前的运行读过的等到间隔到期,其他已存的立即读取。已关闭的按空闲间隔轮询,已合并的保留监听,以接收显式刷新和面板的快照读取结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。
|
||||
|
||||
浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时触发自动刷新,按会话由共享的面板 store 限流;首个面板状态到达前请求的刷新等到该状态到达后执行,因为 Host 只刷新它正在跟随的面板。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。
|
||||
`follow` 与 `reviewChangeRequest` 监听所显示的每个变更请求的快照,并要求 `ctx.forge` 提供不早于 `statusMaxAgeMs`(默认 10 秒)的状态。Session 的面板或评审页的流开始时,如果最近一次快照结果更旧,就立即读取状态;如果结果更新,或者还没有其他快照监听方读过,就跟随常规轮询。
|
||||
|
||||
浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时调用 `revisit`,按会话由共享的面板 store 限流;首个面板状态到达前请求的重新访问等到该状态到达后执行,因为 Host 只重新访问它正在跟随的面板。页面隐藏满 30 秒后,面板流、变更请求状态流与评审计数流关闭,页面再次显示时重新打开,所以 Host 不会为没有人看的页面轮询代码托管平台;它们最后的值仍然可读。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。
|
||||
|
||||
| 源码 | 职责 |
|
||||
|---|---|
|
||||
@@ -153,7 +155,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- **过滤文件与子模块** — 本地 diff 绕过 clean/process filter;Git 内置的换行、ident 与编码转换仍然生效。已物化的 LFS 文件及其他过滤文件可能显示为变更,即使普通 Git 认为它们未变;仅保留指针的检出可正常比较。面板不请求下载 LFS 对象。过滤器覆盖依赖 Git 2.31 或更新版本;旧 Git 可能忽略覆盖,按 Session 权限运行辅助程序。枚举与 diff 之间新增的驱动不在覆盖范围内。子模块提交变化仍可见,内部未提交修改不显示。
|
||||
- **只在显示时轮询**——只有会话列表的某一行或该 Session 的活动面板界面订阅时才会轮询状态,保活但隐藏的变更正文不订阅;其间检查结束不会有通知。
|
||||
- **只在显示时轮询**——只有会话列表的某一行或该 Session 的活动面板界面订阅时才会轮询状态:列表读取简报,面板读取快照;保活但隐藏的变更正文不订阅;其间检查结束不会有通知。
|
||||
- **会话列表中未打开的 Session**——会话列表从缓存的摘要中读取未加载 Session 的 worktree 与绑定:没有缓存摘要的 Session 两者都不显示;此版本之前最后使用的 Session 要打开之后才显示其 worktree。
|
||||
- **检查触发时机**——检出只在 Session 的工具结果与目录变化之后检查;Session 之外的改动在会话面板打开或窗口重新获得焦点时出现(每 10 秒最多一次),否则要等到下一个工具结果。
|
||||
- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。自动生成的分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在;在命名对话框中指定的名称会取代它。
|
||||
|
||||
@@ -128,9 +128,11 @@ export interface ChangesTabInjected {
|
||||
readonly viewedFiles: ViewedFiles
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on a change request's files at `headSha`, or null when its provider keeps
|
||||
* none; `signal` aborts the read.
|
||||
* none; `fresh` skips the marks the host keeps, and `signal` aborts the read.
|
||||
*/
|
||||
readonly changeRequestViewed: (url: string, headSha: string, signal: AbortSignal) => Promise<RemoteResult<ForgeViewedFiles | null>>
|
||||
readonly changeRequestViewed: (
|
||||
url: string, headSha: string, fresh: boolean, signal: AbortSignal,
|
||||
) => Promise<RemoteResult<ForgeViewedFiles | null>>
|
||||
/** Set or clear the signed-in user's viewed mark on one file of a change request. */
|
||||
readonly setFileViewed: (url: string, request: ForgeViewedRequest) => Promise<RemoteResult<void>>
|
||||
/** Read one file of a change request at a commit. */
|
||||
@@ -295,6 +297,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T
|
||||
* @param scope - local scope to read.
|
||||
* @param commits - chosen commits of a change request, or null for all of it.
|
||||
* @param head - head commit of the change request's latest status, or null.
|
||||
* @param fresh - whether the viewed marks are read from the code host although the host keeps some, as after a refresh.
|
||||
* @param reads - the Remote reads.
|
||||
* @param signal - cancellation of the reads.
|
||||
* @returns the changes, or why they could not be read.
|
||||
@@ -304,6 +307,7 @@ async function readChanges(
|
||||
scope: ForgeLocalScope,
|
||||
commits: ForgeCommitRange | null,
|
||||
head: string | null,
|
||||
fresh: boolean,
|
||||
reads: Pick<ChangesTabInjected, 'localDiff' | 'changeRequestDiff' | 'changeRequestViewed'>,
|
||||
signal: AbortSignal,
|
||||
): Promise<RemoteResult<ChangesData>> {
|
||||
@@ -315,7 +319,7 @@ async function readChanges(
|
||||
}
|
||||
const [result, marks] = await Promise.all([
|
||||
reads.changeRequestDiff(source.url, commits, signal),
|
||||
commits === null && head !== null && head !== '' ? reads.changeRequestViewed(source.url, head, signal) : Promise.resolve(null),
|
||||
commits === null && head !== null && head !== '' ? reads.changeRequestViewed(source.url, head, fresh, signal) : Promise.resolve(null),
|
||||
])
|
||||
if (!result.ok) return result
|
||||
if (marks !== null && !marks.ok && marks.error.code === 'forgePanel/stale-head') return marks
|
||||
@@ -705,9 +709,10 @@ export function ChangesView({
|
||||
const split = choices?.split ?? true
|
||||
const wrap = choices?.wrap ?? true
|
||||
// A read starts once the panel state arrives and again when what it describes moves. A change request's read
|
||||
// also waits for its first status, which names the head, unless no provider serves it or its first poll failed.
|
||||
// also waits for the first status of the panel stream, which names the head the Host reads at, unless no provider
|
||||
// serves it or its first poll failed; until then the entry may show a snapshot the Host kept from an earlier stream.
|
||||
const pending = entry !== undefined && entry.ref !== null && entry.update === null
|
||||
const head = entry?.snapshot?.headSha ?? (pending ? null : '')
|
||||
const head = pending ? null : entry?.snapshot?.headSha ?? ''
|
||||
// An accepted review change the host announced, from any plugin, reads a change request's viewed marks again.
|
||||
const hostRevision = entry?.reviewRevision ?? 0
|
||||
const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}`
|
||||
@@ -729,11 +734,16 @@ export function ChangesView({
|
||||
useEffect(() => { latestStatusAt.current = statusAt }, [statusAt])
|
||||
const [refused, setRefused] = useState<{ readonly read: string; readonly statusAt: number | null } | null>(null)
|
||||
const waiting = refused !== null && refused.read === read && refused.statusAt === statusAt
|
||||
// The refresh whose read finished last; until the read of a later refresh finishes, reads skip the viewed marks the
|
||||
// host keeps, which marks changed on the code host itself leave unchanged.
|
||||
const finishedAttempt = useRef(attempt)
|
||||
useEffect(() => {
|
||||
if (!tab.visible || read === null || read === finished || waiting) return
|
||||
const controller = new AbortController()
|
||||
const readAt = latestStatusAt.current
|
||||
void readChanges(source, localScope, changeCommits, head, { localDiff, changeRequestDiff, changeRequestViewed }, controller.signal)
|
||||
const fresh = finishedAttempt.current !== attempt
|
||||
const reads = { localDiff, changeRequestDiff, changeRequestViewed }
|
||||
void readChanges(source, localScope, changeCommits, head, fresh, reads, controller.signal)
|
||||
.then((result) => {
|
||||
if (controller.signal.aborted) return
|
||||
if (!result.ok && result.error.code === 'forgePanel/stale-head') {
|
||||
@@ -741,6 +751,7 @@ export function ChangesView({
|
||||
setFailure(null)
|
||||
return
|
||||
}
|
||||
finishedAttempt.current = attempt
|
||||
setFinished(read)
|
||||
if (result.ok) {
|
||||
setLoaded({ key: dataKey, data: result.value })
|
||||
@@ -750,12 +761,12 @@ export function ChangesView({
|
||||
}
|
||||
})
|
||||
return () => { controller.abort() }
|
||||
}, [tab.visible, read, refused, waiting, source, localScope, changeCommits, head, dataKey, localDiff, changeRequestDiff,
|
||||
}, [tab.visible, read, refused, waiting, source, localScope, changeCommits, head, attempt, dataKey, localDiff, changeRequestDiff,
|
||||
changeRequestViewed])
|
||||
const data = loaded !== null && loaded.key === dataKey ? loaded.data : null
|
||||
// Threads show only while they were read at the head of the latest status and, for the whole change request, at
|
||||
// the head the shown diff was read at, so their positions number the shown files.
|
||||
const prHead = entry?.snapshot?.headSha ?? null
|
||||
const prHead = pending ? null : entry?.snapshot?.headSha ?? null
|
||||
const prAuthor = entry?.snapshot?.author ?? null
|
||||
const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead,
|
||||
updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision + hostRevision, read: changeRequestReview })
|
||||
|
||||
@@ -48,7 +48,7 @@ import type { SessionListInjected } from './session-list.ts'
|
||||
import { SessionHoverForge } from './SessionHoverForge.tsx'
|
||||
import { SessionRowForge } from './SessionRowForge.tsx'
|
||||
import {
|
||||
createNoticeSource, createPanelSource, createStreamSource, foldStates, type PanelSource, type PanelStream,
|
||||
createNoticeSource, createPanelSource, createStreamSource, foldStates, pageVisibility, type PanelSource, type PanelStream,
|
||||
} from './source.ts'
|
||||
import { numberOf, type ChangeRequestEntry } from './status.ts'
|
||||
import type { WorktreeRequestResult } from './WorktreeNameDialog.tsx'
|
||||
@@ -79,7 +79,7 @@ interface SessionStores {
|
||||
readonly panel: PanelSource
|
||||
readonly reviews: WeakMap<AbortSignal, ReviewQueue>
|
||||
readonly viewed: ViewedFiles
|
||||
/** Refresh unless an automatic refresh of this Session ran within {@link AUTO_REFRESH_MIN_MS}. */
|
||||
/** Revisit the Session's panel on the Host unless an automatic revisit of this Session ran within {@link AUTO_REFRESH_MIN_MS}. */
|
||||
readonly refreshIfStale: () => void
|
||||
/** Plugin annotations of each changes view of the Session, by address. */
|
||||
readonly annotations: Map<string, AnnotationView>
|
||||
@@ -87,9 +87,9 @@ interface SessionStores {
|
||||
}
|
||||
|
||||
/**
|
||||
* Least time between automatic refreshes of one Session, which run when the
|
||||
* Least time between automatic revisits of one Session, which run when the
|
||||
* Session panel opens and when the window regains focus; repeated focus
|
||||
* changes then cost one checkout inspection and code host poll.
|
||||
* changes then cost one checkout inspection.
|
||||
*/
|
||||
const AUTO_REFRESH_MIN_MS = 10_000
|
||||
|
||||
@@ -162,6 +162,7 @@ function registerUi(ctx: Context): void {
|
||||
refreshIfStale()
|
||||
}),
|
||||
subscribeReset: listener => ctx.on('connection/reset', listener),
|
||||
visibility: pageVisibility,
|
||||
})
|
||||
const dispose = scope.effect(() => () => {
|
||||
panel.close()
|
||||
@@ -176,7 +177,7 @@ function registerUi(ctx: Context): void {
|
||||
const now = Date.now()
|
||||
if (refreshedAt !== undefined && now - refreshedAt < AUTO_REFRESH_MIN_MS) return
|
||||
refreshedAt = now
|
||||
void refreshOf(sessionId)()
|
||||
void ctx.remote.forgePanel.revisit(sessionId).then((result) => { settled(result, 'toast.refreshFailed') })
|
||||
}
|
||||
store = {
|
||||
panel, reviews: new WeakMap(), viewed: new ViewedFiles(sessionId), annotations: new Map(), refreshIfStale,
|
||||
@@ -377,7 +378,8 @@ function registerUi(ctx: Context): void {
|
||||
changeRequestDiff: (url, commits, signal) => ctx.remote.forgePanel.changeRequestDiff(sessionId, url, commits, signal),
|
||||
changeRequestCommits: (url, signal) => ctx.remote.forgePanel.changeRequestCommits(sessionId, url, signal),
|
||||
viewedFiles: store.viewed,
|
||||
changeRequestViewed: (url, headSha, signal) => ctx.remote.forgePanel.changeRequestViewed(sessionId, url, headSha, signal),
|
||||
changeRequestViewed: (url, headSha, fresh, signal) =>
|
||||
ctx.remote.forgePanel.changeRequestViewed(sessionId, url, headSha, fresh, signal),
|
||||
setFileViewed: (url, request) => ctx.remote.forgePanel.setFileViewed(sessionId, url, request),
|
||||
changeRequestText: (url, commit, path) => ctx.remote.forgePanel.changeRequestText(sessionId, url, commit, path),
|
||||
addReviewToInput: selection => addReviewToInput(sessionId, selection),
|
||||
@@ -513,6 +515,7 @@ function registerUi(ctx: Context): void {
|
||||
const states = createStreamSource<ForgeChangeRequestStatesFrame, ReadonlyMap<string, ForgeChangeRequestListState>>({
|
||||
open: signal => ctx.remote.forgePanel.changeRequestStates(signal),
|
||||
subscribeReset: listener => ctx.on('connection/reset', listener),
|
||||
visibility: pageVisibility,
|
||||
}, new Map(), foldStates)
|
||||
ctx.effect(() => () => { states.close() }, 'forge-panel: change request states')
|
||||
const listFace = (): SessionListInjected => ({ hooks: { states: states.observable } })
|
||||
|
||||
@@ -23,7 +23,7 @@ import { createReviewStore } from './review-store.ts'
|
||||
import { ReviewNavCount, ReviewNavIcon, type ReviewNavCountInjected } from './ReviewNav.tsx'
|
||||
import { ReviewConversation, type ReviewChatFace } from './ReviewChat.tsx'
|
||||
import { ReviewPage, type ReviewChangesFace, type ReviewPageInjected } from './ReviewPage.tsx'
|
||||
import { createStreamSource, type NoticeSource } from '../source.ts'
|
||||
import { createStreamSource, pageVisibility, type NoticeSource } from '../source.ts'
|
||||
import type { ChangeRequestEntry } from '../status.ts'
|
||||
import { ViewedFiles } from '../viewed-files.ts'
|
||||
import type { ForgeReviewCountFrame } from '../../types.ts'
|
||||
@@ -125,7 +125,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
changeRequestDiff: (url, commits, signal) => remote.reviewDiff(url, commits, signal),
|
||||
changeRequestCommits: (url, signal) => remote.reviewCommits(url, signal),
|
||||
viewedFiles: new ViewedFiles('forge-review-page'),
|
||||
changeRequestViewed: (url, headSha, signal) => remote.reviewViewed(url, headSha, signal),
|
||||
changeRequestViewed: (url, headSha, fresh, signal) => remote.reviewViewed(url, headSha, fresh, signal),
|
||||
setFileViewed: (url, request) => remote.reviewSetViewed(url, request),
|
||||
changeRequestText: (url, commit, path) => remote.reviewText(url, commit, path),
|
||||
changeRequestReview: (url, headSha, fresh, signal) => remote.reviewThreads(url, headSha, fresh, signal),
|
||||
@@ -186,6 +186,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
const count = createStreamSource<ForgeReviewCountFrame, number | null>({
|
||||
open: signal => remote.reviewCount(signal),
|
||||
subscribeReset,
|
||||
visibility: pageVisibility,
|
||||
}, null, (_previous, frame) => frame.reviewRequested)
|
||||
ctx.effect(() => () => { count.close() }, 'forge-panel: review count')
|
||||
ctx.effect(() => ctx.remoteAccess.whenAccess('forgePanel/reviewLists', function* () {
|
||||
|
||||
@@ -27,7 +27,34 @@ export interface HostStream<F> extends AsyncIterable<F> {
|
||||
/** One open stream of panel states. */
|
||||
export type PanelStream = HostStream<ForgePanelState>
|
||||
|
||||
/** Stream opener and connection-reset subscription of a source. */
|
||||
/** Whether the page is hidden, and when that changes. */
|
||||
export interface PageVisibility {
|
||||
/** Whether the page is hidden now. */
|
||||
readonly hidden: () => boolean
|
||||
/**
|
||||
* Subscribe to changes of the page's visibility.
|
||||
* @param listener - called after each change.
|
||||
* @returns the unsubscribe function.
|
||||
*/
|
||||
readonly subscribe: (listener: () => void) => () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a page stays hidden before a source that follows its visibility closes its stream, so a short switch to
|
||||
* another window or tab reopens nothing.
|
||||
*/
|
||||
export const HIDDEN_GRACE_MS = 30_000
|
||||
|
||||
/** The visibility of the document, for the sources whose Host stream polls a code host. */
|
||||
export const pageVisibility: PageVisibility = {
|
||||
hidden: () => document.visibilityState === 'hidden',
|
||||
subscribe: (listener) => {
|
||||
document.addEventListener('visibilitychange', listener)
|
||||
return () => { document.removeEventListener('visibilitychange', listener) }
|
||||
},
|
||||
}
|
||||
|
||||
/** Stream opener, connection-reset subscription, and optional page visibility of a source. */
|
||||
export interface StreamSourceDeps<F> {
|
||||
/**
|
||||
* Open the Host stream.
|
||||
@@ -41,9 +68,11 @@ export interface StreamSourceDeps<F> {
|
||||
* @returns the unsubscribe function.
|
||||
*/
|
||||
readonly subscribeReset: (listener: () => void) => () => void
|
||||
/** The page's visibility, for a source whose Host stream costs requests while nobody can see its value. */
|
||||
readonly visibility?: PageVisibility
|
||||
}
|
||||
|
||||
/** Stream opener and connection-reset subscription of one Session's panel source. */
|
||||
/** Stream opener, connection-reset subscription, and optional page visibility of one Session's panel source. */
|
||||
export type PanelSourceDeps = StreamSourceDeps<ForgePanelState>
|
||||
|
||||
/** A value built from a Host stream that runs only while a surface subscribes. */
|
||||
@@ -71,8 +100,11 @@ export interface PanelSource {
|
||||
* subscriber opens the stream and the last one closes it; the value stays
|
||||
* readable for the next subscriber. A stream that ends or fails while
|
||||
* subscribed marks the snapshot disconnected until `reconnect` or a transport
|
||||
* reset reopens it.
|
||||
* @param deps - stream opener and reset subscription.
|
||||
* reset reopens it. A source given the page's visibility closes its stream
|
||||
* once the page has been hidden for {@link HIDDEN_GRACE_MS} and opens it again
|
||||
* when the page shows; meanwhile the value stays and is not marked
|
||||
* disconnected.
|
||||
* @param deps - stream opener, reset subscription, and the page's visibility for a source that pauses.
|
||||
* @param initial - value before the first frame.
|
||||
* @param fold - the value after one frame.
|
||||
* @returns the source.
|
||||
@@ -82,6 +114,11 @@ export function createStreamSource<F, S>(deps: StreamSourceDeps<F>, initial: S,
|
||||
const listeners = new Set<() => void>()
|
||||
let running: { readonly controller: AbortController; readonly stream: HostStream<F> } | undefined
|
||||
let stopReset: (() => void) | undefined
|
||||
let stopVisibility: (() => void) | undefined
|
||||
/** Runs once the page has been hidden for the grace period. */
|
||||
let hiding: ReturnType<typeof setTimeout> | undefined
|
||||
/** Whether the stream is closed because the page is hidden. */
|
||||
let paused = false
|
||||
const publish = (next: StreamSnapshot<S>): void => {
|
||||
snapshot = next
|
||||
for (const listener of [...listeners]) listener()
|
||||
@@ -115,10 +152,30 @@ export function createStreamSource<F, S>(deps: StreamSourceDeps<F>, initial: S,
|
||||
if (listeners.size === 0 || running !== undefined) return
|
||||
start()
|
||||
}
|
||||
const visibilityChanged = (): void => {
|
||||
if (deps.visibility?.hidden() === true) {
|
||||
hiding ??= setTimeout(() => {
|
||||
hiding = undefined
|
||||
paused = true
|
||||
stop()
|
||||
}, HIDDEN_GRACE_MS)
|
||||
return
|
||||
}
|
||||
clearTimeout(hiding)
|
||||
hiding = undefined
|
||||
if (!paused) return
|
||||
paused = false
|
||||
reconnect()
|
||||
}
|
||||
const close = (): void => {
|
||||
listeners.clear()
|
||||
stopReset?.()
|
||||
stopReset = undefined
|
||||
stopVisibility?.()
|
||||
stopVisibility = undefined
|
||||
clearTimeout(hiding)
|
||||
hiding = undefined
|
||||
paused = false
|
||||
stop()
|
||||
}
|
||||
return {
|
||||
@@ -129,9 +186,12 @@ export function createStreamSource<F, S>(deps: StreamSourceDeps<F>, initial: S,
|
||||
if (listeners.size === 1) {
|
||||
stopReset = deps.subscribeReset(() => {
|
||||
stop()
|
||||
reconnect()
|
||||
// A paused source opens its stream on the new connection when the page shows.
|
||||
if (!paused) reconnect()
|
||||
})
|
||||
stopVisibility = deps.visibility?.subscribe(visibilityChanged)
|
||||
start()
|
||||
visibilityChanged()
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
@@ -146,7 +206,7 @@ export function createStreamSource<F, S>(deps: StreamSourceDeps<F>, initial: S,
|
||||
|
||||
/**
|
||||
* Create the panel source of one Session: the latest state the Host streamed.
|
||||
* @param deps - stream opener and reset subscription.
|
||||
* @param deps - stream opener, reset subscription, and the page's visibility for a source that pauses.
|
||||
* @returns the source.
|
||||
*/
|
||||
export function createPanelSource(deps: PanelSourceDeps): PanelSource {
|
||||
|
||||
@@ -9,8 +9,8 @@ import type {
|
||||
BranchUpdateMethod, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot,
|
||||
ChangeRequestUpdate, ForgeActionFailure, ForgeCommitList,
|
||||
ForgeFailure,
|
||||
ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
|
||||
ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
|
||||
ForgeLineComment, ForgeRerunRequest, ForgeReviewChange, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult,
|
||||
ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
@@ -42,7 +42,7 @@ import { PatchCache } from './patch-cache.ts'
|
||||
import { ReviewCache } from './review-cache.ts'
|
||||
import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
|
||||
import { Reader, ViewerLists } from './viewer-lists.ts'
|
||||
import type { PanelConfig } from './panel.ts'
|
||||
import type { KeptPanel, PanelConfig } from './panel.ts'
|
||||
import type {
|
||||
Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
|
||||
ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame,
|
||||
@@ -113,6 +113,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
interfacePaths: z.array(z.string()).default([]),
|
||||
maxCachedReviewBytes: z.number().default(16_777_216),
|
||||
reviewRefreshMs: z.number().default(60_000),
|
||||
statusMaxAgeMs: z.number().default(10_000),
|
||||
lensTimeoutMs: z.number().default(60_000),
|
||||
maxLensReadBytes: z.number().default(33_554_432),
|
||||
maxCachedLensBytes: z.number().default(4_194_304),
|
||||
@@ -126,11 +127,15 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
private readonly home: Context
|
||||
private readonly config: ControllerConfig
|
||||
private readonly panels = new Map<Session, SessionPanel>()
|
||||
/** What the last panel of a Session kept when its last follower left. */
|
||||
private readonly keptPanels = new WeakMap<Session, KeptPanel>()
|
||||
private worktreeStates!: ProjectionHandle<ForgeWorktreeState>
|
||||
private creations!: WorktreeCreations
|
||||
private readonly patches: PatchCache
|
||||
private readonly layers: FileLayers
|
||||
private readonly reviews: ReviewCache
|
||||
private readonly reviews: ReviewCache<ForgeReviewData>
|
||||
/** The viewed marks read for each change request, by head commit. */
|
||||
private readonly viewed: ReviewCache<ForgeViewedFiles>
|
||||
private readonly lenses = new LensRegistry()
|
||||
private readonly lensResults: LensCache
|
||||
/** Review changes `forge/review-changed` announced per change request, which each panel entry reports. */
|
||||
@@ -149,8 +154,8 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
const resolved = config as Required<Config>
|
||||
if (resolved.gitCommand.trim().length === 0) throw new Error('forge-panel: gitCommand must not be empty')
|
||||
for (const key of [
|
||||
'gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs', 'lensTimeoutMs', 'reviewListIntervalMs',
|
||||
'reviewCountIntervalMs', 'reviewMaxBackoffMs',
|
||||
'gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs', 'statusMaxAgeMs', 'lensTimeoutMs',
|
||||
'reviewListIntervalMs', 'reviewCountIntervalMs', 'reviewMaxBackoffMs',
|
||||
] as const) {
|
||||
const value = resolved[key]
|
||||
if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
|
||||
@@ -176,6 +181,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
this.config = resolved
|
||||
this.patches = new PatchCache(resolved.maxCachedDiffBytes)
|
||||
this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
|
||||
this.viewed = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
|
||||
this.lensResults = new LensCache(resolved.maxCachedLensBytes)
|
||||
ctx.effect(() => () => { this.lenses.close() }, 'forge-panel: lens streams')
|
||||
this.stopPanels = ctx.effect(() => async () => {
|
||||
@@ -225,7 +231,9 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
})
|
||||
// A change request staged for a Session that is disposed before its next message is never bound.
|
||||
const disposed = ctx.on('session/disposed', (session: Session) => { this.staged.delete(session.id) })
|
||||
const reviewChanges = ctx.on('forge/review-changed', (ref: ChangeRequestRef) => { this.reviewChanged(ref) })
|
||||
const reviewChanges = ctx.on('forge/review-changed', (ref: ChangeRequestRef, change: ForgeReviewChange) => {
|
||||
this.reviewChanged(ref, change)
|
||||
})
|
||||
const services = ctx.on('internal/service', (name: string) => {
|
||||
if (name !== 'worktrees') return
|
||||
for (const panel of this.panels.values()) panel.updateWorktree()
|
||||
@@ -356,7 +364,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
update = next
|
||||
if ('snapshot' in next) snapshot = next.snapshot
|
||||
emit()
|
||||
})
|
||||
}, { maxAgeMs: this.config.statusMaxAgeMs })
|
||||
emit()
|
||||
try {
|
||||
yield* reader.frames()
|
||||
@@ -492,21 +500,20 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows.
|
||||
* Read the signed-in user's viewed marks on the files of a change request the review page shows, as
|
||||
* {@link ForgePanelController.changeRequestViewed} keeps them.
|
||||
* @param url - web URL of the change request.
|
||||
* @param headSha - head commit of the shown diff.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or
|
||||
* `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does.
|
||||
*/
|
||||
@Remote
|
||||
async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
|
||||
async reviewViewed(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
|
||||
signal.throwIfAborted()
|
||||
const result = await this.home.forge.viewedFiles(this.served(url).ref, headSha, signal)
|
||||
if (result === undefined) return null
|
||||
if ('code' in result) throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {})
|
||||
return result
|
||||
return await this.readViewed(this.served(url).ref, headSha, fresh, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -726,6 +733,21 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
for (const [session, panel] of this.panels) if (session.id === sessionId) await panel.refresh()
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring a followed Session's panel up to date after its surface showed again: reinspect the checkout, poll the
|
||||
* change requests whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found
|
||||
* the host ready, and look the upstream branch up again while the Session shows no change request; an unfollowed
|
||||
* Session is unchanged.
|
||||
* @param sessionId - Session whose panel is revisited; revisiting neither loads nor resumes it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.
|
||||
*/
|
||||
@Remote
|
||||
async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
for (const [session, panel] of this.panels) if (session.id === sessionId) await panel.revisit()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory, with Git using the Session's sandbox policy.
|
||||
@@ -966,10 +988,13 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
|
||||
* whole change request.
|
||||
* whole change request. Marks read at the same head are kept in memory and returned until they are `reviewRefreshMs`
|
||||
* old or `maxCachedReviewBytes` evicts them; a mark saved through `ctx.forge` at that head replaces the kept state
|
||||
* of its file, so the read after a save costs no request.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param headSha - head commit of the shown diff; marks read at another head are refused.
|
||||
* @param fresh - whether to read the host although kept marks could answer, as after a refresh.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the marks at `headSha`, or null when the provider keeps no viewed marks.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
@@ -977,14 +1002,11 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
* when the host does not provide the marks otherwise.
|
||||
*/
|
||||
@Remote
|
||||
async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
|
||||
async changeRequestViewed(
|
||||
session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal,
|
||||
): Promise<ForgeViewedFiles | null> {
|
||||
signal.throwIfAborted()
|
||||
const result = await this.home.forge.viewedFiles(this.bound(session, url).ref, headSha, signal)
|
||||
if (result === undefined) return null
|
||||
if ('code' in result) {
|
||||
throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {})
|
||||
}
|
||||
return result
|
||||
return await this.readViewed(this.bound(session, url).ref, headSha, fresh, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1454,6 +1476,20 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
return { headSha, files, localAhead, fileUrls }
|
||||
}
|
||||
|
||||
/** Read the viewed marks at a head commit, reusing marks kept for that head unless `fresh`. */
|
||||
private async readViewed(ref: ChangeRequestRef, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null> {
|
||||
const key = changeRequestKey(ref)
|
||||
const readAt = Date.now()
|
||||
const kept = fresh ? undefined : this.viewed.get(key, headSha, readAt)
|
||||
if (kept !== undefined) return kept
|
||||
const token = this.viewed.token()
|
||||
const result = await this.home.forge.viewedFiles(ref, headSha, signal)
|
||||
if (result === undefined) return null
|
||||
if ('code' in result) throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {})
|
||||
this.viewed.set(key, headSha, result, readAt, token)
|
||||
return result
|
||||
}
|
||||
|
||||
/** Set or clear a viewed mark. */
|
||||
private async writeViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise<void> {
|
||||
if (request.path === '') throw new Error('Invalid viewed file')
|
||||
@@ -1630,7 +1666,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
if (key === 'forgeChangeRequests') listener(session.id, visibleUrls(session))
|
||||
}),
|
||||
refOf: url => ctx.forge.changeRequestFromUrl(url),
|
||||
watch: (ref, listener) => ctx.forge.watch(ref, listener),
|
||||
watch: (ref, listener, known) => ctx.forge.watchBrief(ref, listener, known),
|
||||
open: async () => {
|
||||
const domain = await storage.open(changeRequestStatesDomain)
|
||||
return { table: domain.table('states'), close: () => domain.close() }
|
||||
@@ -1640,10 +1676,27 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
return this.states
|
||||
}
|
||||
|
||||
/** Drop the threads kept for a change request after an accepted review change and let its panel entries report it. */
|
||||
private reviewChanged(ref: ChangeRequestRef): void {
|
||||
/**
|
||||
* Bring what is kept for a change request up to date after an accepted review change, and let its panel entries
|
||||
* report it: a saved viewed mark replaces the kept state of its file, which a host lists for every changed file, and
|
||||
* leaves the kept threads; any other change drops the kept threads.
|
||||
*/
|
||||
private reviewChanged(ref: ChangeRequestRef, change: ForgeReviewChange): void {
|
||||
const key = changeRequestKey(ref)
|
||||
this.reviews.drop(key)
|
||||
switch (change.kind) {
|
||||
case 'viewed': {
|
||||
const { path, viewed } = change
|
||||
this.viewed.amend(key, change.headSha, marks => path in marks.files
|
||||
? { ...marks, files: { ...marks.files, [path]: viewed ? 'viewed' : 'unviewed' } } : marks)
|
||||
break
|
||||
}
|
||||
case 'write':
|
||||
case 'submit':
|
||||
this.reviews.drop(key)
|
||||
break
|
||||
/* v8 ignore next -- closed ForgeReviewChange kind union exhaustiveness guard */
|
||||
default: assertNever(change, 'ForgeReviewChange.kind')
|
||||
}
|
||||
this.reviewRevisions.set(key, (this.reviewRevisions.get(key) ?? 0) + 1)
|
||||
for (const panel of this.panels.values()) panel.reviewChanged()
|
||||
for (const follower of this.reviewFollowers) if (follower.key === key) follower.emit()
|
||||
@@ -1729,11 +1782,15 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
let panel = this.panels.get(session)
|
||||
if (panel === undefined) {
|
||||
const revision = (ref: ChangeRequestRef): number => this.reviewRevisions.get(changeRequestKey(ref)) ?? 0
|
||||
const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, revision, () => {
|
||||
const idle = (): void => {
|
||||
if (this.panels.get(session) !== created) return
|
||||
this.panels.delete(session)
|
||||
this.keptPanels.set(session, created.keep())
|
||||
void created.dispose()
|
||||
})
|
||||
}
|
||||
const created: SessionPanel = new SessionPanel(
|
||||
this.home, this.config, session, this.worktreeStates, this.creations, revision, this.keptPanels.get(session), idle,
|
||||
)
|
||||
panel = created
|
||||
this.panels.set(session, panel)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ import type { WorktreeCreations } from './worktree.ts'
|
||||
export interface PanelConfig extends DiffConfig {
|
||||
/** Deadline in milliseconds for one provider sign-in probe. */
|
||||
readonly readinessTimeoutMs: number
|
||||
/** Age in milliseconds past which the status of the Session's change requests is read at once when the panel starts. */
|
||||
readonly statusMaxAgeMs: number
|
||||
/** Prefix of generated worktree branch names, which a name the user types starts from. */
|
||||
readonly worktreePrefix: string
|
||||
}
|
||||
@@ -39,17 +41,38 @@ interface Upstream {
|
||||
readonly branch: string
|
||||
}
|
||||
|
||||
/** What the panel of a Session leaves when its last follower left, for the next panel of that Session to start from. */
|
||||
export interface KeptPanel {
|
||||
/** The last published state. */
|
||||
readonly state: ForgePanelState
|
||||
/** The latest snapshot of each change request, by URL. */
|
||||
readonly snapshots: ReadonlyMap<string, ChangeRequestSnapshot>
|
||||
/** Why the last inspection found that no worktree can be created. */
|
||||
readonly blocker: ForgeWorktreeBlocker | null
|
||||
/** The unavailable worktree the last inspection found. */
|
||||
readonly missing: ForgeMissingWorktree | null
|
||||
/** Remote URL and branch of the upstream that a branch lookup covered. */
|
||||
readonly discovered: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Panel state of one Session. Construction starts the first checkout
|
||||
* inspection and watches the Session's change requests. Inspections run one at
|
||||
* inspection and watches the Session's change requests. A panel given what the
|
||||
* previous panel of the Session kept publishes that state first, with the
|
||||
* current bindings and worktree facts, unless the Session has moved to another
|
||||
* directory. Inspections run one at
|
||||
* a time; a request that arrives during one runs once more after it, and a
|
||||
* result for a directory the Session has since left is dropped. A sign-in
|
||||
* probe runs when an inspection recognizes a new code host and on `refresh`;
|
||||
* probe runs when an inspection recognizes a new code host, after the first
|
||||
* inspection of a panel whose kept probe did not find the host ready, on
|
||||
* `refresh`, on `revisit` while the host is not ready, and once when status
|
||||
* reads on a host shown as ready start to be refused as unauthenticated;
|
||||
* a probe result for a host the panel no longer shows is dropped. Each change
|
||||
* request keeps the latest snapshot a poll returned while later polls fail.
|
||||
* When an inspection finds an upstream branch on a remote a provider
|
||||
* recognizes, the open change requests of that branch are bound as discovered,
|
||||
* once per remote and branch until a refresh. The
|
||||
* once per remote and branch until a refresh, or until a panel starts or is
|
||||
* revisited while the Session shows no change request. The
|
||||
* worktree facts follow the `forgeWorktree` projection, the live creation, and the last failed one;
|
||||
* each inspection also decides whether the Session's sandbox can write the
|
||||
* checkout and its shared Git directory, which a new worktree needs, whether
|
||||
@@ -67,8 +90,12 @@ export class SessionPanel {
|
||||
private missing: ForgeMissingWorktree | null = null
|
||||
private inspection: Promise<void> | null = null
|
||||
private rerun: Promise<void> | null = null
|
||||
/** Remote URL and branch of the upstream that the last branch lookup covered, until a refresh. */
|
||||
/** Remote URL and branch of the upstream that the last branch lookup covered, until the next lookup is due. */
|
||||
private discovered: string | null = null
|
||||
/** Whether the readiness the panel started with must be probed again after its first inspection. */
|
||||
private unconfirmed = false
|
||||
/** Whether a refused status read already started a sign-in probe, until no status read on the host is refused. */
|
||||
private questioned = false
|
||||
|
||||
/**
|
||||
* @param ctx - service context that provides the forge, Session, directory, and process services.
|
||||
@@ -78,6 +105,7 @@ export class SessionPanel {
|
||||
* @param creations - reads the running creation and restoration, the last failed creation, and what a message of the
|
||||
* Session waits for.
|
||||
* @param reviewRevision - reads how many review changes were announced for a change request.
|
||||
* @param kept - what the previous panel of the Session kept, when there was one.
|
||||
* @param onIdle - called when the last follower leaves.
|
||||
*/
|
||||
constructor(
|
||||
@@ -87,23 +115,37 @@ export class SessionPanel {
|
||||
private readonly worktreeStates: ProjectionHandle<ForgeWorktreeState>,
|
||||
private readonly creations: Pick<WorktreeCreations, 'of' | 'restorationOf' | 'failureOf' | 'waitingOf'>,
|
||||
private readonly reviewRevision: (ref: ChangeRequestRef) => number,
|
||||
kept: KeptPanel | undefined,
|
||||
private readonly onIdle: () => void,
|
||||
) {
|
||||
this.current = {
|
||||
directory: ctx.workingDirectory.get(session),
|
||||
checkout: { state: 'pending' },
|
||||
repository: null,
|
||||
readiness: null,
|
||||
changeRequests: this.entries(ctx.forgeSession.changeRequests(session)),
|
||||
worktree: this.worktree(),
|
||||
local: null,
|
||||
const directory = ctx.workingDirectory.get(session)
|
||||
const start = kept?.state.directory === directory ? kept : undefined
|
||||
if (start !== undefined) {
|
||||
for (const [url, snapshot] of start.snapshots) this.snapshots.set(url, snapshot)
|
||||
this.blocker = start.blocker
|
||||
this.missing = start.missing
|
||||
this.unconfirmed = start.state.readiness?.state !== 'ready'
|
||||
}
|
||||
this.stopWatching = ctx.forgeSession.watch(session, (changeRequests) => {
|
||||
this.publish({ ...this.current, changeRequests: this.entries(changeRequests) })
|
||||
})
|
||||
const changeRequests = this.entries(ctx.forgeSession.changeRequests(session))
|
||||
if (start !== undefined && changeRequests.length > 0) this.discovered = start.discovered
|
||||
this.current = start === undefined
|
||||
? { directory, checkout: { state: 'pending' }, repository: null, readiness: null, changeRequests, worktree: this.worktree(), local: null }
|
||||
: { ...start.state, changeRequests, worktree: this.worktree() }
|
||||
this.stopWatching = ctx.forgeSession.watch(session, (latest) => {
|
||||
this.publish({ ...this.current, changeRequests: this.entries(latest) })
|
||||
this.confirmSignIn(latest)
|
||||
}, { maxAgeMs: config.statusMaxAgeMs })
|
||||
void this.inspect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Name what the next panel of the Session starts from.
|
||||
* @returns the last published state and what the inspections and status polls found.
|
||||
*/
|
||||
keep(): KeptPanel {
|
||||
return { state: this.current, snapshots: this.snapshots, blocker: this.blocker, missing: this.missing, discovered: this.discovered }
|
||||
}
|
||||
|
||||
/**
|
||||
* Yield the current state, then each later state, until `signal` aborts or the panel stops.
|
||||
* @param signal - ends this follower.
|
||||
@@ -202,6 +244,24 @@ export class SessionPanel {
|
||||
await Promise.all([inspection, probe])
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the panel up to date after its surface showed again: reinspect the checkout, poll each bound change request
|
||||
* whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found the host ready,
|
||||
* and let the inspection look the upstream branch up again while the Session shows no change request.
|
||||
* @returns settles once the inspection and the sign-in probe have ended; each poll publishes its result when it finishes.
|
||||
*/
|
||||
async revisit(): Promise<void> {
|
||||
if (this.current.changeRequests.length === 0) this.discovered = null
|
||||
const inspection = this.inspect()
|
||||
const { repository, readiness } = this.current
|
||||
// A null readiness has its probe in flight, or due after the inspection.
|
||||
const probe = repository !== null && readiness !== null && readiness.state !== 'ready' ? this.probe(repository) : undefined
|
||||
for (const entry of this.current.changeRequests) {
|
||||
if (entry.ref !== null) this.ctx.forge.refresh(entry.ref, { maxAgeMs: this.config.statusMaxAgeMs })
|
||||
}
|
||||
await Promise.all([inspection, probe])
|
||||
}
|
||||
|
||||
/** Publish the review revisions of the bound change requests after a review change was announced. */
|
||||
reviewChanged(): void {
|
||||
this.publish({ ...this.current, changeRequests: this.entries(this.ctx.forgeSession.changeRequests(this.session)) })
|
||||
@@ -309,7 +369,8 @@ export class SessionPanel {
|
||||
const sameHost = repository !== null && this.current.repository !== null && hostOf(repository) === hostOf(this.current.repository)
|
||||
const readiness = sameHost ? this.current.readiness : null
|
||||
this.publish({ ...this.current, checkout, repository, readiness, worktree: this.worktree(), local })
|
||||
if (repository !== null && !sameHost) void this.probe(repository)
|
||||
if (repository !== null && (!sameHost || this.unconfirmed)) void this.probe(repository)
|
||||
this.unconfirmed = false
|
||||
if (upstream !== null) this.discover(upstream)
|
||||
}
|
||||
|
||||
@@ -360,6 +421,25 @@ export class SessionPanel {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe sign-in again when a status read on the host the panel shows as ready was refused as unauthenticated, once
|
||||
* until a status read on that host is no longer refused.
|
||||
*/
|
||||
private confirmSignIn(changeRequests: readonly SessionChangeRequest[]): void {
|
||||
const { repository, readiness } = this.current
|
||||
if (repository === null) return
|
||||
const refused = changeRequests.some(entry => entry.ref !== null && hostOf(entry.ref.repository) === hostOf(repository)
|
||||
&& entry.update !== null && 'failure' in entry.update && entry.update.failure.code === 'unauthenticated')
|
||||
if (!refused) {
|
||||
this.questioned = false
|
||||
return
|
||||
}
|
||||
if (this.questioned || readiness?.state !== 'ready') return
|
||||
this.questioned = true
|
||||
this.publish({ ...this.current, readiness: null })
|
||||
void this.probe(repository)
|
||||
}
|
||||
|
||||
/** Probe sign-in on the repository's host; resolves once the probe has ended. */
|
||||
private probe(repository: ForgeRepository): Promise<void> {
|
||||
const host = hostOf(repository)
|
||||
|
||||
@@ -1,31 +1,32 @@
|
||||
/**
|
||||
* Review threads of change requests kept in memory, so the changes view reads them from the code host again only
|
||||
* after the change request's head or update time changes, the kept threads reach their age limit, or a review write drops them.
|
||||
* Review reads of change requests kept in memory: the review threads and the viewed marks. The changes view reads
|
||||
* them from the code host again only after the version they were read at changes, the kept read reaches its age
|
||||
* limit, or a write drops it.
|
||||
*/
|
||||
|
||||
import { Buffer } from 'node:buffer'
|
||||
import type { ChangeRequestKey, ForgeReviewData } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
|
||||
interface Entry {
|
||||
/** Head commit and update time the threads were read at. */
|
||||
interface Entry<T> {
|
||||
/** What the read was made at: the head commit and update time of review threads, the head commit of viewed marks. */
|
||||
readonly version: string
|
||||
readonly review: ForgeReviewData
|
||||
readonly read: T
|
||||
/** Epoch milliseconds of the read. */
|
||||
readonly readAt: number
|
||||
/** UTF-8 size of the threads as JSON. */
|
||||
/** UTF-8 size of the read as JSON. */
|
||||
readonly bytes: number
|
||||
}
|
||||
|
||||
/**
|
||||
* One read of review threads per change request, bounded by age and by the total UTF-8 size of the kept reads as
|
||||
* JSON; the least recently read change request leaves first. A read that started before a drop of any change request
|
||||
* is not kept, so threads read before a write never replace the drop.
|
||||
* One read of one kind per change request, bounded by age and by the total UTF-8 size of the kept reads as JSON; the
|
||||
* least recently read change request leaves first. A read that started before a drop or an amendment of any change
|
||||
* request is not kept, so a read made before a write never replaces what the write left.
|
||||
*/
|
||||
export class ReviewCache {
|
||||
private readonly entries = new Map<ChangeRequestKey, Entry>()
|
||||
export class ReviewCache<T> {
|
||||
private readonly entries = new Map<ChangeRequestKey, Entry<T>>()
|
||||
private bytes = 0
|
||||
/** Number of drops so far. */
|
||||
private drops = 0
|
||||
/** Number of drops and amendments so far. */
|
||||
private writes = 0
|
||||
|
||||
/**
|
||||
* @param maxBytes - most UTF-8 bytes kept together; a larger read is not kept.
|
||||
@@ -34,19 +35,19 @@ export class ReviewCache {
|
||||
constructor(private readonly maxBytes: number, private readonly maxAgeMs: number) {}
|
||||
|
||||
/**
|
||||
* Read the threads kept for a change request at a version while they are younger than the age limit, marking them
|
||||
* the most recently read.
|
||||
* Read what is kept for a change request at a version while it is younger than the age limit, marking it the most
|
||||
* recently read.
|
||||
* @param key - the change request.
|
||||
* @param version - head commit and update time the reader needs.
|
||||
* @param version - the version the reader needs.
|
||||
* @param now - current epoch milliseconds.
|
||||
* @returns the threads, or undefined when none are kept at that version or they reached the age limit.
|
||||
* @returns the kept read, or undefined when none is kept at that version or it reached the age limit.
|
||||
*/
|
||||
get(key: ChangeRequestKey, version: string, now: number): ForgeReviewData | undefined {
|
||||
get(key: ChangeRequestKey, version: string, now: number): T | undefined {
|
||||
const entry = this.entries.get(key)
|
||||
if (entry?.version !== version || now - entry.readAt >= this.maxAgeMs) return undefined
|
||||
this.entries.delete(key)
|
||||
this.entries.set(key, entry)
|
||||
return entry.review
|
||||
return entry.read
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,24 +55,52 @@ export class ReviewCache {
|
||||
* @returns the token of the read.
|
||||
*/
|
||||
token(): number {
|
||||
return this.drops
|
||||
return this.writes
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a read in place of the change request's earlier one, then drop the least recently read change requests
|
||||
* until the rest fit within `maxBytes`. A read whose token a drop outdated is not kept.
|
||||
* until the rest fit within `maxBytes`. A read whose token a drop or an amendment outdated is not kept.
|
||||
* @param key - the change request.
|
||||
* @param version - head commit and update time the threads were read at.
|
||||
* @param review - the threads.
|
||||
* @param version - the version the read was made at.
|
||||
* @param read - what was read.
|
||||
* @param readAt - epoch milliseconds when the read started.
|
||||
* @param token - what {@link ReviewCache.token} returned when the read started.
|
||||
*/
|
||||
set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number, token: number): void {
|
||||
if (token !== this.drops) return
|
||||
set(key: ChangeRequestKey, version: string, read: T, readAt: number, token: number): void {
|
||||
if (token !== this.writes) return
|
||||
this.keep(key, version, read, readAt)
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget the read kept for a change request, and every read in flight, after a write changed it.
|
||||
* @param key - the change request.
|
||||
*/
|
||||
drop(key: ChangeRequestKey): void {
|
||||
this.writes += 1
|
||||
this.forget(key)
|
||||
const bytes = Buffer.byteLength(JSON.stringify(review))
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a write whose effect on the read is known: a read kept at `version` becomes `change(read)` and keeps its
|
||||
* age, and one kept at another version is forgotten. Reads in flight are not kept, as after a drop.
|
||||
* @param key - the change request.
|
||||
* @param version - the version the write was made at.
|
||||
* @param change - what the kept read is after the write.
|
||||
*/
|
||||
amend(key: ChangeRequestKey, version: string, change: (read: T) => T): void {
|
||||
this.writes += 1
|
||||
const entry = this.entries.get(key)
|
||||
if (entry === undefined) return
|
||||
if (entry.version === version) this.keep(key, version, change(entry.read), entry.readAt)
|
||||
else this.forget(key)
|
||||
}
|
||||
|
||||
private keep(key: ChangeRequestKey, version: string, read: T, readAt: number): void {
|
||||
this.forget(key)
|
||||
const bytes = Buffer.byteLength(JSON.stringify(read))
|
||||
if (bytes > this.maxBytes) return
|
||||
this.entries.set(key, { version, review, readAt, bytes })
|
||||
this.entries.set(key, { version, read, readAt, bytes })
|
||||
this.bytes += bytes
|
||||
for (const [oldest, entry] of this.entries) {
|
||||
if (this.bytes <= this.maxBytes) break
|
||||
@@ -80,15 +109,6 @@ export class ReviewCache {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget the threads kept for a change request, and every read in flight, after a write changed them.
|
||||
* @param key - the change request.
|
||||
*/
|
||||
drop(key: ChangeRequestKey): void {
|
||||
this.drops += 1
|
||||
this.forget(key)
|
||||
}
|
||||
|
||||
private forget(key: ChangeRequestKey): void {
|
||||
const previous = this.entries.get(key)
|
||||
if (previous === undefined) return
|
||||
|
||||
@@ -2,16 +2,20 @@
|
||||
* The last known state of every change request that a listed Session binds,
|
||||
* for the Session list. One run starts with the first stream and stops with
|
||||
* the last: it reads the stored states, lists the Sessions with their
|
||||
* bindings, follows binding changes of loaded Sessions, and polls each bound
|
||||
* change request, once however many Sessions bind it. The forge service
|
||||
* owns polling cadence and terminal-state refresh. Every state change is stored, so a restart shows it before the
|
||||
* first poll.
|
||||
* bindings, follows binding changes of loaded Sessions, and polls the brief of
|
||||
* each bound change request, once however many Sessions bind it. The forge
|
||||
* service owns polling cadence and terminal-state refresh; a run tells it the
|
||||
* state it already holds, so a merged change request is not read again and one
|
||||
* read by an earlier run of this process waits for its interval. Every state
|
||||
* change is stored, so a restart shows it before the first poll.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import { defineDomain } from '@deepseek-ai/dsh-storage-domain'
|
||||
import type { ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type {
|
||||
ChangeRequestBrief, ChangeRequestBriefListener, ChangeRequestKnownState, ChangeRequestRef,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame } from './types.ts'
|
||||
|
||||
@@ -77,24 +81,24 @@ export interface ChangeRequestStateSources {
|
||||
readonly onBindings: (listener: (id: SessionId, urls: readonly string[]) => void) => () => void
|
||||
/** The change request a URL names, or undefined when no provider recognizes it. */
|
||||
readonly refOf: (url: string) => ChangeRequestRef | undefined
|
||||
/** Poll a change request until the returned disposer runs. */
|
||||
readonly watch: (ref: ChangeRequestRef, listener: ChangeRequestListener) => () => void
|
||||
/** Poll the brief of a change request until the returned disposer runs; `known` times the first poll. */
|
||||
readonly watch: (ref: ChangeRequestRef, listener: ChangeRequestBriefListener, known?: ChangeRequestKnownState) => () => void
|
||||
/** Open the stored states; the run owns and closes the returned handle. */
|
||||
readonly open: () => Promise<OpenedStates>
|
||||
/** Report a failed durable write; the state stays in memory. */
|
||||
readonly report: (error: unknown) => void
|
||||
}
|
||||
|
||||
function listStateOf(snapshot: ChangeRequestSnapshot, url: string): ForgeChangeRequestListState {
|
||||
function listStateOf(brief: ChangeRequestBrief, url: string): ForgeChangeRequestListState {
|
||||
return {
|
||||
url,
|
||||
number: snapshot.ref.number,
|
||||
title: snapshot.title,
|
||||
state: snapshot.state,
|
||||
draft: snapshot.draft,
|
||||
checksRollup: snapshot.checksRollup,
|
||||
reviewDecision: snapshot.reviewDecision,
|
||||
mergeability: snapshot.mergeability,
|
||||
number: brief.ref.number,
|
||||
title: brief.title,
|
||||
state: brief.state,
|
||||
draft: brief.draft,
|
||||
checksRollup: brief.checksRollup,
|
||||
reviewDecision: brief.reviewDecision,
|
||||
mergeability: brief.mergeability,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,10 +165,17 @@ class Run {
|
||||
private readonly writes = new Set<Promise<void>>()
|
||||
private stopped = false
|
||||
|
||||
/**
|
||||
* @param sources - what the run reads, follows, and polls.
|
||||
* @param readers - the streams the run publishes to.
|
||||
* @param storage - the stored states, which the run owns and closes.
|
||||
* @param readAt - epoch milliseconds of the latest read of each URL in this process, kept across runs.
|
||||
*/
|
||||
constructor(
|
||||
private readonly sources: ChangeRequestStateSources,
|
||||
private readonly readers: ReadonlySet<Reader>,
|
||||
private readonly storage: OpenedStates,
|
||||
private readonly readAt: Map<string, number>,
|
||||
) {
|
||||
for (const [, state] of storage.table.entries()) this.states.set(state.url, state)
|
||||
// Subscribe before listing; updates received during the read supersede its snapshot.
|
||||
@@ -190,6 +201,7 @@ class Run {
|
||||
for (const [url] of this.states) {
|
||||
if (this.sessionsOf.has(url)) continue
|
||||
this.states.delete(url)
|
||||
this.readAt.delete(url)
|
||||
this.write(() => this.storage.table.delete(storedKey(url)))
|
||||
}
|
||||
}
|
||||
@@ -246,10 +258,16 @@ class Run {
|
||||
if (this.polls.has(url)) return
|
||||
const ref = this.sources.refOf(url)
|
||||
if (ref === undefined) return
|
||||
const state = this.states.get(url)
|
||||
// A stored state that this process has not read counts as read at the epoch, so every state but a merged one is read at once.
|
||||
const known = state === undefined ? undefined : {
|
||||
state: state.state, mergeability: state.mergeability, checksRollup: state.checksRollup, fetchedAt: this.readAt.get(url) ?? 0,
|
||||
}
|
||||
this.polls.set(url, this.sources.watch(ref, (update) => {
|
||||
if ('failure' in update) return
|
||||
this.settle(url, ids, listStateOf(update.snapshot, url))
|
||||
}))
|
||||
this.readAt.set(url, update.fetchedAt)
|
||||
this.settle(url, ids, listStateOf(update.brief, url))
|
||||
}, known))
|
||||
}
|
||||
|
||||
private settle(url: string, ids: ReadonlySet<SessionId>, state: ForgeChangeRequestListState): void {
|
||||
@@ -270,6 +288,8 @@ class Run {
|
||||
/** Streams the states of the change requests that listed Sessions bind. */
|
||||
export class ChangeRequestStates {
|
||||
private readonly readers = new Set<Reader>()
|
||||
/** Epoch milliseconds of the latest read of each change request URL, which outlives the runs. */
|
||||
private readonly readAt = new Map<string, number>()
|
||||
private stopping: Promise<void> = Promise.resolve()
|
||||
private disposed = false
|
||||
private run: { readonly started: Promise<Run | undefined>; readonly aborter: AbortController } | undefined
|
||||
@@ -324,7 +344,7 @@ export class ChangeRequestStates {
|
||||
let run: Run | undefined
|
||||
try {
|
||||
aborter.signal.throwIfAborted()
|
||||
run = new Run(this.sources, this.readers, storage)
|
||||
run = new Run(this.sources, this.readers, storage, this.readAt)
|
||||
await run.start(aborter.signal)
|
||||
return run
|
||||
} catch (error) {
|
||||
|
||||
@@ -620,13 +620,22 @@ export interface Config {
|
||||
* `testPaths` and before the built-in rules.
|
||||
*/
|
||||
interfacePaths?: string[]
|
||||
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
|
||||
/**
|
||||
* Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit
|
||||
* and update time, and, counted apart, of viewed marks kept for later reads at the same head commit.
|
||||
*/
|
||||
maxCachedReviewBytes?: number
|
||||
/**
|
||||
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
|
||||
* request's update time does not change when a thread is resolved.
|
||||
* Age in milliseconds at which review threads and viewed marks kept in memory are read from the code host again; a
|
||||
* GitHub pull request's update time does not change when a thread is resolved, and nothing announces a mark changed
|
||||
* on the code host itself.
|
||||
*/
|
||||
reviewRefreshMs?: number
|
||||
/**
|
||||
* Age in milliseconds past which the status of a change request is read at once when a Session's panel or the
|
||||
* review page starts to show it.
|
||||
*/
|
||||
statusMaxAgeMs?: number
|
||||
/** Deadline in milliseconds for one lens `classify` call. */
|
||||
lensTimeoutMs?: number
|
||||
/** Most UTF-8 bytes of file text one lens `classify` call may read. */
|
||||
|
||||
@@ -1554,6 +1554,19 @@ describe('ChangesTab change requests', () => {
|
||||
expect(within(failed.view.container).getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}${en['diff.viewInBrowser']}`)
|
||||
})
|
||||
|
||||
it('waits for the first status of a change request whose entry shows a snapshot kept from an earlier panel stream', async () => {
|
||||
const m = mount({ source, state: ready({ changeRequests: [{ ...entry(7, null), snapshot: snapshot(7) }] }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).not.toHaveBeenCalled()
|
||||
expect(m.faces.changeRequestReview).not.toHaveBeenCalled()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7))] }), disconnected: false }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce()
|
||||
expect(m.faces.changeRequestReview).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('names a change request without a snapshot by its URL and the number the URL ends in', async () => {
|
||||
const m = mount({ source, state: ready() })
|
||||
expect(m.view.getByRole('img', { name: 'Change request state: Unknown' })).toBeTruthy()
|
||||
@@ -2127,7 +2140,7 @@ describe('ChangesTab viewed marks the host keeps', () => {
|
||||
faces.setFileViewed.mockReturnValueOnce(saved.promise)
|
||||
} })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestViewed).toHaveBeenCalledWith(URL7, HEAD, expect.any(AbortSignal))
|
||||
expect(m.faces.changeRequestViewed).toHaveBeenCalledWith(URL7, HEAD, false, expect.any(AbortSignal))
|
||||
expect(marks(m)).toEqual([['docs/gone.txt', 'unviewed', 'open'], ['docs/notes.txt', 'changed', 'open'], ['src/app.ts', 'viewed', 'closed']])
|
||||
expect(m.view.getByRole('progressbar').getAttribute('aria-valuetext')).toBe('1 / 3 viewed')
|
||||
|
||||
@@ -2209,6 +2222,27 @@ describe('ChangesTab viewed marks the host keeps', () => {
|
||||
expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts'])
|
||||
})
|
||||
|
||||
it('skips the marks the host keeps for the read a refresh starts, until that read finished', async () => {
|
||||
const refreshed = Promise.withResolvers<ReturnType<typeof hosted>>()
|
||||
const m = mount({ source, setup: (faces) => { faces.changeRequestViewed.mockResolvedValue(hosted({})) } })
|
||||
await settle()
|
||||
const fresh = (): boolean[] => m.faces.changeRequestViewed.mock.calls.map(call => call[2])
|
||||
expect(fresh()).toEqual([false])
|
||||
|
||||
m.faces.changeRequestViewed.mockReturnValueOnce(refreshed.promise)
|
||||
fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] }))
|
||||
await settle()
|
||||
// A review change that arrives during the refresh starts the read again, which still skips the kept marks.
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7), { reviewRevision: 1 })] }), disconnected: false }) })
|
||||
await settle()
|
||||
expect(fresh()).toEqual([false, true, true])
|
||||
|
||||
await act(async () => { refreshed.resolve(hosted({})); await Promise.resolve() })
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7), { reviewRevision: 2 })] }), disconnected: false }) })
|
||||
await settle()
|
||||
expect(fresh()).toEqual([false, true, true, false])
|
||||
})
|
||||
|
||||
it('keeps the marks of chosen commits in the browser without reading the host', async () => {
|
||||
const m = mount({ source, setup: (faces) => { faces.changeRequestViewed.mockResolvedValue(hosted({ 'src/app.ts': 'viewed' })) } })
|
||||
await settle()
|
||||
@@ -2285,7 +2319,7 @@ describe('ChangesTab viewed marks the host keeps', () => {
|
||||
const status = { ...polled, update: { ...polled.update!, fetchedAt: 2 } }
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [status] }), disconnected: false }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestViewed).toHaveBeenLastCalledWith(URL7, moved, expect.any(AbortSignal))
|
||||
expect(m.faces.changeRequestViewed).toHaveBeenLastCalledWith(URL7, moved, false, expect.any(AbortSignal))
|
||||
expect(marks(m)[2]?.[1]).toBe('unviewed')
|
||||
expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false)
|
||||
// A write at the new head is in flight when the earlier one settles, which leaves it and its lock alone.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ForgeFailure, ForgeProvider, ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ForgeFailure, ForgeProvider, ForgeReadiness, ForgeReviewData, ForgeViewedFiles } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import { appendPluginRecord, type SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
@@ -189,6 +189,25 @@ describe('forgePanel.follow', () => {
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['at once when its latest status is older than statusMaxAgeMs', { statusMaxAgeMs: 1 }, [[7], [7]]],
|
||||
['with the regular poll when its latest status is younger', {}, [[7]]],
|
||||
])('reads a bound change request that another watcher already read %s, when the panel starts', async (_, config, fetches) => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, config)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
// Another watcher, as the review page is, read the status before the panel starts; it ends with the context.
|
||||
opened.ctx.forge.watch({ repository: demo, number: 7 }, () => {})
|
||||
await vi.waitFor(() => { expect(opened.provider.fetches).toEqual([[7]]) })
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
|
||||
const follower = reader(opened)
|
||||
await follower.until(state => polled(state, pullUrl(7)))
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
|
||||
expect(opened.provider.fetches).toEqual(fetches)
|
||||
})
|
||||
|
||||
it('binds the open change requests of the upstream branch once per remote and branch, and looks again on refresh', async () => {
|
||||
const { repo } = await project()
|
||||
await git(repo, 'checkout', '-b', 'feat')
|
||||
@@ -366,7 +385,7 @@ describe('forgePanel.follow', () => {
|
||||
expect(follower.states.every(state => state.checkout.state !== 'ready' || state.directory === linked)).toBe(true)
|
||||
})
|
||||
|
||||
it('shares one panel among followers and starts a fresh one after the last leaves', async () => {
|
||||
it('shares one panel among followers and starts the next one from the kept state after the last leaves', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
@@ -382,7 +401,9 @@ describe('forgePanel.follow', () => {
|
||||
expect(opened.ctx.forge.latest(ref)).toBeUndefined()
|
||||
|
||||
const third = reader(opened)
|
||||
await expect(third.until(() => true)).resolves.toMatchObject({ checkout: { state: 'pending' } })
|
||||
await expect(third.until(() => true)).resolves.toMatchObject({
|
||||
checkout: { state: 'ready' }, changeRequests: [{ url: pullUrl(7), update: null, snapshot: snapshot(ref) }],
|
||||
})
|
||||
})
|
||||
|
||||
it('ends followers whose signal aborts while waiting and when the Remote stops', async () => {
|
||||
@@ -2045,33 +2066,93 @@ describe('forgePanel actions', () => {
|
||||
const head = 'a'.repeat(40)
|
||||
const request = { path: 'src/app.ts', viewed: true, headSha: head }
|
||||
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)).resolves.toBeNull()
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, false, signal)).resolves.toBeNull()
|
||||
await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider keeps no viewed marks' })
|
||||
const marks = { headSha: head, files: { 'src/app.ts': 'dismissed' as const }, truncated: false }
|
||||
const viewedFiles = vi.fn<NonNullable<ForgeProvider['viewedFiles']>>(async () => marks)
|
||||
const setViewed = vi.fn<NonNullable<ForgeProvider['setViewed']>>(async () => undefined)
|
||||
Object.assign(opened.provider, { viewedFiles, setViewed })
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)).resolves.toEqual(marks)
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, false, signal)).resolves.toEqual(marks)
|
||||
await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal)).resolves.toBeUndefined()
|
||||
expect(setViewed).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), request, expect.any(AbortSignal))
|
||||
|
||||
// The marks kept from the read above would answer a read that is not fresh.
|
||||
viewedFiles.mockResolvedValueOnce({ code: 'stale', message: 'moved' }).mockResolvedValueOnce({ code: 'unavailable', message: 'rate limited' })
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal))
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, true, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'moved' })
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal))
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, true, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/viewed-failed', message: 'rate limited' })
|
||||
setViewed.mockResolvedValueOnce({ code: 'stale', message: 'moved' })
|
||||
await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/stale-head' })
|
||||
await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), { ...request, path: '' }, signal)).rejects.toThrow('Invalid viewed file')
|
||||
for (const url of [pullUrl(8), 'https://unserved.test/a/b/pull/3']) {
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, url, head, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
|
||||
await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, url, head, false, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
|
||||
await expect(opened.ctx.forgePanel.setFileViewed(opened.session, url, request, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
|
||||
}
|
||||
expect(setViewed).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps the viewed marks read at a head, amends them after a saved mark, and reads the host again when asked or at another head', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
await reader(opened).until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
const head = 'a'.repeat(40)
|
||||
const other = 'b'.repeat(40)
|
||||
const listed = (headSha: string): ForgeViewedFiles => ({ headSha, files: { 'src/app.ts': 'dismissed', 'docs/notes.txt': 'viewed' }, truncated: false })
|
||||
const viewedFiles = vi.fn<NonNullable<ForgeProvider['viewedFiles']>>(async (_ref, headSha) => listed(headSha))
|
||||
const setViewed = vi.fn<NonNullable<ForgeProvider['setViewed']>>(async () => undefined)
|
||||
const threads: ForgeReviewData = {
|
||||
headSha: head, viewer: null, threads: [], truncated: false, pendingReview: null, viewerCanReview: false, reviewEvents: [],
|
||||
}
|
||||
const readReview = vi.fn<NonNullable<ForgeProvider['readReview']>>(async () => threads)
|
||||
Object.assign(opened.provider, { viewedFiles, setViewed, readReview })
|
||||
const panel = opened.ctx.forgePanel
|
||||
const read = (headSha = head, fresh = false): Promise<ForgeViewedFiles | null> =>
|
||||
panel.changeRequestViewed(opened.session, pullUrl(7), headSha, fresh, signal)
|
||||
const save = (path: string, viewed: boolean, headSha = head): Promise<void> =>
|
||||
panel.setFileViewed(opened.session, pullUrl(7), { path, viewed, headSha }, signal)
|
||||
|
||||
await expect(read()).resolves.toEqual(listed(head))
|
||||
await expect(read()).resolves.toEqual(listed(head))
|
||||
expect(viewedFiles).toHaveBeenCalledOnce()
|
||||
await expect(panel.changeRequestReview(opened.session, pullUrl(7), head, false, signal)).resolves.toEqual(threads)
|
||||
|
||||
// A saved mark replaces the kept state of a listed file and leaves the kept threads.
|
||||
await save('src/app.ts', true)
|
||||
await save('docs/notes.txt', false)
|
||||
await save('unlisted.ts', true)
|
||||
await expect(read()).resolves.toEqual({ headSha: head, files: { 'src/app.ts': 'viewed', 'docs/notes.txt': 'unviewed' }, truncated: false })
|
||||
await expect(panel.changeRequestReview(opened.session, pullUrl(7), head, false, signal)).resolves.toEqual(threads)
|
||||
expect(viewedFiles).toHaveBeenCalledOnce()
|
||||
expect(readReview).toHaveBeenCalledOnce()
|
||||
|
||||
// A fresh read replaces the kept marks with what the host lists.
|
||||
await expect(read(head, true)).resolves.toEqual(listed(head))
|
||||
await expect(read()).resolves.toEqual(listed(head))
|
||||
expect(viewedFiles).toHaveBeenCalledTimes(2)
|
||||
|
||||
// A mark saved at another head forgets the kept marks, and a read that the save overtook is not kept.
|
||||
const held = Promise.withResolvers<ForgeViewedFiles>()
|
||||
await save('src/app.ts', true, other)
|
||||
viewedFiles.mockReturnValueOnce(held.promise)
|
||||
const overtaken = read()
|
||||
await save('src/app.ts', false)
|
||||
held.resolve(listed(head))
|
||||
await expect(overtaken).resolves.toEqual(listed(head))
|
||||
await expect(read()).resolves.toEqual(listed(head))
|
||||
expect(viewedFiles).toHaveBeenCalledTimes(4)
|
||||
|
||||
// A review write drops the kept threads and leaves the kept marks.
|
||||
await opened.ctx.parallel('forge/review-changed', { repository: demo, number: 7 }, { kind: 'submit', headSha: head })
|
||||
await expect(panel.changeRequestReview(opened.session, pullUrl(7), head, false, signal)).resolves.toEqual(threads)
|
||||
await expect(read()).resolves.toEqual(listed(head))
|
||||
expect(readReview).toHaveBeenCalledTimes(2)
|
||||
expect(viewedFiles).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('reruns checks, requests reviews, lists reviewers, and updates the branch of a bound change request', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
@@ -2256,6 +2337,8 @@ describe('forgePanel configuration', () => {
|
||||
[{ graceMs: 1.5 }, 'forge-panel: graceMs must be a positive integer no greater than 2147483647'],
|
||||
[{ maxOutputBytes: -1 }, 'forge-panel: maxOutputBytes must be a positive integer no greater than 2147483647'],
|
||||
[{ readinessTimeoutMs: 2_147_483_648 }, 'forge-panel: readinessTimeoutMs must be a positive integer no greater than 2147483647'],
|
||||
[{ statusMaxAgeMs: 0 }, 'forge-panel: statusMaxAgeMs must be a positive integer no greater than 2147483647'],
|
||||
[{ statusMaxAgeMs: 1.5 }, 'forge-panel: statusMaxAgeMs must be a positive integer no greater than 2147483647'],
|
||||
[{ maxBranches: 0 }, 'forge-panel: maxBranches must be a positive integer'],
|
||||
[{ maxBranches: 2.5 }, 'forge-panel: maxBranches must be a positive integer'],
|
||||
[{ maxCachedDiffBytes: 0 }, 'forge-panel: maxCachedDiffBytes must be a positive integer'],
|
||||
|
||||
@@ -224,10 +224,11 @@ async function base() {
|
||||
): Read<readonly ForgeReviewerCandidate[]> => ({ ok: true, value: [{ login: 'mona', name: null, avatarUrl: null, suggested: true }] })),
|
||||
updateBranch: vi.fn(async (_sessionId: SessionId, _url: string, _method: string, _headSha: string): Promise<RemoteResult<void>> => OK),
|
||||
changeRequestViewed: vi.fn(async (
|
||||
_sessionId: SessionId, _url: string, _headSha: string, _signal: AbortSignal,
|
||||
_sessionId: SessionId, _url: string, _headSha: string, _fresh: boolean, _signal: AbortSignal,
|
||||
): Read<ForgeViewedFiles | null> => ({ ok: true, value: null })),
|
||||
setFileViewed: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeViewedRequest): Promise<RemoteResult<void>> => OK),
|
||||
refresh: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
revisit: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null, _name: string | null): Promise<RemoteResult<void>> => OK),
|
||||
cancelWorktree: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
stopCreation: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
@@ -284,7 +285,7 @@ async function base() {
|
||||
reviewDiff: vi.fn(async (_url: string, _commits: ForgeCommitRange | null, _signal: AbortSignal): Read<ForgeChangeRequestDiff> =>
|
||||
({ ok: true, value: CHANGE })),
|
||||
reviewCommits: vi.fn(async (_url: string, _signal: AbortSignal): Read<ForgeCommitList | null> => ({ ok: true, value: COMMITS })),
|
||||
reviewViewed: vi.fn(async (_url: string, _headSha: string, _signal: AbortSignal): Read<ForgeViewedFiles | null> =>
|
||||
reviewViewed: vi.fn(async (_url: string, _headSha: string, _fresh: boolean, _signal: AbortSignal): Read<ForgeViewedFiles | null> =>
|
||||
({ ok: true, value: null })),
|
||||
reviewSetViewed: vi.fn(async (_url: string, _request: ForgeViewedRequest): Promise<RemoteResult<void>> => OK),
|
||||
reviewText: vi.fn(async (_url: string, _commit: string, _path: string): Read<string> => ({ ok: true, value: 'c\n' })),
|
||||
@@ -810,7 +811,7 @@ describe('mountForgePanel Session panel actions', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('refreshes each Session automatically at most once every 10 seconds', async () => {
|
||||
it('revisits each Session automatically at most once every 10 seconds', async () => {
|
||||
const f = await fixture()
|
||||
for (const id of [S1, S2]) f.section(id).hooks.panel.subscribe(() => {})
|
||||
await vi.waitFor(() => { expect(f.streams).toHaveLength(2) })
|
||||
@@ -822,14 +823,16 @@ describe('mountForgePanel Session panel actions', () => {
|
||||
refreshIfStale()
|
||||
refreshIfStale()
|
||||
f.checkout(S2).refreshIfStale()
|
||||
expect(f.forgePanel.refresh.mock.calls).toEqual([[S1], [S2]])
|
||||
expect(f.forgePanel.revisit.mock.calls).toEqual([[S1], [S2]])
|
||||
now.mockReturnValue(1_009_999)
|
||||
refreshIfStale()
|
||||
expect(f.forgePanel.refresh).toHaveBeenCalledTimes(2)
|
||||
expect(f.forgePanel.revisit).toHaveBeenCalledTimes(2)
|
||||
now.mockReturnValue(1_010_000)
|
||||
refreshIfStale()
|
||||
expect(f.forgePanel.refresh.mock.calls).toEqual([[S1], [S2], [S1]])
|
||||
f.forgePanel.refresh.mockResolvedValueOnce(REFUSED.failed)
|
||||
expect(f.forgePanel.revisit.mock.calls).toEqual([[S1], [S2], [S1]])
|
||||
// The refresh a reader asks for is a separate, forced read.
|
||||
expect(f.forgePanel.refresh).not.toHaveBeenCalled()
|
||||
f.forgePanel.revisit.mockResolvedValueOnce(REFUSED.failed)
|
||||
now.mockReturnValue(1_020_000)
|
||||
refreshIfStale()
|
||||
await settle()
|
||||
@@ -837,27 +840,67 @@ describe('mountForgePanel Session panel actions', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('defers an automatic refresh asked for before the panel state arrives until the Host follows the panel', async () => {
|
||||
it('defers an automatic revisit asked for before the panel state arrives until the Host follows the panel', async () => {
|
||||
const f = await fixture()
|
||||
const unsubscribe = f.section(S1).hooks.panel.subscribe(() => {})
|
||||
f.checkout(S1).refreshIfStale()
|
||||
await vi.waitFor(() => { expect(f.forgePanel.follow).toHaveBeenCalledOnce() })
|
||||
expect(f.forgePanel.refresh).not.toHaveBeenCalled()
|
||||
expect(f.forgePanel.revisit).not.toHaveBeenCalled()
|
||||
f.streams[0]?.push(ready())
|
||||
await vi.waitFor(() => { expect(f.forgePanel.refresh).toHaveBeenCalledWith(S1) })
|
||||
await vi.waitFor(() => { expect(f.forgePanel.revisit).toHaveBeenCalledWith(S1) })
|
||||
f.streams[0]?.push(ready({ local: null }))
|
||||
await settle()
|
||||
expect(f.forgePanel.refresh).toHaveBeenCalledOnce()
|
||||
// A later stream refreshes nothing on its own: only a refresh that was asked for waits for the first state.
|
||||
expect(f.forgePanel.revisit).toHaveBeenCalledOnce()
|
||||
// A later stream revisits nothing on its own: only a revisit that was asked for waits for the first state.
|
||||
f.ctx.emit('connection/reset')
|
||||
await vi.waitFor(() => { expect(f.streams).toHaveLength(2) })
|
||||
f.streams[1]?.push(ready())
|
||||
await settle()
|
||||
expect(f.forgePanel.refresh).toHaveBeenCalledOnce()
|
||||
expect(f.forgePanel.revisit).toHaveBeenCalledOnce()
|
||||
unsubscribe()
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('closes the panel, Session list, and review count streams once the page was hidden for 30 seconds, and opens them when it shows', async () => {
|
||||
const f = await fixture()
|
||||
const visibility = vi.spyOn(document, 'visibilityState', 'get')
|
||||
const show = (state: DocumentVisibilityState): void => {
|
||||
visibility.mockReturnValue(state)
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
const panel = f.section(S1).hooks.panel.subscribe(() => {})
|
||||
const list = f.list('row').hooks.states.subscribe(() => {})
|
||||
const extensions = f.changes(S1).hooks.extensions.subscribe(() => {})
|
||||
const face = f.entry('sidebar.panellist.trailing', ReviewNavCount)?.inject?.()
|
||||
assert(face !== undefined && isReviewCountFace(face))
|
||||
const count = face.hooks.count.subscribe(() => {})
|
||||
await vi.waitFor(() => { expect(f.streams).toHaveLength(1) })
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
show('hidden')
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
expect(f.streams[0]?.disposed).toHaveBeenCalled()
|
||||
expect(f.stateStreams[0]?.disposed).toHaveBeenCalled()
|
||||
expect(f.countStreams[0]?.disposed).toHaveBeenCalled()
|
||||
// The extension stream reads nothing from a code host and stays open.
|
||||
expect(f.extensionStreams[0]?.disposed).not.toHaveBeenCalled()
|
||||
|
||||
show('visible')
|
||||
await vi.waitFor(() => { expect(f.streams).toHaveLength(2) })
|
||||
expect(f.stateStreams).toHaveLength(2)
|
||||
expect(f.countStreams).toHaveLength(2)
|
||||
expect(f.extensionStreams).toHaveLength(1)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
visibility.mockRestore()
|
||||
}
|
||||
panel()
|
||||
list()
|
||||
extensions()
|
||||
count()
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('restores a removed worktree, confirming it or reporting why it failed until the notice is dismissed', async () => {
|
||||
const f = await fixture()
|
||||
f.checkout(S1).restore()
|
||||
@@ -1010,8 +1053,8 @@ describe('mountForgePanel overview actions', () => {
|
||||
const f = await fixture()
|
||||
const signal = new AbortController().signal
|
||||
const view = f.changes(S1)
|
||||
expect(await view.changeRequestViewed(url, 'a'.repeat(40), signal)).toEqual({ ok: true, value: null })
|
||||
expect(f.forgePanel.changeRequestViewed).toHaveBeenCalledWith(S1, url, 'a'.repeat(40), signal)
|
||||
expect(await view.changeRequestViewed(url, 'a'.repeat(40), true, signal)).toEqual({ ok: true, value: null })
|
||||
expect(f.forgePanel.changeRequestViewed).toHaveBeenCalledWith(S1, url, 'a'.repeat(40), true, signal)
|
||||
const request = { path: 'src/a.ts', viewed: true, headSha: 'a'.repeat(40) }
|
||||
expect(await view.setFileViewed(url, request)).toEqual(OK)
|
||||
expect(f.forgePanel.setFileViewed).toHaveBeenCalledWith(S1, url, request)
|
||||
@@ -1691,8 +1734,8 @@ describe('mountForgePanel review page changes view', () => {
|
||||
expect(f.forgePanel.reviewDiff).toHaveBeenCalledWith(url, null, signal)
|
||||
expect(await f.view.changeRequestCommits(url, signal)).toEqual({ ok: true, value: COMMITS })
|
||||
expect(f.forgePanel.reviewCommits).toHaveBeenCalledWith(url, signal)
|
||||
expect(await f.view.changeRequestViewed(url, head, signal)).toEqual({ ok: true, value: null })
|
||||
expect(f.forgePanel.reviewViewed).toHaveBeenCalledWith(url, head, signal)
|
||||
expect(await f.view.changeRequestViewed(url, head, true, signal)).toEqual({ ok: true, value: null })
|
||||
expect(f.forgePanel.reviewViewed).toHaveBeenCalledWith(url, head, true, signal)
|
||||
const viewed: ForgeViewedRequest = { path: 'a.ts', viewed: true, headSha: head }
|
||||
expect(await f.view.setFileViewed(url, viewed)).toEqual(OK)
|
||||
expect(f.forgePanel.reviewSetViewed).toHaveBeenCalledWith(url, viewed)
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
/** A Session panel that starts again after its last follower left, the revisit of a followed one, and sign-in after a refused read. */
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Config, ForgePanelState } from '../src/index.ts'
|
||||
import { bench, demo, follow, git, pullUrl, repository, scratch, shellTurn, snapshot } from './harness.ts'
|
||||
import type { Bench, Follower } from './harness.ts'
|
||||
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
|
||||
})
|
||||
|
||||
const signal = new AbortController().signal
|
||||
const seven = { repository: demo, number: 7 }
|
||||
const READY: ForgeReadiness = { state: 'ready', message: null, signIn: null }
|
||||
const SIGNED_OUT: ForgeReadiness = { state: 'unauthenticated', message: 'sign in', signIn: null }
|
||||
const UNSERVED = 'https://unserved.test/a/b/pull/3'
|
||||
|
||||
async function project(remote = 'https://fake.test/octo/demo.git'): Promise<{ root: string; repo: string }> {
|
||||
const { path, remove } = await scratch('dsh-forge-revisit-')
|
||||
cleanups.push(remove)
|
||||
const repo = await repository(path)
|
||||
await git(repo, 'remote', 'add', 'origin', remote)
|
||||
return { root: path, repo }
|
||||
}
|
||||
|
||||
/** A project on branch `feat` that tracks `origin/feat`, so an inspection finds an upstream branch to look up. */
|
||||
async function tracking(): Promise<string> {
|
||||
const { repo } = await project()
|
||||
await git(repo, 'checkout', '-b', 'feat')
|
||||
await git(repo, 'update-ref', 'refs/remotes/origin/feat', 'HEAD')
|
||||
await git(repo, 'branch', '--set-upstream-to=origin/feat')
|
||||
return repo
|
||||
}
|
||||
|
||||
async function open(cwd: string, config: Config = {}): Promise<Bench> {
|
||||
const opened = await bench(cwd, config)
|
||||
cleanups.push(() => opened.ctx.fiber.dispose())
|
||||
return opened
|
||||
}
|
||||
|
||||
function reader(opened: Bench): Follower {
|
||||
const follower = follow(opened.ctx, opened.session)
|
||||
cleanups.push(follower.stop)
|
||||
return follower
|
||||
}
|
||||
|
||||
const ready = (state: ForgePanelState): boolean => state.checkout.state === 'ready' && state.readiness !== null
|
||||
|
||||
/** Whether the change request at `url` holds a snapshot. */
|
||||
function polled(state: ForgePanelState, url: string): boolean {
|
||||
return (state.changeRequests.find(entry => entry.url === url)?.snapshot ?? null) !== null
|
||||
}
|
||||
|
||||
/** Whether the latest polling result of the change request at `url` is a failure. */
|
||||
function failing(state: ForgePanelState, url: string): boolean {
|
||||
const update = state.changeRequests.find(entry => entry.url === url)?.update ?? null
|
||||
return update !== null && 'failure' in update
|
||||
}
|
||||
|
||||
function commitOf(state: ForgePanelState | undefined): string | null {
|
||||
return state?.checkout.state === 'ready' ? state.checkout.checkout.commit : null
|
||||
}
|
||||
|
||||
/** Wait for an inspection that starts after this call; the new commit gives it a state of its own to publish. */
|
||||
async function inspectedAgain(repo: string, opened: Bench, follower: Follower, turn: number): Promise<void> {
|
||||
const before = commitOf(follower.states.at(-1))
|
||||
await git(repo, 'commit', '--allow-empty', '-m', `turn ${turn}`)
|
||||
shellTurn(opened.session, turn, [{ callId: `list-${turn}`, command: 'ls', output: '' }])
|
||||
await follower.next(state => commitOf(state) !== null && commitOf(state) !== before)
|
||||
}
|
||||
|
||||
describe('forge panel that starts again', () => {
|
||||
it('publishes the state the last panel kept first, and neither probes sign-in nor looks the branch up again', async () => {
|
||||
const repo = await tracking()
|
||||
const opened = await open(repo)
|
||||
opened.provider.heads.set('feat', [7])
|
||||
const first = reader(opened)
|
||||
const left = await first.until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
await first.stop()
|
||||
const fetched = opened.provider.fetches.length
|
||||
|
||||
const second = reader(opened)
|
||||
const resumed = await second.until(() => true)
|
||||
|
||||
// The registry kept no status once the last watcher left; the card shows the snapshot the panel kept.
|
||||
expect(resumed).toMatchObject({
|
||||
directory: repo, checkout: left.checkout, repository: demo, readiness: READY,
|
||||
changeRequests: [{ url: pullUrl(7), origin: 'discovered', update: null, snapshot: snapshot(seven) }],
|
||||
})
|
||||
await second.until(state => state.changeRequests[0]?.update != null)
|
||||
expect(opened.provider.fetches).toHaveLength(fetched + 1)
|
||||
// The first inspection of the new panel has ended once a later one publishes.
|
||||
await inspectedAgain(repo, opened, second, 1)
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
expect(opened.provider.lookups).toEqual(['octo/demo feat'])
|
||||
})
|
||||
|
||||
it('probes sign-in again when the last panel found the host signed out', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
opened.provider.readinessImpl = () => Promise.resolve(SIGNED_OUT)
|
||||
const first = reader(opened)
|
||||
await first.until(state => state.readiness?.state === 'unauthenticated')
|
||||
await first.stop()
|
||||
opened.provider.readinessImpl = () => Promise.resolve(READY)
|
||||
|
||||
const second = reader(opened)
|
||||
|
||||
expect((await second.until(() => true)).readiness).toEqual(SIGNED_OUT)
|
||||
await second.until(state => state.readiness?.state === 'ready')
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
})
|
||||
|
||||
it('probes sign-in again when the probe of the last panel had not answered', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const held = Promise.withResolvers<ForgeReadiness>()
|
||||
opened.provider.readinessImpl = () => held.promise
|
||||
const first = reader(opened)
|
||||
await first.until(state => state.repository !== null)
|
||||
await first.stop()
|
||||
opened.provider.readinessImpl = () => Promise.resolve(READY)
|
||||
|
||||
const second = reader(opened)
|
||||
|
||||
expect(await second.until(() => true)).toMatchObject({ repository: demo, readiness: null })
|
||||
await second.until(state => state.readiness?.state === 'ready')
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
held.resolve(SIGNED_OUT)
|
||||
})
|
||||
|
||||
it('starts without the kept state when the Session has moved to another directory', async () => {
|
||||
const { root, repo } = await project()
|
||||
const outside = join(root, 'plain')
|
||||
await mkdir(outside)
|
||||
const opened = await open(repo)
|
||||
const first = reader(opened)
|
||||
await first.until(ready)
|
||||
await first.stop()
|
||||
await opened.ctx.workingDirectory.set(opened.agent, outside)
|
||||
|
||||
const second = reader(opened)
|
||||
|
||||
expect(await second.until(() => true)).toMatchObject({ directory: outside, checkout: { state: 'pending' }, repository: null, readiness: null })
|
||||
await second.until(state => state.checkout.state === 'none')
|
||||
})
|
||||
|
||||
it('looks the upstream branch up again while the Session shows no change request', async () => {
|
||||
const repo = await tracking()
|
||||
const opened = await open(repo)
|
||||
const first = reader(opened)
|
||||
await first.until(ready)
|
||||
await vi.waitFor(() => { expect(opened.provider.lookups).toEqual(['octo/demo feat']) })
|
||||
await first.stop()
|
||||
opened.provider.heads.set('feat', [7])
|
||||
|
||||
const second = reader(opened)
|
||||
|
||||
await second.until(state => polled(state, pullUrl(7)))
|
||||
expect(opened.provider.lookups).toEqual(['octo/demo feat', 'octo/demo feat'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('forge panel revisit', () => {
|
||||
it.each([
|
||||
['polls a change request whose latest poll is older than statusMaxAgeMs', { statusMaxAgeMs: 1 }, 1],
|
||||
['leaves a change request whose latest poll is younger than statusMaxAgeMs', {}, 0],
|
||||
])('reinspects the checkout and %s, without a sign-in probe or a branch lookup', async (_, config, reads) => {
|
||||
const repo = await tracking()
|
||||
const opened = await open(repo, config)
|
||||
opened.provider.heads.set('feat', [7])
|
||||
const follower = reader(opened)
|
||||
const before = await follower.until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
const fetched = opened.provider.fetches.length
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
await git(repo, 'commit', '--allow-empty', '-m', 'again')
|
||||
|
||||
await opened.ctx.forgePanel.revisit(opened.session.id, signal)
|
||||
// A revisit names its Session by id and leaves the panels of other Sessions alone.
|
||||
await opened.ctx.forgePanel.revisit(brandString<SessionId>('session-unfollowed'), signal)
|
||||
|
||||
// The revisit ended with its inspection, which found the new commit.
|
||||
await follower.next(state => commitOf(state) !== null && commitOf(state) !== commitOf(before))
|
||||
expect(opened.provider.fetches).toHaveLength(fetched + reads)
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
expect(opened.provider.lookups).toEqual(['octo/demo feat'])
|
||||
})
|
||||
|
||||
it('probes sign-in again while the host is not ready, and not while a probe has not answered', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const held = Promise.withResolvers<ForgeReadiness>()
|
||||
opened.provider.readinessImpl = () => held.promise
|
||||
const follower = reader(opened)
|
||||
await follower.until(state => state.repository !== null)
|
||||
|
||||
await opened.ctx.forgePanel.revisit(opened.session.id, signal)
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
|
||||
held.resolve(SIGNED_OUT)
|
||||
await follower.until(state => state.readiness?.state === 'unauthenticated')
|
||||
opened.provider.readinessImpl = () => Promise.resolve(READY)
|
||||
await opened.ctx.forgePanel.revisit(opened.session.id, signal)
|
||||
|
||||
await follower.until(state => state.readiness?.state === 'ready')
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
})
|
||||
|
||||
it('looks the upstream branch up again while the Session shows no change request', async () => {
|
||||
const repo = await tracking()
|
||||
const opened = await open(repo)
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await vi.waitFor(() => { expect(opened.provider.lookups).toEqual(['octo/demo feat']) })
|
||||
opened.provider.heads.set('feat', [7])
|
||||
|
||||
await opened.ctx.forgePanel.revisit(opened.session.id, signal)
|
||||
|
||||
await follower.until(state => polled(state, pullUrl(7)))
|
||||
expect(opened.provider.lookups).toEqual(['octo/demo feat', 'octo/demo feat'])
|
||||
})
|
||||
|
||||
it('polls no change request that no provider serves', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${UNSERVED}\n` }])
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
|
||||
await opened.ctx.forgePanel.revisit(opened.session.id, signal)
|
||||
|
||||
expect(follower.states.at(-1)?.changeRequests).toMatchObject([{ url: UNSERVED, ref: null }])
|
||||
expect(opened.provider.fetches).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a cancelled request', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
|
||||
await expect(opened.ctx.forgePanel.revisit(opened.session.id, AbortSignal.abort(new Error('cancelled')))).rejects.toThrow('cancelled')
|
||||
})
|
||||
})
|
||||
|
||||
describe('forge panel sign-in after a refused status read', () => {
|
||||
it('probes sign-in again when a status read on the host shown as ready is refused as unauthenticated', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
// The binding reaches the panel before its first poll, and an unserved one never has a reference.
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n${UNSERVED}\n` }])
|
||||
await follower.until(state => polled(state, pullUrl(7)))
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
|
||||
opened.provider.failures.set(7, { code: 'unauthenticated', message: 'gh auth login' })
|
||||
opened.provider.readinessImpl = () => Promise.resolve(SIGNED_OUT)
|
||||
opened.ctx.forge.refresh(seven)
|
||||
|
||||
await follower.until(state => failing(state, pullUrl(7)) && state.readiness === null)
|
||||
await follower.until(state => state.readiness?.state === 'unauthenticated')
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
|
||||
// A further refused read finds the host no longer shown as ready.
|
||||
opened.ctx.forge.refresh(seven)
|
||||
await follower.next(state => failing(state, pullUrl(7)))
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
})
|
||||
|
||||
it('probes sign-in once while refused status reads follow one another, and again after a status read succeeded', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
const follower = reader(opened)
|
||||
await follower.until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
const refusedOnce = async (): Promise<void> => {
|
||||
opened.provider.failures.set(7, { code: 'unauthenticated', message: 'gh auth login' })
|
||||
opened.ctx.forge.refresh(seven)
|
||||
await follower.next(state => failing(state, pullUrl(7)))
|
||||
}
|
||||
|
||||
// The probe keeps answering that the host is ready, as for a token that lacks access to one repository.
|
||||
await refusedOnce()
|
||||
await follower.until(state => failing(state, pullUrl(7)) && state.readiness?.state === 'ready')
|
||||
await refusedOnce()
|
||||
expect(opened.provider.probes).toEqual(['fake.test', 'fake.test'])
|
||||
|
||||
opened.provider.failures.delete(7)
|
||||
opened.ctx.forge.refresh(seven)
|
||||
await follower.next(state => !failing(state, pullUrl(7)))
|
||||
await refusedOnce()
|
||||
await vi.waitFor(() => { expect(opened.provider.probes).toEqual(['fake.test', 'fake.test', 'fake.test']) })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['is refused for another reason', 'https://fake.test/octo/demo.git', { code: 'not-found', message: 'gone' }, 'fake.test'],
|
||||
['is refused as unauthenticated on another host', 'https://other.test/octo/demo.git', { code: 'unauthenticated', message: 'gh auth login' }, 'other.test'],
|
||||
] as const)('leaves sign-in alone when a status read %s', async (_, remote, failure, host) => {
|
||||
const { repo } = await project(remote)
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
const follower = reader(opened)
|
||||
await follower.until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
|
||||
opened.provider.failures.set(7, failure)
|
||||
opened.ctx.forge.refresh(seven)
|
||||
|
||||
const refused = await follower.until(state => failing(state, pullUrl(7)))
|
||||
expect(refused.readiness).toEqual(READY)
|
||||
expect(opened.provider.probes).toEqual([host])
|
||||
})
|
||||
})
|
||||
@@ -58,6 +58,37 @@ describe('ReviewCache', () => {
|
||||
expect(cache.get(c, 'v1', 0)).toEqual(review('w'))
|
||||
})
|
||||
|
||||
it('amends a read kept at the version of a write, keeping its age, and forgets one kept at another version', () => {
|
||||
const cache = new ReviewCache<ForgeReviewData>(size * 4, 100)
|
||||
const truncated = (read: ForgeReviewData): ForgeReviewData => ({ ...read, truncated: true })
|
||||
cache.set(a, 'v1', review('x'), 1_000, cache.token())
|
||||
cache.set(b, 'v1', review('y'), 1_000, cache.token())
|
||||
|
||||
cache.amend(a, 'v1', truncated)
|
||||
cache.amend(b, 'v2', truncated)
|
||||
cache.amend(c, 'v1', truncated)
|
||||
|
||||
expect(cache.get(a, 'v1', 1_099)).toEqual({ ...review('x'), truncated: true })
|
||||
expect(cache.get(a, 'v1', 1_100)).toBeUndefined()
|
||||
expect(cache.get(b, 'v1', 1_050)).toBeUndefined()
|
||||
expect(cache.get(c, 'v1', 1_050)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps no read that started before an amendment, and no amended read larger than the byte limit', () => {
|
||||
const cache = new ReviewCache<ForgeReviewData>(size, 100)
|
||||
const early = cache.token()
|
||||
cache.set(a, 'v1', review('x'), 0, early)
|
||||
cache.amend(b, 'v1', read => read)
|
||||
cache.set(b, 'v1', review('y'), 0, early)
|
||||
expect(cache.get(b, 'v1', 0)).toBeUndefined()
|
||||
expect(cache.get(a, 'v1', 0)).toEqual(review('x'))
|
||||
|
||||
cache.amend(a, 'v1', () => review('longer'))
|
||||
expect(cache.get(a, 'v1', 0)).toBeUndefined()
|
||||
cache.set(b, 'v1', review('y'), 0, cache.token())
|
||||
expect(cache.get(b, 'v1', 0)).toEqual(review('y'))
|
||||
})
|
||||
|
||||
it('keeps no read larger than the byte limit and forgets the read it replaced', () => {
|
||||
const cache = new ReviewCache(size, 100)
|
||||
cache.set(a, 'v1', review('x'), 0, cache.token())
|
||||
|
||||
@@ -217,6 +217,20 @@ describe('forgePanel.reviewChangeRequest', () => {
|
||||
expect(opened.ctx.forge.latest(ref(7))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads a change request at once for a stream that starts once its latest status is older than statusMaxAgeMs', async () => {
|
||||
const opened = await page({ statusMaxAgeMs: 1 })
|
||||
const first = changeRequest(opened, pullUrl(7))
|
||||
await first.until(polled)
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
|
||||
// The stream watches the change request once its first frame is pulled.
|
||||
const joined = changeRequest(opened, pullUrl(7))
|
||||
await joined.pull()
|
||||
|
||||
await vi.waitFor(() => { expect(opened.provider.fetches).toEqual([[7], [7]]) })
|
||||
await Promise.all([first.stop(), joined.stop()])
|
||||
})
|
||||
|
||||
it('names how the change request\'s provider calls itself, and nothing once that provider left', async () => {
|
||||
const opened = await page()
|
||||
const { registration } = await registerViewer(opened)
|
||||
@@ -284,14 +298,17 @@ describe('forgePanel review page reads', () => {
|
||||
await expect(panel.reviewText(url, HEAD, 'src/a.ts', signal)).resolves.toBe('new\n')
|
||||
await expect(panel.reviewText(url, HEAD, 'big.bin', signal)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' })
|
||||
|
||||
await expect(panel.reviewViewed(url, HEAD, signal)).resolves.toBeNull()
|
||||
await expect(panel.reviewViewed(url, HEAD, false, signal)).resolves.toBeNull()
|
||||
const marks = { headSha: HEAD, files: { 'src/a.ts': 'dismissed' as const }, truncated: false }
|
||||
const viewedFiles = vi.fn<NonNullable<ForgeProvider['viewedFiles']>>(() => Promise.resolve(marks))
|
||||
Object.assign(opened.provider, { viewedFiles, setViewed: () => Promise.resolve(undefined) })
|
||||
await expect(panel.reviewViewed(url, HEAD, signal)).resolves.toEqual(marks)
|
||||
await expect(panel.reviewViewed(url, HEAD, false, signal)).resolves.toEqual(marks)
|
||||
// The marks are kept for the next read that is not fresh.
|
||||
await expect(panel.reviewViewed(url, HEAD, false, signal)).resolves.toEqual(marks)
|
||||
expect(viewedFiles).toHaveBeenCalledOnce()
|
||||
viewedFiles.mockResolvedValueOnce({ code: 'stale', message: 'moved' }).mockResolvedValueOnce({ code: 'unavailable', message: 'down' })
|
||||
await expect(panel.reviewViewed(url, HEAD, signal)).rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'moved' })
|
||||
await expect(panel.reviewViewed(url, HEAD, signal)).rejects.toMatchObject({ code: 'forgePanel/viewed-failed', message: 'down' })
|
||||
await expect(panel.reviewViewed(url, HEAD, true, signal)).rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'moved' })
|
||||
await expect(panel.reviewViewed(url, HEAD, true, signal)).rejects.toMatchObject({ code: 'forgePanel/viewed-failed', message: 'down' })
|
||||
})
|
||||
|
||||
it('reads the files and review threads at the head of the streamed status, which a review page write refreshes', async () => {
|
||||
@@ -425,7 +442,7 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewDiff(UNSERVED, null, signal),
|
||||
() => panel.reviewCommits(UNSERVED, signal),
|
||||
() => panel.reviewText(UNSERVED, HEAD, 'src/a.ts', signal),
|
||||
() => panel.reviewViewed(UNSERVED, HEAD, signal),
|
||||
() => panel.reviewViewed(UNSERVED, HEAD, false, signal),
|
||||
() => panel.reviewSetViewed(UNSERVED, { path: 'src/a.ts', viewed: true, headSha: HEAD }, signal),
|
||||
() => panel.reviewMarkReady(UNSERVED, signal),
|
||||
() => panel.reviewMerge(UNSERVED, 'merge', HEAD, signal),
|
||||
@@ -460,7 +477,7 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewDiff(url, null, aborted),
|
||||
() => panel.reviewCommits(url, aborted),
|
||||
() => panel.reviewText(url, HEAD, 'src/a.ts', aborted),
|
||||
() => panel.reviewViewed(url, HEAD, aborted),
|
||||
() => panel.reviewViewed(url, HEAD, false, aborted),
|
||||
() => panel.reviewMarkReady(url, aborted),
|
||||
() => panel.reviewStage(opened.session.id, url, aborted),
|
||||
]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createNoticeSource, createPanelSource, createStreamSource, foldStates } from '../src/client/source.ts'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createNoticeSource, createPanelSource, createStreamSource, foldStates, HIDDEN_GRACE_MS } from '../src/client/source.ts'
|
||||
import type { PanelStream } from '../src/client/source.ts'
|
||||
import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgePanelState } from '../src/types.ts'
|
||||
import { entry, listState, ready, snapshot } from './client-fixtures.client.ts'
|
||||
@@ -207,6 +207,126 @@ describe('createPanelSource', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/** A page whose visibility the test sets by hand. */
|
||||
function page(hidden = false) {
|
||||
const listeners = new Set<() => void>()
|
||||
return {
|
||||
listeners,
|
||||
visibility: {
|
||||
hidden: () => hidden,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
},
|
||||
},
|
||||
set(next: boolean) {
|
||||
hidden = next
|
||||
for (const listener of [...listeners]) listener()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('a stream source that follows the page visibility', () => {
|
||||
beforeEach(() => { vi.useFakeTimers() })
|
||||
afterEach(() => { vi.useRealTimers() })
|
||||
|
||||
function pausing(tab = page()) {
|
||||
const streams: ReturnType<typeof feed>[] = []
|
||||
const resets = new Set<() => void>()
|
||||
const panel = createPanelSource({
|
||||
open: (signal): PanelStream => {
|
||||
const stream = feed()
|
||||
stream.signal = signal
|
||||
streams.push(stream)
|
||||
return stream
|
||||
},
|
||||
subscribeReset: (listener) => {
|
||||
resets.add(listener)
|
||||
return () => { resets.delete(listener) }
|
||||
},
|
||||
visibility: tab.visibility,
|
||||
})
|
||||
return { panel, streams, tab, reset: () => { for (const listener of [...resets]) listener() } }
|
||||
}
|
||||
|
||||
it('closes its stream once the page has been hidden for 30 seconds, keeps the value, and opens a stream when the page shows', async () => {
|
||||
const { panel, streams, tab } = pausing()
|
||||
const observable = panel.hooks.panel
|
||||
const seen: unknown[] = []
|
||||
const unsubscribe = observable.subscribe(() => { seen.push(observable.getSnapshot()) })
|
||||
streams[0]?.push(ready())
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
tab.set(true)
|
||||
await vi.advanceTimersByTimeAsync(HIDDEN_GRACE_MS - 1)
|
||||
// A second change while hidden does not start the period again.
|
||||
tab.set(true)
|
||||
expect(streams[0]?.disposed).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(streams[0]?.disposed).toHaveBeenCalled()
|
||||
expect(streams[0]?.signal?.aborted).toBe(true)
|
||||
expect(observable.getSnapshot()).toEqual({ state: ready(), disconnected: false })
|
||||
expect(seen).toEqual([{ state: ready(), disconnected: false }])
|
||||
|
||||
tab.set(false)
|
||||
expect(streams).toHaveLength(2)
|
||||
const later = ready({ changeRequests: [entry(1, snapshot(1))] })
|
||||
streams[1]?.push(later)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(observable.getSnapshot()).toEqual({ state: later, disconnected: false })
|
||||
unsubscribe()
|
||||
expect(tab.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps its stream when the page shows again within 30 seconds', async () => {
|
||||
const { panel, streams, tab } = pausing()
|
||||
const unsubscribe = panel.hooks.panel.subscribe(() => {})
|
||||
|
||||
tab.set(true)
|
||||
await vi.advanceTimersByTimeAsync(HIDDEN_GRACE_MS - 1)
|
||||
tab.set(false)
|
||||
await vi.advanceTimersByTimeAsync(HIDDEN_GRACE_MS)
|
||||
|
||||
expect(streams).toHaveLength(1)
|
||||
expect(streams[0]?.disposed).not.toHaveBeenCalled()
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('opens no stream after a transport reset while paused, and one on the new connection when the page shows', async () => {
|
||||
const { panel, streams, tab, reset } = pausing()
|
||||
const unsubscribe = panel.hooks.panel.subscribe(() => {})
|
||||
tab.set(true)
|
||||
await vi.advanceTimersByTimeAsync(HIDDEN_GRACE_MS)
|
||||
|
||||
reset()
|
||||
expect(streams).toHaveLength(1)
|
||||
tab.set(false)
|
||||
expect(streams).toHaveLength(2)
|
||||
reset()
|
||||
expect(streams).toHaveLength(3)
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('starts the period when its first subscriber arrives on a hidden page, and forgets it with the last subscriber', async () => {
|
||||
const { panel, streams } = pausing(page(true))
|
||||
const unsubscribe = panel.hooks.panel.subscribe(() => {})
|
||||
expect(streams).toHaveLength(1)
|
||||
expect(vi.getTimerCount()).toBe(1)
|
||||
|
||||
unsubscribe()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
|
||||
// A source that paused opens a stream for its next first subscriber.
|
||||
const again = panel.hooks.panel.subscribe(() => {})
|
||||
await vi.advanceTimersByTimeAsync(HIDDEN_GRACE_MS)
|
||||
expect(streams[1]?.disposed).toHaveBeenCalled()
|
||||
again()
|
||||
const third = panel.hooks.panel.subscribe(() => {})
|
||||
expect(streams).toHaveLength(3)
|
||||
third()
|
||||
})
|
||||
})
|
||||
|
||||
describe('change request states', () => {
|
||||
it('builds states from a baseline and its changes, and lets the baseline after a transport reset replace them', async () => {
|
||||
const streams: ReturnType<typeof feed<ForgeChangeRequestStatesFrame>>[] = []
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** The Host's last known state of every change request that a listed Session binds. */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestBriefListener, ChangeRequestRef, ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { ChangeRequestStates, storedKey, type ChangeRequestStateSources, type ListedSession, type StoredStates } from '../src/states.ts'
|
||||
import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame } from '../src/types.ts'
|
||||
@@ -44,7 +44,7 @@ function state(number: number, overrides: Partial<ForgeChangeRequestListState> =
|
||||
|
||||
/** Sources over fixed listed Sessions, stored states, and polls the test drives. */
|
||||
function fixture(sessions: readonly ListedSession[], stored: readonly ForgeChangeRequestListState[] = []) {
|
||||
const watchers = new Map<number, ChangeRequestListener>()
|
||||
const watchers = new Map<number, ChangeRequestBriefListener>()
|
||||
const listeners = new Set<(id: SessionId, urls: readonly string[]) => void>()
|
||||
const records = new Map(stored.map(value => [storedKey(value.url), value]))
|
||||
const put = vi.fn<StoredStates['put']>(async (key, value) => { records.set(key, value) })
|
||||
@@ -79,8 +79,12 @@ function fixture(sessions: readonly ListedSession[], stored: readonly ForgeChang
|
||||
remove,
|
||||
watchers,
|
||||
listeners,
|
||||
poll(number: number, overrides: Partial<ChangeRequestSnapshot> = {}): void {
|
||||
watchers.get(number)?.({ key: changeRequestKey(ref(number)), fetchedAt: 1, snapshot: snapshot(number, overrides) })
|
||||
poll(number: number, overrides: Partial<ChangeRequestSnapshot> = {}, fetchedAt = 1): void {
|
||||
watchers.get(number)?.({ key: changeRequestKey(ref(number)), fetchedAt, brief: snapshot(number, overrides) })
|
||||
},
|
||||
/** The state each `watch` call named as known, by pull request number, in call order. */
|
||||
known(): [number, unknown][] {
|
||||
return sources.watch.mock.calls.map(([target, , known]) => [target.number, known])
|
||||
},
|
||||
fail(number: number): void {
|
||||
watchers.get(number)?.({ key: changeRequestKey(ref(number)), fetchedAt: 1, failure: { code: 'unavailable', message: 'down' } })
|
||||
@@ -132,12 +136,49 @@ describe('ChangeRequestStates', () => {
|
||||
expect([...f.watchers.keys()]).toEqual([7, 8])
|
||||
})
|
||||
|
||||
it('watches stored merged and closed requests for fresh results', async () => {
|
||||
const f = fixture([{ id: S1, urls: [url(7), url(8)] }], [state(7, { state: 'merged' }), state(8, { state: 'closed' })])
|
||||
it('watches stored merged and closed requests, naming the state it holds as read at the epoch', async () => {
|
||||
const f = fixture([{ id: S1, urls: [url(7), url(8), url(9)] }], [
|
||||
state(7, { state: 'merged' }), state(8, { state: 'closed', mergeability: 'conflicting', checksRollup: 'failure' }),
|
||||
])
|
||||
const r = reader(f.hub)
|
||||
|
||||
expect(await r.next()).toEqual({ type: 'baseline', states: [state(7, { state: 'merged' }), state(8, { state: 'closed' })] })
|
||||
expect(f.sources.watch.mock.calls.map(([target]) => target.number)).toEqual([7, 8])
|
||||
expect(await r.next()).toMatchObject({ type: 'baseline' })
|
||||
expect(f.known()).toEqual([
|
||||
[7, { state: 'merged', mergeability: 'mergeable', checksRollup: 'success', fetchedAt: 0 }],
|
||||
[8, { state: 'closed', mergeability: 'conflicting', checksRollup: 'failure', fetchedAt: 0 }],
|
||||
[9, undefined],
|
||||
])
|
||||
})
|
||||
|
||||
it('names the read of an earlier run when a later run watches the same change request', async () => {
|
||||
const f = fixture([{ id: S1, urls: [url(7), url(8)] }])
|
||||
const first = reader(f.hub)
|
||||
await first.next()
|
||||
f.poll(7, { checksRollup: 'pending' }, 5_000)
|
||||
f.poll(7, { checksRollup: 'pending' }, 9_000)
|
||||
f.fail(8)
|
||||
await first.close()
|
||||
f.sources.watch.mockClear()
|
||||
|
||||
const second = reader(f.hub)
|
||||
expect(await second.next()).toEqual({ type: 'baseline', states: [state(7, { checksRollup: 'pending' })] })
|
||||
expect(f.known()).toEqual([[7, { state: 'open', mergeability: 'mergeable', checksRollup: 'pending', fetchedAt: 9_000 }], [8, undefined]])
|
||||
})
|
||||
|
||||
it('forgets the read of a change request that no listed Session binds any more', async () => {
|
||||
const f = fixture([{ id: S1, urls: [url(7)] }])
|
||||
const first = reader(f.hub)
|
||||
await first.next()
|
||||
f.poll(7, {}, 5_000)
|
||||
await first.close()
|
||||
|
||||
f.sources.sessions.mockResolvedValueOnce([{ id: S1, urls: [] }])
|
||||
const second = reader(f.hub)
|
||||
expect(await second.next()).toEqual({ type: 'baseline', states: [] })
|
||||
await vi.waitFor(() => { expect(f.records.size).toBe(0) })
|
||||
f.sources.watch.mockClear()
|
||||
f.bind(S1, [url(7)])
|
||||
expect(f.known()).toEqual([[7, undefined]])
|
||||
})
|
||||
|
||||
it('starts polling a change request when a Session binds it and stops once no Session binds it', async () => {
|
||||
|
||||
@@ -9,17 +9,17 @@
|
||||
en: 1c2533aa62dd459c
|
||||
zh: 3d26837df2bbf525
|
||||
/deepseek-ai-dsh-experimental-forge-github/summary:
|
||||
en: c64194798b228b23
|
||||
zh: 5b1a145621f0c90a
|
||||
en: b57b4a4e780ea0a3
|
||||
zh: 6c3746c3fbdf2aee
|
||||
/deepseek-ai-dsh-experimental-forge-github/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge-github/use-this-package:
|
||||
en: b916d3e2bd0cce2d
|
||||
zh: 943e6caad6972b0f
|
||||
en: 16acf338dc8ff67f
|
||||
zh: 1a70559dc1892545
|
||||
/deepseek-ai-dsh-experimental-forge-github/understand-the-implementation:
|
||||
en: b3407071292d7d98
|
||||
zh: dfe8f077cd041909
|
||||
en: ed8edec5c90cc1eb
|
||||
zh: e3a5b74f75dfc17d
|
||||
/deepseek-ai-dsh-experimental-forge-github/further-exploration:
|
||||
en: d377d5fd9d9f190e
|
||||
zh: 920bcbfdb8c993f2
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 26b946af4b742e17
|
||||
zh: 00b34f0721ac72f6
|
||||
/deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work:
|
||||
en: 39310eb6ef6b8035
|
||||
zh: 9b57c9f504e71f96
|
||||
en: aa6f410a7f265d2f
|
||||
zh: ecd80b54fd5c0a59
|
||||
/deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Read GitHub and GitHub Enterprise pull requests for `ctx.forge` with the GitHub CLI that is already signed in on the host. Each poll batches pull requests by host to read state, changed lines, checks, review decision, mergeability, and unresolved review threads for every due pull request.
|
||||
Read GitHub and GitHub Enterprise pull requests for `ctx.forge` with the GitHub CLI that is already signed in on the host. Each snapshot poll batches pull requests by host to read state, changed lines, checks, review decision, mergeability, and unresolved review threads for every due pull request. A brief poll reads only the title, state, draft flag, mergeability, review decision, and combined check state.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -34,7 +34,7 @@ Mount the provider after the forge registry and list every GitHub Enterprise hos
|
||||
hosts: [github.com, ghe.example.com]
|
||||
```
|
||||
|
||||
The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname <host>`. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes`, `maxReviewThreads`, `maxCommits`, `maxViewedFiles`, and `maxViewerItems` must be positive safe integers, and `maxViewerItems` at most 100; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, `maxReviewThreads`, `maxCommits`, `maxViewedFiles`, and `maxViewerItems` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github).
|
||||
The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname <host>`. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes`, `maxReviewThreads`, `snapshotBatchSize`, `briefBatchSize`, `maxCommits`, `maxViewedFiles`, and `maxViewerItems` must be positive safe integers, and `maxViewerItems` at most 100; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, `maxReviewThreads`, `snapshotBatchSize`, `briefBatchSize`, `maxCommits`, `maxViewedFiles`, and `maxViewerItems` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github).
|
||||
|
||||
While [forge-session](../forge-session/README.md) runs, the plugin registers the `gh` command rule with it. `gh pr create` and `gh pr new` bind the pull requests they print. `gh pr view`, `gh pr edit`, and `gh pr checkout` bind the pull request that a URL selects, or a number with `--repo`, `--repo=`, or `-R` before or after it; a repository that contains its host, or a literal `GH_HOST` assignment, supplies the URL directly, and any other repository resolves through `gh pr view <number> --repo <repository> --json url --jq .url` in the call's shell. `gh api` binds the pull request its REST path names, such as `repos/octo/demo/pulls/7/files`: directly when `--hostname` or a literal `GH_HOST` assignment names the host, else through the same `gh pr view` lookup, without `--repo` for the `{owner}/{repo}` placeholders.
|
||||
|
||||
@@ -42,7 +42,9 @@ The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in
|
||||
|
||||
Polling returns the first 100 head-commit check contexts without following pages. An incomplete preview sets `checksTruncated` and keeps GitHub’s aggregate state; its counts do not describe the full list. `fetchChecks(ref, signal)` reads complete details only for the requested PR, pinning continuation pages to the first response’s rollup. The combined UTF-8 JSON responses, review thread pages included, must fit `maxOutputBytes`; excess returns `too-large`. Failed or non-advancing pages fail only this detail read and leave polling results intact. Runs with the same application, workflow, event, and check name keep only the newest run id; a queued replacement supersedes an older completed run. Runs without a numeric database id are retained by node id because their relative age is unknown. Commit status contexts keep the newest result per context name. Complete lists derive their indicator from these results; unknown context kinds retain GitHub’s aggregate state.
|
||||
|
||||
Every status read counts review threads in pages of up to 100 until it has counted `maxReviewThreads` (default 1,000) of them; each page after the first is one more GraphQL query. A pull request with more threads sets `threadsTruncated`, and its `unresolvedThreads` counts only the threads read. A thread page that fails or does not advance fails that pull request's status read and leaves the other pull requests of the batch intact; a partial count is not published.
|
||||
A snapshot read puts at most `snapshotBatchSize` (default 8) pull requests of one host in one GraphQL query, and `fetchBriefs` at most `briefBatchSize` (default 25). The provider names both sizes to the forge registry, which polls that many pull requests of a host per call, so each query of a poll has the registry's `fetchTimeoutMs` deadline to itself and its results are published when it is answered. A read that names more pull requests of a host sends its queries one after another; a snapshot query is followed by its review thread pages before the next query. A brief query reads `url`, `title`, `state`, `isDraft`, `mergeable`, `reviewDecision`, and the `statusCheckRollup.state` of the head commit, without the check list, reviewers, review threads, or the repository's merge settings. The combined check outcome of a brief is that `statusCheckRollup.state`; a snapshot with a complete check list derives its outcome from the checks it keeps instead. A query whose `gh` run cannot start, outlives `timeoutMs`, or prints over `maxOutputBytes`, and one GitHub refuses, fails only its own pull requests, as does a GraphQL error without a path in its response. Once the read is cancelled, it sends no further query.
|
||||
|
||||
Every snapshot read counts review threads in pages of up to 100 until it has counted `maxReviewThreads` (default 1,000) of them; each page after the first is one more GraphQL query. A pull request with more threads sets `threadsTruncated`, and its `unresolvedThreads` counts only the threads read. A thread page that fails or does not advance fails that pull request's status read and leaves the other pull requests of the batch intact; a partial count is not published.
|
||||
|
||||
Unfinished check runs and completed runs with stale, missing, or unrecognized conclusions map to `pending`. Other completed checks map to `success`, `failure` (failure, timed out, startup failure, or action required), `cancelled`, `skipped`, or `neutral`. Cancelled checks keep the rollup non-passing. Check runs keep their start and completion times. Commit status contexts map `SUCCESS` to `success`, `FAILURE` and `ERROR` to `failure`, and every other state to `pending`, and carry no times. A GraphQL `NOT_FOUND` error becomes a `not-found` failure. A response without GraphQL data or errors, including an HTTP error JSON body, uses the first stderr diagnostic or the body's message. Authentication diagnostics become `unauthenticated`; oversized check pages become `too-large`; a GraphQL `RATE_LIMITED` error or a diagnostic that names a rate limit becomes `rate-limited`; other failures become `unavailable`. Head lookups preserve the same diagnostic in their rejection.
|
||||
|
||||
@@ -72,7 +74,7 @@ Every status read also reads the overview of each pull request: up to 25 review
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
A fetch groups references by host and sends one initial `gh api graphql` query per host. Continuation queries use the original rollup node id, so a changed pull request head cannot mix commits within one check list. The query inlines validated owner, name, and number values and gives each pull request an alias, so partial GraphQL errors fail only their own aliases. `gh` exits nonzero on partial errors but still prints the complete response, which the provider parses before it inspects the exit code.
|
||||
A snapshot fetch and a brief read each group references by host, build a `gh api graphql` query for every `snapshotBatchSize` or `briefBatchSize` of them before the first request, and send the queries in turn. Continuation queries use the original rollup node id, so a changed pull request head cannot mix commits within one check list. The query inlines validated owner, name, and number values and gives each pull request an alias, so partial GraphQL errors fail only their own aliases. `gh` exits nonzero on partial errors but still prints the complete response, which the provider parses before it inspects the exit code.
|
||||
|
||||
| Source | Responsibility |
|
||||
|---|---|
|
||||
@@ -118,10 +120,11 @@ None. Provider output reaches only host-side watchers.
|
||||
|
||||
- **GitHub CLI on the host** — `gh` must be installed and signed in for each configured host; tokens in environment variables are not forwarded. Hosts missing from `hosts` are never read, including references retained across configuration changes. A status fetch returns `unavailable` for those references; a head lookup rejects before starting `gh`.
|
||||
- **Review thread bound** — a status read counts, and a review read reads, at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks, and a review read is `truncated`.
|
||||
- **Batch deadline** — continuation pages of a pull request with many review threads lengthen its host's polling batch; a batch that outlives `ctx.forge`'s `fetchTimeoutMs` reports `unavailable` for every pull request in it, not only for the one with many threads.
|
||||
- **Call deadline** — one snapshot query and the continuation pages of its pull requests run within one `fetchTimeoutMs` deadline of `ctx.forge`; a pull request with many review threads can make its query outlive it, which reports `unavailable` for the up to `snapshotBatchSize` pull requests of that query, not only for the one with many threads.
|
||||
- **Brief check outcome** — a brief reports GitHub's combined check state, while a snapshot with a complete check list derives its own; nothing reconciles the two when they differ for one pull request.
|
||||
- **Rewritten base branch** — the diff starts from the merge base of the head and the base commit GitHub recorded at the pull request's last update. After the base branch is force-pushed, that merge base can differ from the one GitHub's pull request view uses, so the patch can include or omit commits until the pull request is updated.
|
||||
- **No fork discovery** — head lookups exclude pull requests whose head is in another repository.
|
||||
- **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request, and a second REST request when the base commit changed after the latest status. All count against the signed-in account’s rate limit. A review read costs one GraphQL query per page of 100 threads and one more per further page of 100 comments in a thread. A review write costs one GraphQL query for the head check and one mutation, or two for a pending reply that starts the pending review.
|
||||
- **Rate limits** — every brief poll costs one GraphQL query per `briefBatchSize` pull requests of a host; every snapshot poll costs one per `snapshotBatchSize` pull requests of a host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request, and a second REST request when the base commit changed after the latest status. All count against the signed-in account’s rate limit. A review read costs one GraphQL query per page of 100 threads and one more per further page of 100 comments in a thread. A review write costs one GraphQL query for the head check and one mutation, or two for a pending reply that starts the pending review.
|
||||
- **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
借助宿主上已登录的 GitHub CLI,为 `ctx.forge` 读取 GitHub 与 GitHub Enterprise 的 pull request。每次轮询按主机批量查询,读取所有到期 pull request 的状态、改动行数、检查、评审结论、可合并性与未解决的评审讨论。
|
||||
借助宿主上已登录的 GitHub CLI,为 `ctx.forge` 读取 GitHub 与 GitHub Enterprise 的 pull request。每次快照轮询按主机批量查询,读取所有到期 pull request 的状态、改动行数、检查、评审结论、可合并性与未解决的评审讨论。简报轮询只读取标题、状态、草稿标记、可合并性、评审结论与检查汇总状态。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -34,7 +34,7 @@ kind: "package-reference"
|
||||
hosts: [github.com, ghe.example.com]
|
||||
```
|
||||
|
||||
即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname <host>` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes`、`maxReviewThreads`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 必须是正安全整数,`maxViewerItems` 最大为 100;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。
|
||||
即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname <host>` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes`、`maxReviewThreads`、`snapshotBatchSize`、`briefBatchSize`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 必须是正安全整数,`maxViewerItems` 最大为 100;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads`、`snapshotBatchSize`、`briefBatchSize`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。
|
||||
|
||||
[forge-session](../forge-session/README.zh.md) 运行期间,插件向其注册 `gh` 命令规则。`gh pr create` 与 `gh pr new` 绑定它们打印的 pull request。`gh pr view`、`gh pr edit` 与 `gh pr checkout` 绑定 URL 选中的 pull request,或前后带有 `--repo`、`--repo=` 或 `-R` 的编号所选中的 pull request;包含主机的仓库参数或字面量 `GH_HOST` 赋值可直接确定 URL,其他仓库参数则在调用所在的 shell 中通过 `gh pr view <number> --repo <repository> --json url --jq .url` 解析。`gh api` 绑定其 REST 路径指向的 pull request,例如 `repos/octo/demo/pulls/7/files`:`--hostname` 或字面量 `GH_HOST` 赋值写明主机时直接绑定,否则通过同样的 `gh pr view` 查询解析,`{owner}/{repo}` 占位符则不带 `--repo`。
|
||||
|
||||
@@ -42,7 +42,9 @@ kind: "package-reference"
|
||||
|
||||
轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应(包括评审讨论分页)的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。
|
||||
|
||||
每次状态读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响;不发布不完整的计数。
|
||||
快照读取把同一主机最多 `snapshotBatchSize`(默认 8)个 pull request 放进一个 GraphQL 查询,`fetchBriefs` 则最多放 `briefBatchSize`(默认 25)个。提供方把这两个大小告知 forge 注册表,注册表每次调用轮询同一主机的这么多个 pull request,所以一次轮询的每个查询独占注册表的 `fetchTimeoutMs` 时限,查询得到应答后它的结果就会发布。一次读取指定了同一主机更多的 pull request 时,依次发送各个查询;快照查询读完自己的评审讨论分页后,才发送下一个查询。简报查询读取 `url`、`title`、`state`、`isDraft`、`mergeable`、`reviewDecision` 以及 head 提交的 `statusCheckRollup.state`,不读取检查列表、评审人、评审讨论和仓库的合并设置。简报的检查汇总结果就是这个 `statusCheckRollup.state`;检查列表完整的快照则根据自己保留的检查得出结果。某个查询的 `gh` 无法启动、超过 `timeoutMs` 或输出超过 `maxOutputBytes`,或被 GitHub 拒绝时,只有该查询内的 pull request 失败;响应中不带路径的 GraphQL 错误也只影响该查询内的 pull request。读取被取消后不再发送后续查询。
|
||||
|
||||
每次快照读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响;不发布不完整的计数。
|
||||
|
||||
未完成的检查运行(check run),以及结论已过期、缺失或无法识别的已完成运行,均映射为 `pending`。其他已完成的检查映射为 `success`、`failure`(失败、超时、启动失败或需要操作)、`cancelled`、`skipped` 或 `neutral`。已取消的检查使汇总保持未通过状态。检查运行保留其开始与完成时间。提交状态上下文把 `SUCCESS` 映射为 `success`,把 `FAILURE` 与 `ERROR` 映射为 `failure`,其余状态均映射为 `pending`,且不带时间。GraphQL 的 `NOT_FOUND` 错误转为 `not-found` 失败。响应不含 GraphQL data 或 errors 时(包括 HTTP 错误 JSON),使用 stderr 的首条诊断或响应体的 message。认证诊断转为 `unauthenticated`;超出输出大小上限的检查分页转为 `too-large`;GraphQL 的 `RATE_LIMITED` 错误或提到限流的诊断转为 `rate-limited`;其他失败转为 `unavailable`。head 查找在拒绝时保留相同诊断。
|
||||
|
||||
@@ -72,7 +74,7 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
一次读取按主机对引用分组,每个主机先发送一个 `gh api graphql` 查询。后续分页使用原汇总节点 id,因此 PR 的 head 变化不会让同一检查列表混入其他提交。查询内联经过校验的 owner、name 与编号,并为每个 pull request 设置别名,因此局部 GraphQL 错误只影响对应的别名。出现局部错误时 `gh` 以非零状态退出,但仍会输出完整响应;提供方先解析该响应,再检查退出码。
|
||||
快照读取与简报读取都按主机对引用分组,在第一次请求前为每 `snapshotBatchSize` 或 `briefBatchSize` 个引用构造一个 `gh api graphql` 查询,再依次发送。后续分页使用原汇总节点 id,因此 PR 的 head 变化不会让同一检查列表混入其他提交。查询内联经过校验的 owner、name 与编号,并为每个 pull request 设置别名,因此局部 GraphQL 错误只影响对应的别名。出现局部错误时 `gh` 以非零状态退出,但仍会输出完整响应;提供方先解析该响应,再检查退出码。
|
||||
|
||||
| 源码 | 职责 |
|
||||
|---|---|
|
||||
@@ -118,10 +120,11 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
|
||||
- **宿主需要 GitHub CLI**——必须安装 `gh` 并为每个已配置主机登录;环境变量中的令牌不会被转发。不在 `hosts` 中的主机永远不会被读取,包括配置变更后保留的引用。状态读取为这些引用返回 `unavailable`;head 查找会在启动 `gh` 前拒绝。
|
||||
- **评审讨论上限**——每次状态读取每个 pull request 最多统计、每次评审读取最多读取 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出,评审读取的结果标记为 `truncated`。
|
||||
- **批次时限**——评审讨论很多的 pull request 的续页会拉长其主机的轮询批次;批次超过 `ctx.forge` 的 `fetchTimeoutMs` 时,批次内每个 pull request 都报告 `unavailable`,而不只是讨论很多的那个。
|
||||
- **调用时限**——一个快照查询和它的 pull request 的续页,在 `ctx.forge` 的同一个 `fetchTimeoutMs` 时限内运行;评审讨论很多的 pull request 可能让它所在的查询超过该时限,这时该查询里最多 `snapshotBatchSize` 个 pull request 都报告 `unavailable`,而不只是讨论很多的那个。
|
||||
- **简报的检查结果**——简报报告 GitHub 的检查汇总状态,检查列表完整的快照则自行得出结果;同一个 pull request 的两个结果不一致时,没有机制去对齐它们。
|
||||
- **基准分支被改写**——diff 从 head 与 GitHub 在 pull request 最后一次更新时记录的基准提交的合并基准开始。基准分支被强制推送后,该合并基准可能不同于 GitHub pull request 页面使用的合并基准,因此在 pull request 更新前,补丁可能多出或缺少提交。
|
||||
- **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。
|
||||
- **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求;最新状态之后基准提交有变化时再多一次 REST 请求。这些都计入已登录账号的速率配额。每次评审读取每页 100 个讨论消耗一次 GraphQL 查询,单个讨论的评论每多一页(100 条)再消耗一次。每次评审写入消耗一次用于检查 head 的 GraphQL 查询和一个 mutation;开始待提交评审的待提交回复需要两个 mutation。
|
||||
- **速率限制**——每次简报轮询为每个主机的每 `briefBatchSize` 个 pull request 消耗一次 GraphQL 查询;每次快照轮询为每个主机的每 `snapshotBatchSize` 个 pull request 消耗一次,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求;最新状态之后基准提交有变化时再多一次 REST 请求。这些都计入已登录账号的速率配额。每次评审读取每页 100 个讨论消耗一次 GraphQL 查询,单个讨论的评论每多一页(100 条)再消耗一次。每次评审写入消耗一次用于检查 head 的 GraphQL 查询和一个 mutation;开始待提交评审的待提交回复需要两个 mutation。
|
||||
- **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, CheckState, ChecksRollup,
|
||||
ChangeRequestBrief, ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, CheckState,
|
||||
ChecksRollup,
|
||||
ForgeCheckId, ForgeFailure, ForgeRepository, Mergeability, MergeMethod, ReviewDecision, ReviewVerdict,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
@@ -63,6 +64,9 @@ export const THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
|
||||
|
||||
const REPOSITORY_FIELDS = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod'
|
||||
|
||||
/** Fields of one pull request's brief: its own scalars and the combined state of the head commit's checks, without the check list. */
|
||||
const BRIEF_FIELDS = 'url title state isDraft mergeable reviewDecision commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }'
|
||||
|
||||
/** Head-branch lookup; variables `owner`, `name`, and `branch` are passed as strings. */
|
||||
export const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: String!) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
@@ -245,6 +249,16 @@ const pullRequestCommitsSchema = z.object({ data: z.object({ repository: z.objec
|
||||
baseRefOid: z.string().refine(isCommit),
|
||||
}) }) }) })
|
||||
|
||||
const briefSchema = z.object({
|
||||
url: z.string(),
|
||||
title: z.string(),
|
||||
state: z.enum(['OPEN', 'CLOSED', 'MERGED']),
|
||||
isDraft: z.boolean(),
|
||||
mergeable: z.string(),
|
||||
reviewDecision: z.string().nullable(),
|
||||
commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ state: z.string() }).nullable() }) })) }),
|
||||
})
|
||||
|
||||
type PullRequestNode = z.infer<typeof pullRequestSchema>
|
||||
type RepositoryNode = z.infer<typeof repositorySchema>
|
||||
|
||||
@@ -273,25 +287,30 @@ const METHODS: readonly {
|
||||
{ method: 'rebase', allowed: 'rebaseMergeAllowed', name: 'REBASE' },
|
||||
]
|
||||
|
||||
/** One batched snapshot query and the change request behind each alias. */
|
||||
export interface SnapshotQuery {
|
||||
/** One batched status query and the change request behind each alias. */
|
||||
export interface StatusQuery {
|
||||
/** GraphQL document with one aliased field per change request. */
|
||||
readonly document: string
|
||||
/** Change requests keyed by alias path `r<i>.p<j>`. */
|
||||
readonly targets: ReadonlyMap<string, ChangeRequestRef>
|
||||
}
|
||||
|
||||
/** One batched snapshot query. */
|
||||
export interface SnapshotQuery extends StatusQuery {
|
||||
/** Most review threads counted per change request. */
|
||||
readonly maxReviewThreads: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one query that reads every change request in `refs`, grouping them by
|
||||
* repository. Owners, names, and numbers are validated before they are inlined.
|
||||
* Build one query that reads the same fields of every change request in `refs`, grouping them by repository. Owners,
|
||||
* names, and numbers are validated before they are inlined.
|
||||
* @param refs - change requests on one host.
|
||||
* @param maxReviewThreads - positive integer bound on the review threads counted per change request.
|
||||
* @param repositoryFields - selection read once per repository, or the empty string.
|
||||
* @param pullRequestSelection - selection read per pull request.
|
||||
* @returns the document and its alias targets.
|
||||
* @throws when an owner, name, or number cannot be inlined safely.
|
||||
*/
|
||||
export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThreads: number): SnapshotQuery {
|
||||
function statusQuery(refs: readonly ChangeRequestRef[], repositoryFields: string, pullRequestSelection: string): StatusQuery {
|
||||
const repositories = new Map<string, { repository: ForgeRepository; numbers: Map<number, ChangeRequestRef> }>()
|
||||
for (const ref of refs) {
|
||||
const { owner, name } = checkedRepository(ref)
|
||||
@@ -312,21 +331,84 @@ export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThread
|
||||
targets.set(`r${r}.p${p}`, ref)
|
||||
}
|
||||
const owner = JSON.stringify(repository.owner)
|
||||
fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(' ')} }`)
|
||||
fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${repositoryFields} ${pulls.join(' ')} }`)
|
||||
}
|
||||
const document = `query { ${fields.join(' ')} }
|
||||
fragment ChangeRequestFields on PullRequest { ${pullRequestFields(Math.min(PAGE_SIZE, maxReviewThreads))} }`
|
||||
return { document, targets, maxReviewThreads }
|
||||
fragment ChangeRequestFields on PullRequest { ${pullRequestSelection} }`
|
||||
return { document, targets }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one query that reads the snapshot of every change request in `refs`.
|
||||
* @param refs - change requests on one host.
|
||||
* @param maxReviewThreads - positive integer bound on the review threads counted per change request.
|
||||
* @returns the document and its alias targets.
|
||||
* @throws when an owner, name, or number cannot be inlined safely.
|
||||
*/
|
||||
export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThreads: number): SnapshotQuery {
|
||||
return { ...statusQuery(refs, REPOSITORY_FIELDS, pullRequestFields(Math.min(PAGE_SIZE, maxReviewThreads))), maxReviewThreads }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one query that reads the brief of every change request in `refs`.
|
||||
* @param refs - change requests on one host.
|
||||
* @returns the document and its alias targets.
|
||||
* @throws when an owner, name, or number cannot be inlined safely.
|
||||
*/
|
||||
export function briefQuery(refs: readonly ChangeRequestRef[]): StatusQuery {
|
||||
return statusQuery(refs, '', BRIEF_FIELDS)
|
||||
}
|
||||
|
||||
/** What a status response holds for one alias target. */
|
||||
interface StatusTarget {
|
||||
readonly ref: ChangeRequestRef
|
||||
readonly key: ChangeRequestKey
|
||||
/** The pull request node as GitHub returned it, not yet validated. */
|
||||
readonly node: unknown
|
||||
/** The repository node as GitHub returned it, not yet validated. */
|
||||
readonly repository: unknown
|
||||
/** What to report when the node does not hold the fields the query asked for. */
|
||||
readonly failure: ForgeFailure
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve every alias target of a status response, including GitHub's partial-error form. Path-scoped errors apply to
|
||||
* their repository or pull request; errors without a path apply to every unresolved target.
|
||||
* @param body - parsed JSON printed by `gh api graphql`.
|
||||
* @param query - the query that produced the response.
|
||||
* @returns the nodes and the failure of each target, in query order.
|
||||
*/
|
||||
function statusTargets(body: unknown, query: StatusQuery): StatusTarget[] {
|
||||
const parsed = responseSchema.safeParse(body)
|
||||
const repositories = new Set([...query.targets.keys()].map(alias => alias.split('.')[0]))
|
||||
return [...query.targets].map(([alias, ref]) => {
|
||||
const key = changeRequestKey(ref)
|
||||
if (!parsed.success) {
|
||||
return { ref, key, node: undefined, repository: undefined, failure: { code: 'unavailable', message: 'unexpected GitHub response' } }
|
||||
}
|
||||
const [repositoryAlias = '', pullAlias = ''] = alias.split('.')
|
||||
const errors = parsed.data.errors ?? []
|
||||
const error = errors.find(entry => entry.path?.[0] === repositoryAlias && (entry.path.length === 1 || entry.path[1] === pullAlias))
|
||||
?? errors.find(entry => entry.path === undefined || !repositories.has(String(entry.path[0])))
|
||||
const repository = parsed.data.data?.[repositoryAlias]
|
||||
const node = repository?.[pullAlias]
|
||||
let failure: ForgeFailure
|
||||
if (error !== undefined) {
|
||||
const code = error.type === 'NOT_FOUND' ? 'not-found' : error.type === 'RATE_LIMITED' ? 'rate-limited' : 'unavailable'
|
||||
failure = { code, message: error.message }
|
||||
} else if (node === null || node === undefined) failure = { code: 'not-found', message: 'pull request not found' }
|
||||
else failure = { code: 'unavailable', message: 'unexpected pull request fields' }
|
||||
return { ref, key, node, repository, failure }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a snapshot response, including GitHub's partial-error form, into one
|
||||
* result per alias target. Path-scoped errors apply to their repository or
|
||||
* pull request; errors without a path apply to every unresolved target. A
|
||||
* repository without readable merge settings offers no merge. Review threads
|
||||
* are counted across pages up to `query.maxReviewThreads`. Polling returns
|
||||
* the first check page; an explicit detail read can complete its pagination.
|
||||
* A continuation page that fails or does not advance fails its target.
|
||||
* result per alias target. A repository without readable merge settings offers
|
||||
* no merge. Review threads are counted across pages up to
|
||||
* `query.maxReviewThreads`. Polling returns the first check page; an explicit
|
||||
* detail read can complete its pagination. A continuation page that fails or
|
||||
* does not advance fails its target.
|
||||
* @param body - parsed JSON printed by `gh api graphql`.
|
||||
* @param query - the query that produced the response.
|
||||
* @param pages - continuation reads of review threads and, for a detail read, of checks on the same commit.
|
||||
@@ -336,35 +418,46 @@ export async function mapSnapshotResponse(
|
||||
body: unknown, query: SnapshotQuery, pages: SnapshotPages,
|
||||
): Promise<Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
|
||||
const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
|
||||
const parsed = responseSchema.safeParse(body)
|
||||
const repositories = new Set([...query.targets.keys()].map(alias => alias.split('.')[0]))
|
||||
for (const [alias, ref] of query.targets) {
|
||||
const key = changeRequestKey(ref)
|
||||
if (!parsed.success) {
|
||||
results.set(key, { code: 'unavailable', message: 'unexpected GitHub response' })
|
||||
for (const target of statusTargets(body, query)) {
|
||||
const node = pullRequestSchema.safeParse(target.node)
|
||||
if (!node.success) {
|
||||
results.set(target.key, target.failure)
|
||||
continue
|
||||
}
|
||||
const [repositoryAlias = '', pullAlias = ''] = alias.split('.')
|
||||
const errors = parsed.data.errors ?? []
|
||||
const error = errors.find(entry => entry.path?.[0] === repositoryAlias && (entry.path.length === 1 || entry.path[1] === pullAlias))
|
||||
?? errors.find(entry => entry.path === undefined || !repositories.has(String(entry.path[0])))
|
||||
const raw = parsed.data.data?.[repositoryAlias]?.[pullAlias]
|
||||
const node = pullRequestSchema.safeParse(raw)
|
||||
const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias])
|
||||
if (node.success) {
|
||||
const { id, reviewThreads } = node.data
|
||||
const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup
|
||||
const { checks } = pages
|
||||
const failure = await readPages(reviewThreads, query.maxReviewThreads, 'review thread',
|
||||
async (cursor, first) => await pages.threads(id, cursor, first))
|
||||
?? (rollup === undefined || rollup === null || checks === undefined ? undefined
|
||||
: await readPages(rollup.contexts, Number.POSITIVE_INFINITY, 'check', async cursor => await checks(rollup.id, cursor)))
|
||||
results.set(key, failure ?? toSnapshot(ref, node.data, settings.success ? settings.data : undefined))
|
||||
} else if (error !== undefined) {
|
||||
const code = error.type === 'NOT_FOUND' ? 'not-found' : error.type === 'RATE_LIMITED' ? 'rate-limited' : 'unavailable'
|
||||
results.set(key, { code, message: error.message })
|
||||
} else if (raw === null || raw === undefined) results.set(key, { code: 'not-found', message: 'pull request not found' })
|
||||
else results.set(key, { code: 'unavailable', message: 'unexpected pull request fields' })
|
||||
const settings = repositorySchema.safeParse(target.repository)
|
||||
const { id, reviewThreads } = node.data
|
||||
const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup
|
||||
const { checks } = pages
|
||||
const failure = await readPages(reviewThreads, query.maxReviewThreads, 'review thread',
|
||||
async (cursor, first) => await pages.threads(id, cursor, first))
|
||||
?? (rollup === undefined || rollup === null || checks === undefined ? undefined
|
||||
: await readPages(rollup.contexts, Number.POSITIVE_INFINITY, 'check', async cursor => await checks(rollup.id, cursor)))
|
||||
results.set(target.key, failure ?? toSnapshot(target.ref, node.data, settings.success ? settings.data : undefined))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a brief response, including GitHub's partial-error form, into one result per alias target. The combined check
|
||||
* outcome is GitHub's own for the head commit, as a snapshot reports it when its check list is incomplete.
|
||||
* @param body - parsed JSON printed by `gh api graphql`.
|
||||
* @param query - the query that produced the response.
|
||||
* @returns a brief or a failure for every target.
|
||||
*/
|
||||
export function mapBriefResponse(body: unknown, query: StatusQuery): Map<ChangeRequestKey, ChangeRequestBrief | ForgeFailure> {
|
||||
const results = new Map<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>()
|
||||
for (const target of statusTargets(body, query)) {
|
||||
const node = briefSchema.safeParse(target.node)
|
||||
results.set(target.key, node.success ? {
|
||||
ref: target.ref,
|
||||
url: node.data.url,
|
||||
title: node.data.title,
|
||||
state: changeRequestState(node.data.state),
|
||||
draft: node.data.isDraft,
|
||||
mergeability: mergeability(node.data.mergeable),
|
||||
reviewDecision: reviewDecision(node.data.reviewDecision),
|
||||
checksRollup: checksRollup(node.data.commits.nodes[0]?.commit.statusCheckRollup?.state),
|
||||
} : target.failure)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -30,6 +30,13 @@ export interface Config {
|
||||
* one review read, which reports itself truncated past it.
|
||||
*/
|
||||
maxReviewThreads?: number
|
||||
/**
|
||||
* Most pull requests one snapshot query reads. The forge registry polls that many pull requests of a host per call,
|
||||
* each call within its own fetch deadline; a read of more pull requests on one host sends several queries in turn.
|
||||
*/
|
||||
snapshotBatchSize?: number
|
||||
/** The same bound for one brief query. */
|
||||
briefBatchSize?: number
|
||||
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
@@ -44,6 +51,8 @@ export const Config: z<Config> = z.object({
|
||||
timeoutMs: z.number().default(30_000),
|
||||
maxOutputBytes: z.number().default(8_388_608),
|
||||
maxReviewThreads: z.number().default(1_000),
|
||||
snapshotBatchSize: z.number().default(8),
|
||||
briefBatchSize: z.number().default(25),
|
||||
maxCommits: z.number().default(250),
|
||||
maxViewedFiles: z.number().default(3_000),
|
||||
maxViewerItems: z.number().default(50),
|
||||
@@ -64,7 +73,9 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) {
|
||||
throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
|
||||
}
|
||||
for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits', 'maxViewedFiles', 'maxViewerItems'] as const) {
|
||||
for (const key of [
|
||||
'maxOutputBytes', 'maxReviewThreads', 'snapshotBatchSize', 'briefBatchSize', 'maxCommits', 'maxViewedFiles', 'maxViewerItems',
|
||||
] as const) {
|
||||
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`)
|
||||
}
|
||||
if (resolved.maxViewerItems > SEARCH_PAGE) throw new Error(`forge-github: maxViewerItems must be no greater than ${SEARCH_PAGE}`)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure,
|
||||
BranchUpdateRequest, ChangeRequestBrief, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot,
|
||||
ForgeActionFailure,
|
||||
ForgeCommitList, ForgeFailure, ForgeViewerCapability, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery,
|
||||
ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewersRequest,
|
||||
ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
|
||||
@@ -14,10 +15,10 @@ import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts'
|
||||
import type { GhOutput, GhRunner } from './gh.ts'
|
||||
import { readComparison } from './compare.ts'
|
||||
import {
|
||||
actionsRunOf, CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse,
|
||||
mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY,
|
||||
actionsRunOf, briefQuery, CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapBriefResponse, mapCheckPageResponse, mapHeadResponse,
|
||||
mapPullRequestCommitsResponse, mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY,
|
||||
} from './graphql.ts'
|
||||
import type { PageResult, SnapshotPages } from './graphql.ts'
|
||||
import type { PageResult, SnapshotPages, SnapshotQuery, StatusQuery } from './graphql.ts'
|
||||
import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts'
|
||||
import { submitGitHubReview } from './review.ts'
|
||||
import { readViewed, writeViewed } from './viewed.ts'
|
||||
@@ -47,12 +48,16 @@ const TOO_LARGE = /\btoo_large\b/
|
||||
/** HTTP status GitHub answers when it refuses to render a diff over its limits. */
|
||||
const NOT_ACCEPTABLE = '406'
|
||||
|
||||
/** Bounds on what one read retains or counts. */
|
||||
/** Bounds on what one read retains or counts, and on the pull requests one status query reads. */
|
||||
export interface GitHubLimits {
|
||||
/** Maximum combined JSON bytes retained by an explicit check read or a review read. */
|
||||
readonly maxOutputBytes: number
|
||||
/** Most review threads counted per pull request in one status read, and read in one review read. */
|
||||
readonly maxReviewThreads: number
|
||||
/** Most pull requests one snapshot query reads. */
|
||||
readonly snapshotBatchSize: number
|
||||
/** Most pull requests one brief query reads. */
|
||||
readonly briefBatchSize: number
|
||||
/** Most commits one commit listing returns. */
|
||||
readonly maxCommits: number
|
||||
/** Most files whose viewed marks one read lists. */
|
||||
@@ -69,6 +74,8 @@ export class GitHubProvider implements ForgeProvider {
|
||||
readonly changeRequestNoun = 'pull-request'
|
||||
readonly viewer: ForgeViewerCapability
|
||||
private readonly served: ReadonlySet<string>
|
||||
readonly snapshotBatchSize: number
|
||||
readonly briefBatchSize: number
|
||||
|
||||
async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
@@ -101,13 +108,16 @@ export class GitHubProvider implements ForgeProvider {
|
||||
/**
|
||||
* @param gh - runner that executes `gh` on the host.
|
||||
* @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts.
|
||||
* @param limits - bounds on retained check and review bytes, counted and read review threads, listed commits, listed
|
||||
* viewed files, and listed viewer pull requests.
|
||||
* @param limits - bounds on retained check and review bytes, counted and read review threads, pull requests per snapshot
|
||||
* query and per brief query, listed commits, listed viewed files, and listed viewer pull requests.
|
||||
*/
|
||||
constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) {
|
||||
this.hosts = [...new Set(hosts.map(host => host.toLowerCase()))]
|
||||
this.served = new Set(this.hosts)
|
||||
this.viewer = { hosts: this.hosts, filters: VIEWER_FILTERS, maxItems: limits.maxViewerItems }
|
||||
// One polling call of the registry then holds one query, which has the call's deadline to itself.
|
||||
this.snapshotBatchSize = limits.snapshotBatchSize
|
||||
this.briefBatchSize = limits.briefBatchSize
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,24 +171,52 @@ export class GitHubProvider implements ForgeProvider {
|
||||
return `https://${host}/${owner}/${name}/pull/${ref.number}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Read snapshots through GraphQL, at most `snapshotBatchSize` pull requests of one host per query, one query after
|
||||
* another. Every query is built before the first request. A query whose `gh` run cannot start, times out, or prints
|
||||
* over its limit, and one GitHub refuses, fails only its own pull requests.
|
||||
* @param refs - pull requests to read.
|
||||
* @param signal - cancellation of the whole read.
|
||||
* @returns one result for each pull request in `refs`.
|
||||
* @throws with `signal.reason` once cancelled, without another request, and before any request when a reference
|
||||
* cannot be inlined.
|
||||
*/
|
||||
async fetch(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
|
||||
const byHost = new Map<string, ChangeRequestRef[]>()
|
||||
const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
|
||||
for (const ref of refs) {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) {
|
||||
results.set(changeRequestKey(ref), failure)
|
||||
continue
|
||||
}
|
||||
const group = byHost.get(ref.repository.host)
|
||||
if (group === undefined) byHost.set(ref.repository.host, [ref])
|
||||
else group.push(ref)
|
||||
const { snapshotBatchSize, maxReviewThreads } = this.limits
|
||||
const queries = this.statusQueries(refs, results, snapshotBatchSize, chunk => snapshotQuery(chunk, maxReviewThreads))
|
||||
for (const { host, query } of queries) {
|
||||
for (const [key, result] of await this.fetchSnapshots(host, query, signal, false)) results.set(key, result)
|
||||
}
|
||||
for (const [host, group] of byHost) {
|
||||
for (const [key, result] of await this.fetchHost(host, group, signal)) results.set(key, result)
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Read briefs through GraphQL, at most `briefBatchSize` pull requests of one host per query, one query after
|
||||
* another. Every query is built before the first request. A query whose `gh` run cannot start, times out, or prints
|
||||
* over its limit, and one GitHub refuses, fails only its own pull requests.
|
||||
* @param refs - pull requests to read.
|
||||
* @param signal - cancellation of the whole read.
|
||||
* @returns one result for each pull request in `refs`.
|
||||
* @throws with `signal.reason` once cancelled, without another request, and before any request when a reference
|
||||
* cannot be inlined.
|
||||
*/
|
||||
async fetchBriefs(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>> {
|
||||
const results = new Map<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>()
|
||||
for (const { host, query } of this.statusQueries(refs, results, this.limits.briefBatchSize, briefQuery)) {
|
||||
const output = await this.statusOutput(host, ['-f', `query=${query.document}`], signal)
|
||||
let briefs: ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>
|
||||
if ('stdout' in output) {
|
||||
const body = parseJson(output.stdout)
|
||||
briefs = hasGraphqlFields(body) ? mapBriefResponse(body, query) : failAll(query, responseFailure(output, body))
|
||||
} else briefs = failAll(query, output)
|
||||
for (const [key, result] of briefs) results.set(key, result)
|
||||
}
|
||||
return results
|
||||
}
|
||||
@@ -186,14 +224,10 @@ export class GitHubProvider implements ForgeProvider {
|
||||
async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) return failure
|
||||
try {
|
||||
const results = await this.fetchHost(ref.repository.host, [ref], signal, true)
|
||||
// oxlint-disable-next-line typescript/no-non-null-assertion -- fetchHost returns one result for each requested ref.
|
||||
return results.get(changeRequestKey(ref))!
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw signal.reason
|
||||
return processFailure(error)
|
||||
}
|
||||
const query = snapshotQuery([ref], this.limits.maxReviewThreads)
|
||||
const [result] = (await this.fetchSnapshots(ref.repository.host, query, signal, true)).values()
|
||||
// oxlint-disable-next-line typescript/no-non-null-assertion -- a query returns one result for each of its pull requests.
|
||||
return result!
|
||||
}
|
||||
|
||||
async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]> {
|
||||
@@ -496,14 +530,57 @@ export class GitHubProvider implements ForgeProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchHost(
|
||||
host: string,
|
||||
/**
|
||||
* Build the queries of a status read: pull requests grouped by host in the order given, at most `size` per query.
|
||||
* @param refs - pull requests to read.
|
||||
* @param results - receives the failure of each pull request on a host this provider does not serve.
|
||||
* @param size - most pull requests in one query.
|
||||
* @param build - builds the query of consecutive pull requests on one host.
|
||||
* @returns every query with its host, in request order.
|
||||
* @throws what `build` throws for a reference that cannot be inlined.
|
||||
*/
|
||||
private statusQueries<Query extends StatusQuery, Status>(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
results: Map<ChangeRequestKey, Status | ForgeFailure>,
|
||||
size: number,
|
||||
build: (refs: readonly ChangeRequestRef[]) => Query,
|
||||
): { readonly host: string; readonly query: Query }[] {
|
||||
const byHost = new Map<string, ChangeRequestRef[]>()
|
||||
for (const ref of refs) {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) {
|
||||
results.set(changeRequestKey(ref), failure)
|
||||
continue
|
||||
}
|
||||
const group = byHost.get(ref.repository.host)
|
||||
if (group === undefined) byHost.set(ref.repository.host, [ref])
|
||||
else group.push(ref)
|
||||
}
|
||||
const queries: { readonly host: string; readonly query: Query }[] = []
|
||||
for (const [host, group] of byHost) {
|
||||
for (let start = 0; start < group.length; start += size) queries.push({ host, query: build(group.slice(start, start + size)) })
|
||||
}
|
||||
return queries
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one snapshot query and the continuation pages of its pull requests.
|
||||
* @param host - host the query reads from.
|
||||
* @param query - the query and its alias targets.
|
||||
* @param signal - cancellation of the read.
|
||||
* @param completeChecks - whether to follow every check page within one `maxOutputBytes` budget.
|
||||
* @returns one result for each alias target: the same failure for all of them when the `gh` run of the query cannot
|
||||
* start, times out, or prints over its limit, and when GitHub refuses the query.
|
||||
* @throws with `signal.reason` when the read is cancelled.
|
||||
*/
|
||||
private async fetchSnapshots(
|
||||
host: string,
|
||||
query: SnapshotQuery,
|
||||
signal: AbortSignal,
|
||||
completeChecks = false,
|
||||
completeChecks: boolean,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
|
||||
const query = snapshotQuery(refs, this.limits.maxReviewThreads)
|
||||
const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal)
|
||||
const output = await this.statusOutput(host, ['-f', `query=${query.document}`], signal)
|
||||
if (!('stdout' in output)) return failAll(query, output)
|
||||
const body = parseJson(output.stdout)
|
||||
// A complete check read retains every response it reads, so all of them share one byte budget.
|
||||
let bytes = Buffer.byteLength(output.stdout)
|
||||
@@ -516,7 +593,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const continuation = async <T>(
|
||||
variables: readonly string[], map: (value: unknown) => PageResult<T>,
|
||||
): Promise<PageResult<T>> => {
|
||||
const page = await this.continuation(host, variables, signal)
|
||||
const page = await this.statusOutput(host, variables, signal)
|
||||
if (!('stdout' in page)) return { ok: false, failure: page }
|
||||
if (overBudget(page)) return { ok: false, failure: tooLarge }
|
||||
const value = parseJson(page.stdout)
|
||||
@@ -525,24 +602,23 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const threads: SnapshotPages['threads'] = async (id, cursor, first) => await continuation(
|
||||
['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], mapThreadPageResponse)
|
||||
if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads })
|
||||
if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge]))
|
||||
if (bytes > this.limits.maxOutputBytes) return failAll(query, tooLarge)
|
||||
if (hasGraphqlFields(body)) {
|
||||
return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => await continuation(
|
||||
['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], mapCheckPageResponse) })
|
||||
}
|
||||
const failure = responseFailure(output, body)
|
||||
return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const))
|
||||
return failAll(query, responseFailure(output, body))
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one continuation query of a snapshot read.
|
||||
* @param host - host the snapshot was read from.
|
||||
* Run one GraphQL request of a status read: a snapshot query, a brief query, or a continuation page.
|
||||
* @param host - host the status is read from.
|
||||
* @param variables - `gh api graphql` field flags, the query first.
|
||||
* @param signal - cancellation of the snapshot read.
|
||||
* @param signal - cancellation of the status read.
|
||||
* @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit.
|
||||
* @throws with `signal.reason` when the read is cancelled.
|
||||
*/
|
||||
private async continuation(host: string, variables: readonly string[], signal: AbortSignal): Promise<GhOutput | ForgeFailure> {
|
||||
private async statusOutput(host: string, variables: readonly string[], signal: AbortSignal): Promise<GhOutput | ForgeFailure> {
|
||||
signal.throwIfAborted()
|
||||
try {
|
||||
return await this.gh(['api', 'graphql', '--hostname', host, ...variables], signal)
|
||||
@@ -553,6 +629,11 @@ export class GitHubProvider implements ForgeProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The same failure for every pull request of a status query. */
|
||||
function failAll(query: StatusQuery, failure: ForgeFailure): Map<ChangeRequestKey, ForgeFailure> {
|
||||
return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const))
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a `gh` invocation that did not run to an exit code.
|
||||
* @param error - what the runner threw.
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
/** The brief read of the GitHub provider: its query, its mapping, and its queries per `briefBatchSize`. */
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestBrief, ChangeRequestRef, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from '../src/gh.ts'
|
||||
import type { GhOutput, GhRunner } from '../src/gh.ts'
|
||||
import { briefQuery, mapBriefResponse } from '../src/graphql.ts'
|
||||
import { GitHubProvider } from '../src/provider.ts'
|
||||
import type { GitHubLimits } from '../src/provider.ts'
|
||||
import { briefNode, demo, pull } from './fixtures.ts'
|
||||
|
||||
const enterprise = { forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' }
|
||||
const other = { ...demo, name: 'other' }
|
||||
const signal = new AbortController().signal
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
/** The brief of `briefNode(number)`. */
|
||||
function brief(target: ChangeRequestRef, overrides: Partial<ChangeRequestBrief> = {}): ChangeRequestBrief {
|
||||
return {
|
||||
ref: target,
|
||||
url: `https://github.com/octo/demo/pull/${target.number}`,
|
||||
title: `Change ${target.number}`,
|
||||
state: 'open',
|
||||
draft: false,
|
||||
mergeability: 'mergeable',
|
||||
reviewDecision: 'none',
|
||||
checksRollup: 'success',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr }
|
||||
}
|
||||
|
||||
/** Pull request numbers one brief query reads, in alias order. */
|
||||
function queried(args: readonly string[]): number[] {
|
||||
const query = args.find(arg => arg.startsWith('query=')) ?? ''
|
||||
return [...query.matchAll(/pullRequest\(number: (\d+)\)/g)].map(match => Number(match[1]))
|
||||
}
|
||||
|
||||
/** Answer a brief query of `demo` pull requests with one node each. */
|
||||
function answer(args: readonly string[]): GhOutput {
|
||||
return output({ data: { r0: Object.fromEntries(queried(args).map((number, index) => [`p${index}`, briefNode(number)])) } })
|
||||
}
|
||||
|
||||
function fakeGh(handler: (args: readonly string[]) => GhOutput | Promise<GhOutput>): { run: GhRunner; calls: string[][] } {
|
||||
const calls: string[][] = []
|
||||
return {
|
||||
calls,
|
||||
run: async (args) => {
|
||||
calls.push([...args])
|
||||
return await handler(args)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function pulls(count: number): ChangeRequestRef[] {
|
||||
return Array.from({ length: count }, (_, index) => pull(index + 1))
|
||||
}
|
||||
|
||||
function provider(run: GhRunner, overrides: Partial<GitHubLimits> = {}): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com', 'ghe.corp.example'], { ...limits, ...overrides })
|
||||
}
|
||||
|
||||
describe('brief query', () => {
|
||||
it('reads the brief fields of each pull request and no repository fields', () => {
|
||||
const query = briefQuery([pull(1), pull(2), pull(7, other)])
|
||||
|
||||
expect([...query.targets]).toEqual([['r0.p0', pull(1)], ['r0.p1', pull(2)], ['r1.p0', pull(7, other)]])
|
||||
expect(query.document).toContain('r0: repository(owner: "octo", name: "demo") { p0: pullRequest(number: 1) { ...ChangeRequestFields } p1: pullRequest(number: 2) { ...ChangeRequestFields } }')
|
||||
expect(query.document).toContain('fragment ChangeRequestFields on PullRequest { url title state isDraft mergeable reviewDecision '
|
||||
+ 'commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } }')
|
||||
})
|
||||
|
||||
it('refuses a reference that cannot be inlined', () => {
|
||||
expect(() => briefQuery([pull(1, { ...demo, owner: 'oc"to' })])).toThrow('forge-github: invalid repository "oc\\"to/demo"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('brief mapping', () => {
|
||||
it('maps the state, draft flag, mergeability, review decision, and combined check state', () => {
|
||||
const query = briefQuery([pull(1), pull(2), pull(3), pull(4), pull(5)])
|
||||
const results = mapBriefResponse({ data: { r0: {
|
||||
p0: briefNode(1),
|
||||
p1: briefNode(2, { state: 'MERGED', mergeable: 'UNKNOWN', reviewDecision: 'APPROVED', commits: { nodes: [{ commit: { statusCheckRollup: null } }] } }),
|
||||
p2: briefNode(3, { state: 'CLOSED', isDraft: true, mergeable: 'CONFLICTING', reviewDecision: 'CHANGES_REQUESTED',
|
||||
commits: { nodes: [{ commit: { statusCheckRollup: { state: 'FAILURE' } } }] } }),
|
||||
p3: briefNode(4, { reviewDecision: 'REVIEW_REQUIRED', commits: { nodes: [{ commit: { statusCheckRollup: { state: 'PENDING' } } }] } }),
|
||||
p4: briefNode(5, { commits: { nodes: [] } }),
|
||||
} } }, query)
|
||||
|
||||
expect([...results.values()]).toEqual([
|
||||
brief(pull(1)),
|
||||
brief(pull(2), { state: 'merged', mergeability: 'unknown', reviewDecision: 'approved', checksRollup: 'none' }),
|
||||
brief(pull(3), { state: 'closed', draft: true, mergeability: 'conflicting', reviewDecision: 'changes-requested', checksRollup: 'failure' }),
|
||||
brief(pull(4), { reviewDecision: 'review-required', checksRollup: 'pending' }),
|
||||
brief(pull(5), { checksRollup: 'none' }),
|
||||
])
|
||||
})
|
||||
|
||||
it('fails only the pull requests an error names, a missing node, and a node without the brief fields', () => {
|
||||
const query = briefQuery([pull(1), pull(2), pull(3), pull(4), pull(7, other)])
|
||||
const results = mapBriefResponse({
|
||||
data: { r0: { p0: briefNode(1), p1: null, p2: null, p3: { title: 4 } }, r1: null },
|
||||
errors: [
|
||||
{ type: 'NOT_FOUND', path: ['r0', 'p1'], message: 'Could not resolve to a PullRequest with the number of 2.' },
|
||||
{ type: 'RATE_LIMITED', path: ['r1'], message: 'API rate limit exceeded' },
|
||||
],
|
||||
}, query)
|
||||
|
||||
expect([...results.values()]).toEqual([
|
||||
brief(pull(1)),
|
||||
{ code: 'not-found', message: 'Could not resolve to a PullRequest with the number of 2.' },
|
||||
{ code: 'not-found', message: 'pull request not found' },
|
||||
{ code: 'unavailable', message: 'unexpected pull request fields' },
|
||||
{ code: 'rate-limited', message: 'API rate limit exceeded' },
|
||||
])
|
||||
})
|
||||
|
||||
it('applies an error without a path to every pull request, and fails every one of a body that is not GraphQL', () => {
|
||||
const query = briefQuery([pull(1), pull(2)])
|
||||
const timeout: ForgeFailure = { code: 'unavailable', message: 'Something went wrong while executing your query.' }
|
||||
|
||||
expect([...mapBriefResponse({ data: null, errors: [{ message: timeout.message }] }, query).values()]).toEqual([timeout, timeout])
|
||||
expect([...mapBriefResponse([], query).values()]).toEqual([
|
||||
{ code: 'unavailable', message: 'unexpected GitHub response' }, { code: 'unavailable', message: 'unexpected GitHub response' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GitHub provider briefs', () => {
|
||||
it.each([
|
||||
[1, 50, [1]],
|
||||
[50, 50, [50]],
|
||||
[51, 50, [50, 1]],
|
||||
[7, 3, [3, 3, 1]],
|
||||
[3, 1, [1, 1, 1]],
|
||||
])('reads %i pull requests with briefBatchSize %i in queries of %j, in order', async (count, briefBatchSize, sizes) => {
|
||||
const gh = fakeGh(answer)
|
||||
const refs = pulls(count)
|
||||
|
||||
const results = await provider(gh.run, { briefBatchSize }).fetchBriefs(refs, signal)
|
||||
|
||||
expect(gh.calls.map(call => queried(call).length)).toEqual(sizes)
|
||||
expect(gh.calls.flatMap(queried)).toEqual(refs.map(ref => ref.number))
|
||||
expect(gh.calls[0]?.slice(0, 5)).toEqual(['api', 'graphql', '--hostname', 'github.com', '-f'])
|
||||
expect([...results.values()]).toEqual(refs.map(ref => brief(ref)))
|
||||
})
|
||||
|
||||
it('sends a query only after the previous one is answered', async () => {
|
||||
const first = Promise.withResolvers<undefined>()
|
||||
const gh = fakeGh(async (args) => {
|
||||
if (queried(args)[0] === 1) await first.promise
|
||||
return answer(args)
|
||||
})
|
||||
|
||||
const read = provider(gh.run, { briefBatchSize: 2 }).fetchBriefs(pulls(3), signal)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
expect(gh.calls).toHaveLength(1)
|
||||
first.resolve(undefined)
|
||||
|
||||
expect((await read).size).toBe(3)
|
||||
expect(gh.calls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['times out', () => { throw new GhTimeoutError('gh api timed out after 30000ms') }, 'unavailable', 'gh api timed out after 30000ms'],
|
||||
['prints over its limit', () => { throw new GhOutputLimitError('gh api output exceeds maxOutputBytes') }, 'too-large',
|
||||
'gh api output exceeds maxOutputBytes'],
|
||||
['cannot start', () => { throw new GhUnavailableError('gh could not start: spawn gh ENOENT') }, 'unavailable',
|
||||
'gh could not start: spawn gh ENOENT'],
|
||||
['is refused', () => output('', 1, 'HTTP 502: Bad Gateway (https://api.github.com/graphql)'), 'unavailable',
|
||||
'HTTP 502: Bad Gateway (https://api.github.com/graphql)'],
|
||||
] as const)('fails only the pull requests of a query that %s', async (_, fail, code, message) => {
|
||||
const gh = fakeGh(args => queried(args)[0] === 3 ? fail() : answer(args))
|
||||
const refs = pulls(6)
|
||||
|
||||
const results = await provider(gh.run, { briefBatchSize: 2 }).fetchBriefs(refs, signal)
|
||||
|
||||
expect(gh.calls).toHaveLength(3)
|
||||
expect([...results.values()]).toEqual([
|
||||
brief(pull(1)), brief(pull(2)), { code, message }, { code, message }, brief(pull(5)), brief(pull(6)),
|
||||
])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['after a query is answered', false],
|
||||
['while a query runs', true],
|
||||
])('sends no further query once cancelled %s', async (_, during) => {
|
||||
const controller = new AbortController()
|
||||
const gh = fakeGh((args) => {
|
||||
if (queried(args)[0] !== 3) return answer(args)
|
||||
controller.abort(new Error('cancelled'))
|
||||
if (during) throw controller.signal.reason
|
||||
return answer(args)
|
||||
})
|
||||
|
||||
await expect(provider(gh.run, { briefBatchSize: 2 }).fetchBriefs(pulls(6), controller.signal)).rejects.toThrow('cancelled')
|
||||
expect(gh.calls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('passes on a runner defect', async () => {
|
||||
const gh = fakeGh(() => { throw new Error('defect') })
|
||||
|
||||
await expect(provider(gh.run).fetchBriefs(pulls(1), signal)).rejects.toThrow('defect')
|
||||
})
|
||||
|
||||
it('builds every query before the first request, across hosts', async () => {
|
||||
const gh = fakeGh(answer)
|
||||
|
||||
await expect(provider(gh.run).fetchBriefs([pull(1), pull(2, { ...enterprise, owner: 'te"am' })], signal)).rejects.toThrow('invalid repository')
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
|
||||
it('reads each configured host with its own queries and fails references of other hosts without a request', async () => {
|
||||
const gh = fakeGh(answer)
|
||||
const denied = pull(9, { ...demo, host: 'unconfigured.example' })
|
||||
|
||||
const results = await provider(gh.run).fetchBriefs([pull(1), denied, pull(2, enterprise), pull(3)], signal)
|
||||
|
||||
expect(gh.calls.map(call => [call[3], queried(call)])).toEqual([['github.com', [1, 3]], ['ghe.corp.example', [2]]])
|
||||
expect(results.get(changeRequestKey(denied))).toEqual({ code: 'unavailable', message: 'forge-github: host "unconfigured.example" is not configured' })
|
||||
expect(results.get(changeRequestKey(pull(3)))).toEqual(brief(pull(3)))
|
||||
expect(results.size).toBe(4)
|
||||
})
|
||||
})
|
||||
@@ -8,7 +8,8 @@ import { pull } from './fixtures.ts'
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner; calls: string[][] } {
|
||||
|
||||
@@ -42,6 +42,20 @@ export function repositorySettings(overrides: Record<string, unknown> = {}): Rec
|
||||
}
|
||||
}
|
||||
|
||||
/** One pull request node as a brief query returns it. */
|
||||
export function briefNode(number: number, overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
url: `https://github.com/octo/demo/pull/${number}`,
|
||||
title: `Change ${number}`,
|
||||
state: 'OPEN',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
reviewDecision: null,
|
||||
commits: { nodes: [{ commit: { statusCheckRollup: { state: 'SUCCESS' } } }] },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** A pull request node with the fields the snapshot query selects. */
|
||||
export function pullRequestNode(number: number, overrides: Record<string, unknown> = {}, contexts: unknown[] = [], rollupState: string | null = 'SUCCESS'): Record<string, unknown> {
|
||||
return {
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import ForgeService from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ForgeCommandRule } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { GH_COMMANDS } from '../src/commands.ts'
|
||||
import * as ForgeGitHub from '../src/index.ts'
|
||||
import { briefNode, pull, pullRequestNode } from './fixtures.ts'
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
@@ -96,10 +101,14 @@ describe('forge-github plugin', () => {
|
||||
[{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
|
||||
[{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
|
||||
[{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
|
||||
[{ snapshotBatchSize: 0 }, 'forge-github: snapshotBatchSize must be a positive safe integer'],
|
||||
[{ snapshotBatchSize: 2.5 }, 'forge-github: snapshotBatchSize must be a positive safe integer'],
|
||||
[{ maxCommits: 0 }, 'forge-github: maxCommits must be a positive safe integer'],
|
||||
[{ maxCommits: 2.5 }, 'forge-github: maxCommits must be a positive safe integer'],
|
||||
[{ maxReviewThreads: 0 }, 'forge-github: maxReviewThreads must be a positive safe integer'],
|
||||
[{ maxReviewThreads: 2.5 }, 'forge-github: maxReviewThreads must be a positive safe integer'],
|
||||
[{ briefBatchSize: 0 }, 'forge-github: briefBatchSize must be a positive safe integer'],
|
||||
[{ briefBatchSize: 2.5 }, 'forge-github: briefBatchSize must be a positive safe integer'],
|
||||
[{ maxViewerItems: 0 }, 'forge-github: maxViewerItems must be a positive safe integer'],
|
||||
[{ maxViewerItems: 101 }, 'forge-github: maxViewerItems must be no greater than 100'],
|
||||
])('rejects %j at load', async (config, message) => {
|
||||
@@ -114,3 +123,82 @@ describe('forge-github plugin', () => {
|
||||
expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
// The recording `gh` is a POSIX shell script, as in gh.spec.ts.
|
||||
describe.skipIf(process.platform === 'win32')('forge-github plugin status queries', () => {
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
|
||||
})
|
||||
|
||||
/**
|
||||
* A `gh` that appends the pull request numbers of each query to a log and answers `node` for each; a query that
|
||||
* names pull request `hangOn` never answers.
|
||||
*/
|
||||
async function recordingGh(
|
||||
node: Record<string, unknown>, hangOn?: number,
|
||||
): Promise<{ readonly command: string; readonly queries: () => Promise<number[][]> }> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'forge-github-status-'))
|
||||
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
|
||||
const command = join(root, 'gh')
|
||||
const log = join(root, 'queries.log')
|
||||
await writeFile(command, [
|
||||
'#!/bin/sh',
|
||||
'numbers=$(printf "%s" "$*" | grep -o "pullRequest(number: [0-9]*)" | grep -o "[0-9]*" | tr "\\n" " ")',
|
||||
`printf "%s\\n" "$numbers" >> ${JSON.stringify(log)}`,
|
||||
...hangOn === undefined ? [] : [`case " $numbers" in *" ${hangOn} "*) exec sleep 60;; esac`],
|
||||
'fields=""; index=0',
|
||||
`for number in $numbers; do fields="$fields\${fields:+,}\\"p$index\\":"${JSON.stringify(JSON.stringify(node))}; index=$((index + 1)); done`,
|
||||
'printf "{\\"data\\":{\\"r0\\":{%s}}}" "$fields"',
|
||||
'',
|
||||
].join('\n'))
|
||||
await chmod(command, 0o755)
|
||||
return {
|
||||
command,
|
||||
queries: async () => (await readFile(log, 'utf8')).trim().split('\n').map(line => line.trim().split(' ').map(Number)),
|
||||
}
|
||||
}
|
||||
|
||||
it.each([
|
||||
['brief', {}, 51, [25, 25, 1]],
|
||||
['brief', { briefBatchSize: 3 }, 4, [3, 1]],
|
||||
['snapshot', {}, 9, [8, 1]],
|
||||
['snapshot', { snapshotBatchSize: 3 }, 4, [3, 1]],
|
||||
] as const)('polls %s watches of the forge service in queries of the configured size: %j', async (level, config, count, sizes) => {
|
||||
const gh = await recordingGh(level === 'brief' ? briefNode(0) : pullRequestNode(0))
|
||||
const context = new Context()
|
||||
cleanups.push(async () => { await context.fiber.dispose() })
|
||||
await context.plugin(ForgeService)
|
||||
await context.plugin(ForgeGitHub, { ghCommand: gh.command, ...config })
|
||||
const seen = new Set<ChangeRequestKey>()
|
||||
|
||||
for (const ref of Array.from({ length: count }, (_, index) => pull(index + 1))) {
|
||||
if (level === 'brief') context.forge.watchBrief(ref, update => void ('brief' in update && seen.add(update.key)))
|
||||
else context.forge.watch(ref, update => void ('snapshot' in update && seen.add(update.key)))
|
||||
}
|
||||
|
||||
await vi.waitFor(() => { expect(seen.size).toBe(count) }, { timeout: 10_000 })
|
||||
expect((await gh.queries()).map(numbers => numbers.length)).toEqual(sizes)
|
||||
})
|
||||
|
||||
it('gives each query a fetch deadline of its own, so a query whose gh run hangs fails only its own pull requests', async () => {
|
||||
const gh = await recordingGh(pullRequestNode(0), 1)
|
||||
const context = new Context()
|
||||
cleanups.push(async () => { await context.fiber.dispose() })
|
||||
// The deadline of the registry equals the one of a `gh` run, as it does by default. Five seconds leave the `gh`
|
||||
// run that answers enough time on a machine that also runs other specs.
|
||||
await context.plugin(ForgeService, { fetchTimeoutMs: 5_000 })
|
||||
await context.plugin(ForgeGitHub, { ghCommand: gh.command, timeoutMs: 5_000, snapshotBatchSize: 2 })
|
||||
const outcomes = new Map<number, string>()
|
||||
|
||||
for (const number of [1, 2, 3, 4]) {
|
||||
context.forge.watch(pull(number), (update) => { outcomes.set(number, 'failure' in update ? update.failure.code : 'snapshot') })
|
||||
}
|
||||
|
||||
await vi.waitFor(() => { expect(outcomes.size).toBe(4) }, { timeout: 30_000 })
|
||||
expect([...outcomes].sort(([left], [right]) => left - right)).toEqual([[1, 'unavailable'], [2, 'unavailable'], [3, 'snapshot'], [4, 'snapshot']])
|
||||
// The run that hangs may end before it logged its query; the query after it is sent once.
|
||||
expect((await gh.queries()).filter(numbers => !numbers.includes(1))).toEqual([[3, 4]])
|
||||
}, 60_000)
|
||||
})
|
||||
@@ -28,11 +28,12 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
}
|
||||
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits)
|
||||
function provider(run: GhRunner, overrides: Partial<GitHubLimits> = {}): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], { ...limits, ...overrides })
|
||||
}
|
||||
|
||||
describe('GitHub provider addressing', () => {
|
||||
@@ -331,6 +332,112 @@ describe('GitHub provider fetch', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GitHub provider snapshot queries', () => {
|
||||
it('names the sizes of its queries to the registry', () => {
|
||||
const subject = provider(fakeGh(() => output('')).run, { snapshotBatchSize: 3, briefBatchSize: 7 })
|
||||
|
||||
expect([subject.snapshotBatchSize, subject.briefBatchSize]).toEqual([3, 7])
|
||||
})
|
||||
|
||||
/** Pull request numbers one snapshot query reads, in alias order. */
|
||||
function documentNumbers(args: readonly string[]): number[] {
|
||||
const query = args.find(arg => arg.startsWith('query=')) ?? ''
|
||||
return [...query.matchAll(/pullRequest\(number: (\d+)\)/g)].map(match => Number(match[1]))
|
||||
}
|
||||
|
||||
/** Answer a snapshot query of `demo` pull requests with one node each. */
|
||||
function answer(args: readonly string[]): GhOutput {
|
||||
return output({ data: { r0: Object.fromEntries(documentNumbers(args).map((number, index) => [`p${index}`, pullRequestNode(number)])) } })
|
||||
}
|
||||
|
||||
function pulls(count: number): ReturnType<typeof pull>[] {
|
||||
return Array.from({ length: count }, (_, index) => pull(index + 1))
|
||||
}
|
||||
|
||||
it.each([
|
||||
[1, {}, [1]],
|
||||
[8, {}, [8]],
|
||||
[9, {}, [8, 1]],
|
||||
[17, {}, [8, 8, 1]],
|
||||
[7, { snapshotBatchSize: 3 }, [3, 3, 1]],
|
||||
[3, { snapshotBatchSize: 1 }, [1, 1, 1]],
|
||||
])('reads %i pull requests under limits %j in queries of %j, in order', async (count, overrides, sizes) => {
|
||||
const gh = fakeGh(answer)
|
||||
const refs = pulls(count)
|
||||
|
||||
const results = await provider(gh.run, overrides).fetch(refs, signal)
|
||||
|
||||
expect(gh.calls.map(call => documentNumbers(call).length)).toEqual(sizes)
|
||||
expect(gh.calls.flatMap(documentNumbers)).toEqual(refs.map(ref => ref.number))
|
||||
for (const ref of refs) expect(results.get(changeRequestKey(ref))).toMatchObject({ title: `Change ${ref.number}` })
|
||||
})
|
||||
|
||||
it('sends a query only after the previous one is answered', async () => {
|
||||
const first = Promise.withResolvers<undefined>()
|
||||
const gh = fakeGh(async (args) => {
|
||||
if (documentNumbers(args)[0] === 1) await first.promise
|
||||
return answer(args)
|
||||
})
|
||||
|
||||
const read = provider(gh.run).fetch(pulls(9), signal)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
expect(gh.calls).toHaveLength(1)
|
||||
first.resolve(undefined)
|
||||
|
||||
expect((await read).size).toBe(9)
|
||||
expect(gh.calls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['times out', () => { throw new GhTimeoutError('gh api timed out after 30000ms') }, 'unavailable', 'gh api timed out after 30000ms'],
|
||||
['prints over its limit', () => { throw new GhOutputLimitError('gh api output exceeds maxOutputBytes') }, 'too-large',
|
||||
'gh api output exceeds maxOutputBytes'],
|
||||
['cannot start', () => { throw new GhUnavailableError('gh could not start: spawn gh ENOENT') }, 'unavailable',
|
||||
'gh could not start: spawn gh ENOENT'],
|
||||
['is refused', () => output('', 1, 'HTTP 502: Bad Gateway (https://api.github.com/graphql)'), 'unavailable',
|
||||
'HTTP 502: Bad Gateway (https://api.github.com/graphql)'],
|
||||
['meets a GraphQL timeout', () => output({ data: null, errors: [{ message: 'Something went wrong while executing your query.' }] }),
|
||||
'unavailable', 'Something went wrong while executing your query.'],
|
||||
] as const)('fails only the pull requests of a query that %s', async (_, fail, code, message) => {
|
||||
const gh = fakeGh(args => documentNumbers(args)[0] === 9 ? fail() : answer(args))
|
||||
const refs = pulls(17)
|
||||
|
||||
const results = await provider(gh.run).fetch(refs, signal)
|
||||
|
||||
expect(gh.calls).toHaveLength(3)
|
||||
for (const ref of refs) {
|
||||
expect(results.get(changeRequestKey(ref))).toEqual(ref.number >= 9 && ref.number <= 16
|
||||
? { code, message } : expect.objectContaining({ title: `Change ${ref.number}` }))
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
['after a query is answered', false],
|
||||
['while a query runs', true],
|
||||
])('sends no further query once cancelled %s', async (_, during) => {
|
||||
const controller = new AbortController()
|
||||
const gh = fakeGh((args) => {
|
||||
if (documentNumbers(args)[0] !== 9) return answer(args)
|
||||
controller.abort(new Error('cancelled'))
|
||||
if (during) throw controller.signal.reason
|
||||
return answer(args)
|
||||
})
|
||||
|
||||
await expect(provider(gh.run).fetch(pulls(17), controller.signal)).rejects.toThrow('cancelled')
|
||||
expect(gh.calls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['in a later query of the same host', () => [...pulls(8), pull(9, { ...demo, owner: 'oc"to' })]],
|
||||
['on a later host', () => [pull(1), pull(2, { ...enterprise, owner: 'te"am' })]],
|
||||
])('rejects a reference it cannot inline %s before the first request', async (_, refs) => {
|
||||
const gh = fakeGh(answer)
|
||||
|
||||
await expect(provider(gh.run).fetch(refs(), signal)).rejects.toThrow('invalid repository')
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GitHub provider head branch lookup', () => {
|
||||
it('passes the repository and branch as GraphQL variables', async () => {
|
||||
const gh = fakeGh(() => output({ data: { repository: { defaultBranchRef: { name: 'master' }, pullRequests: { nodes: [{ number: 5, isCrossRepository: false }] } } } }))
|
||||
|
||||
@@ -53,7 +53,10 @@ function fakeGh(check: GhOutput, ...mutations: Array<GhOutput | Thrown>): { run:
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50 })
|
||||
return new GitHubProvider(run, ['github.com'], {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
})
|
||||
}
|
||||
|
||||
function payload(field: string, value: unknown = { id: 'x' }): GhOutput {
|
||||
|
||||
@@ -6,7 +6,10 @@ import { GhTimeoutError, GhUnavailableError, type GhRunner } from '../src/gh.ts'
|
||||
|
||||
const ref = { repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 7 }
|
||||
const head = 'a'.repeat(40)
|
||||
const LIMITS = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50 }
|
||||
const LIMITS = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
const comment = { path: 'src/space name.ts', side: 'L' as const, startLine: 3, endLine: 5, body: 'Check `$(secret)`\n第二行' }
|
||||
const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment }
|
||||
const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' }
|
||||
|
||||
@@ -22,7 +22,9 @@ function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner
|
||||
|
||||
function provider(run: GhRunner, limits: Partial<GitHubLimits> = {}): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com'], {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50, ...limits,
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
...limits,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@ import { searchText, VIEWER_COUNT_QUERY, VIEWER_LIST_QUERY } from '../src/viewer
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner; calls: string[][] } {
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge-session/use-this-package:
|
||||
en: 732af52013e236ad
|
||||
zh: 18f25f12abd8e15b
|
||||
en: d0f77a3d598d292f
|
||||
zh: bb5b5436f956dd96
|
||||
/deepseek-ai-dsh-experimental-forge-session/understand-the-implementation:
|
||||
en: d0ba8f59ffcd625c
|
||||
zh: 1d89347f14e34701
|
||||
en: 36d45c65174011aa
|
||||
zh: 769b5b7b1cf12b39
|
||||
/deepseek-ai-dsh-experimental-forge-session/further-exploration:
|
||||
en: afd5ea387dc53920
|
||||
zh: 1f2d48bdd1abeef7
|
||||
|
||||
@@ -36,7 +36,7 @@ Mount the service with the forge registry, a provider, and the Session projectio
|
||||
|
||||
A provider registers the commands of its CLI with `ctx.forgeSession.registerCommands(rule)`, an effect on the calling fiber that returns its disposer; while forge-session runs, [forge-github](../forge-github/README.md) registers `gh` and [forge-gitlab](../forge-gitlab/README.md) registers `glab`. A rule names its executable, its creation subcommands, its reference subcommands and its raw API request subcommands, each group with the options it accepts, a regular expression for the change request page path, the JSON members that hold a reference command's own URL, and a `select` function that maps one parsed reference or API request command to a URL or to a read-only lookup command. Registration throws for a malformed rule and for a rule whose id or executable a live registration has. A rule classifies the same input the same way every time, and its registrant raises `version` whenever the rule classifies any command or output differently.
|
||||
|
||||
`ctx.forgeSession.changeRequests(session)` returns the visible bindings in first-recorded order. Each entry carries the URL, its `origin` (`created`, `referenced`, `discovered`, or `tracked`), the provider reference or `null` when no provider serves the URL, and the latest polling result or `null`. `watch(session, listener)` is an effect on the calling fiber: while a Session has a watcher, every visible binding that a provider serves is polled, and listeners receive the complete list after each later binding change, provider registration change, or polling result. Provider changes resynchronize existing watches, including URLs that were previously unserved. `track(session, url)` binds a URL under the provider's canonical form, or restores a dismissed binding, and throws when no provider recognizes the URL. `dismiss(session, url)` hides a visible binding; other URLs leave the log unchanged. `discoverBranch(session, remote, branch)` runs the lookup that follows a push for a branch on the remote at `remote` and resolves once it has recorded its bindings or failed; a remote that no provider serves changes nothing.
|
||||
`ctx.forgeSession.changeRequests(session)` returns the visible bindings in first-recorded order. Each entry carries the URL, its `origin` (`created`, `referenced`, `discovered`, or `tracked`), the provider reference or `null` when no provider serves the URL, and the latest polling result or `null`. `watch(session, listener, options)` is an effect on the calling fiber: while a Session has a watcher, every visible binding that a provider serves is polled for its snapshot, with the `options` of the Session's first watcher passed to `ctx.forge.watch`, and listeners receive the complete list after each later binding change, provider registration change, or polling result. Provider changes resynchronize existing watches, including URLs that were previously unserved. `track(session, url)` binds a URL under the provider's canonical form, or restores a dismissed binding, and throws when no provider recognizes the URL. `dismiss(session, url)` hides a visible binding; other URLs leave the log unchanged. `discoverBranch(session, remote, branch)` runs the lookup that follows a push for a branch on the remote at `remote` and resolves once it has recorded its bindings or failed; a remote that no provider serves changes nothing.
|
||||
|
||||
A `bash` or `pwsh` call binds evidence only from its first result, and only when the tool execution itself succeeded; the command's exit status does not matter. A `bash` or `pwsh` call inside a PTC program binds the same evidence from its `tool/ptc-dispatch` event, which logs the call's arguments with its settled outcome. A command containing a rule's creation subcommand, such as `gh pr create`, binds every change request page URL of that rule in its text output. A command containing a reference subcommand, such as `gh pr view`, binds, as `referenced`, the change request that the rule's `select` finds in a literal simple command, plus the URL its output prints for its own change request: a `url:` field or a URL alone on a line before the `--` line that starts a description, and the rule's JSON URL members. Links in a description or in other fields do not bind, and a command that also contains a creation subcommand binds its URLs as `created`. An API request subcommand, such as `glab api`, binds as `referenced` only the change request its request path names; its output is not read, since one request can list many change requests. A command containing `git push`, optionally with leading `-C`, `-c`, or long Git options, records each branch listed under a `To <remote>` line as created, updated, forced, or already up to date; rejected and deleted refs, new tags, and explicit refs outside `refs/heads/` are skipped. For each pushed branch whose remote a provider serves, the service runs `ctx.forge.findByHead` within `discoveryTimeoutMs` and appends a `discover` record for every returned change request that is not bound. Dismissed bindings remain bound and are skipped; only `track` restores them. Every push repeats the lookup; failures are logged as warnings. Closing a Session cancels its unfinished branch lookups without adding bindings. Reopening it does not repeat those lookups; another push, `discoverBranch`, or `track` can bind the change request. URLs that differ only in scheme, letter case, query, fragment, or trailing slashes name the same binding.
|
||||
|
||||
@@ -52,7 +52,7 @@ Binding actions are `plugin:forge-session/binding` records listed in the [experi
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The `forgeChangeRequests` projection keeps shell calls awaiting their first result, every binding with its dismissal state, and each pushed branch with the sequence number of the latest result that reported it. Pending calls are dropped at `turn/end`. Its client view, which the Session summary carries, is every binding with its URL, origin, and dismissal state in first-recorded order, and it keeps its reference while only pending calls or pushes change. The service reacts to a `tool/result` or `tool/ptc-dispatch` event by discovering exactly the pushes whose sequence number equals the event's, and refreshes watchers when the bindings array changes. Disposing the service aborts lookups and drops their results.
|
||||
The `forgeChangeRequests` projection keeps shell calls awaiting their first result, every binding with its dismissal state, and each pushed branch with the sequence number of the latest result that reported it. Pending calls are dropped at `turn/end`. Its client view, which the Session summary carries, is every binding with its URL, origin, and dismissal state in first-recorded order, and it keeps its reference while only pending calls or pushes change. The service reacts to a `tool/result` or `tool/ptc-dispatch` event by discovering exactly the pushes whose sequence number equals the event's, and refreshes watchers when the bindings array changes. For each such push it also calls `ctx.forge.expectChange` for the visible change requests in the pushed remote's repository, so a watched one is polled at once and at the active interval until its checks start. At `turn/end` of a turn that had a tool result, it calls `ctx.forge.refresh` for every visible change request with the age of the turn's last tool result as `maxAgeMs`, so a watched change request that a command of the turn may have merged, closed, or updated is polled unless a poll of it started after that result; a turn without a tool result polls nothing. Disposing the service aborts lookups and drops their results.
|
||||
|
||||
The projection's state version is `5 × 2^32` plus a 32-bit hash of the recognized rules' `id@version` pairs, so a checkpoint folded with other rules is discarded and the log folds again. A registration that changes the recognized rules releases the projection and registers it at the new version once the registrations of the same microtask have run, one re-registration at a time; each Session refolds its log with the new rules when next read, including commands that ran before the provider loaded, and watchers whose bindings changed are notified. Ending a registration leaves its rule recognized until the service restarts or another registration replaces its id or executable, so unloading providers, including at shutdown, leaves the checkpointed version unchanged; only live registrations run reference lookups. Each start registers the projection without rules, since providers register theirs once forge-session has started, and their registrations then re-register it once. A failed re-registration registers the projection again with the earlier rules and logs a warning; when that fails too, it logs an error, and clients see no bindings until the service restarts.
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ kind: "package-reference"
|
||||
|
||||
提供方通过 `ctx.forgeSession.registerCommands(rule)` 注册其 CLI 的命令;该调用是调用方 fiber 上的 effect,返回其 disposer。forge-session 运行期间,[forge-github](../forge-github/README.zh.md) 注册 `gh`,[forge-gitlab](../forge-gitlab/README.zh.md) 注册 `glab`。一条规则声明其可执行文件、创建子命令、引用子命令与原始 API 请求子命令(后两组各带其接受的选项)、匹配变更请求页面路径的正则表达式、存放引用命令自身 URL 的 JSON 成员,以及一个 `select` 函数:它把一条解析后的引用命令或 API 请求命令映射为一个 URL 或一条只读查询命令。规则格式不正确,或其 id 或可执行文件已被一项仍有效的注册占用时,注册抛错。规则对同一输入总是给出同样的分类;规则对任何命令或输出的分类发生变化时,注册方要提高 `version`。
|
||||
|
||||
`ctx.forgeSession.changeRequests(session)` 按首次记录的顺序返回可见的绑定。每一项包含 URL、其 `origin`(`created`、`referenced`、`discovered` 或 `tracked`)、提供方引用(没有提供方服务该 URL 时为 `null`)以及最近一次轮询结果(尚无结果时为 `null`)。`watch(session, listener)` 是调用方 fiber 上的 effect:Session 有监听方期间,提供方服务的每个可见绑定都会被轮询;此后每次绑定变化、提供方注册变化或轮询结果到达时,监听方都会收到完整列表。提供方变化会重新同步已有监听,包括此前没有提供方服务的 URL。`track(session, url)` 以提供方的规范形式绑定 URL,或恢复已隐藏的绑定;没有提供方识别该 URL 时抛错。`dismiss(session, url)` 隐藏一个可见绑定;其他 URL 不会改变日志。`discoverBranch(session, remote, branch)` 为位于 `remote` 远端的分支执行推送之后的那次查找,记录完绑定或失败后 resolve;没有提供方服务的远端不会带来任何变化。
|
||||
`ctx.forgeSession.changeRequests(session)` 按首次记录的顺序返回可见的绑定。每一项包含 URL、其 `origin`(`created`、`referenced`、`discovered` 或 `tracked`)、提供方引用(没有提供方服务该 URL 时为 `null`)以及最近一次轮询结果(尚无结果时为 `null`)。`watch(session, listener, options)` 是调用方 fiber 上的 effect:Session 有监听方期间,提供方服务的每个可见绑定都会被轮询以读取快照,Session 第一个监听方的 `options` 会传给 `ctx.forge.watch`;此后每次绑定变化、提供方注册变化或轮询结果到达时,监听方都会收到完整列表。提供方变化会重新同步已有监听,包括此前没有提供方服务的 URL。`track(session, url)` 以提供方的规范形式绑定 URL,或恢复已隐藏的绑定;没有提供方识别该 URL 时抛错。`dismiss(session, url)` 隐藏一个可见绑定;其他 URL 不会改变日志。`discoverBranch(session, remote, branch)` 为位于 `remote` 远端的分支执行推送之后的那次查找,记录完绑定或失败后 resolve;没有提供方服务的远端不会带来任何变化。
|
||||
|
||||
`bash` 或 `pwsh` 调用只从其第一个结果中提取证据,且仅当工具执行本身成功时才提取;命令的退出状态不影响结果。PTC 程序内的 `bash` 或 `pwsh` 调用从其 `tool/ptc-dispatch` 事件提取同样的证据,该事件记录调用的参数及其结算结果。包含某条规则创建子命令(如 `gh pr create`)的命令,会绑定其文本输出中该规则的每个变更请求页面 URL。包含引用子命令(如 `gh pr view`)的命令以 `referenced` 绑定:规则的 `select` 从字面量简单命令中找到的变更请求,以及输出为它所操作的变更请求本身打印的 URL,即 `url:` 字段、开始描述正文的 `--` 行之前单独成行的 URL,以及规则声明的 JSON URL 成员。描述正文或其他字段里的链接不会绑定;同一命令里还包含创建子命令时,其 URL 以 `created` 绑定。API 请求子命令(如 `glab api`)只以 `referenced` 绑定其请求路径指向的变更请求,不读取输出,因为一次请求可能列出许多变更请求。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To <remote>` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `refs/heads/` 之外的引用会被跳过。对远端由提供方服务的每个被推送分支,服务在 `discoveryTimeoutMs` 内调用 `ctx.forge.findByHead`,并为返回的每个尚未绑定的变更请求追加一条 `discover` 记录。已隐藏的绑定仍视为已绑定而被跳过;只有 `track` 会恢复它们。每次推送都会重新查找;失败记录为警告日志。关闭 Session 会取消其未完成的分支查找,不追加绑定。重新打开不会补做这些查找;可再次推送、调用 `discoverBranch` 或用 `track` 绑定变更请求。仅在协议、大小写、查询、片段或末尾斜杠上不同的 URL 指向同一个绑定。
|
||||
|
||||
@@ -52,7 +52,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
`forgeChangeRequests` 投影保存等待第一个结果的 shell 调用、每个绑定及其隐藏状态,以及每个被推送分支和最近一次报告它的结果的序号。`turn/end` 会丢弃仍在等待的调用。它的客户端视图随 Session 摘要下发,按首次记录的顺序列出每个绑定的 URL、来源与隐藏状态;只有等待中的调用或推送变化时,视图保持同一引用。服务收到 `tool/result` 或 `tool/ptc-dispatch` 事件时,只对序号等于该事件序号的推送执行发现,并在绑定数组变化时刷新监听方。销毁服务会中止查找并丢弃其结果。
|
||||
`forgeChangeRequests` 投影保存等待第一个结果的 shell 调用、每个绑定及其隐藏状态,以及每个被推送分支和最近一次报告它的结果的序号。`turn/end` 会丢弃仍在等待的调用。它的客户端视图随 Session 摘要下发,按首次记录的顺序列出每个绑定的 URL、来源与隐藏状态;只有等待中的调用或推送变化时,视图保持同一引用。服务收到 `tool/result` 或 `tool/ptc-dispatch` 事件时,只对序号等于该事件序号的推送执行发现,并在绑定数组变化时刷新监听方。对每个这样的推送,它还为被推送远端所在仓库里的可见变更请求调用 `ctx.forge.expectChange`,所以被监听的变更请求会立即轮询,并按活跃间隔轮询到检查开始为止。有过工具结果的回合在 `turn/end` 时,它为每个可见的变更请求调用 `ctx.forge.refresh`,以该回合最后一个工具结果距今的时间作为 `maxAgeMs`;所以回合里的命令可能合并、关闭或更新过的被监听变更请求会被轮询,除非它的某次轮询开始于那个结果之后。没有工具结果的回合不轮询。销毁服务会中止查找并丢弃其结果。
|
||||
|
||||
投影的状态版本为 `5 × 2^32` 加上已识别规则 `id@version` 对的 32 位哈希,因此按其他规则折叠的检查点会被丢弃,日志重新折叠。改变已识别规则的注册会在同一微任务内的注册都执行完后,释放投影并以新版本重新注册,同一时间只进行一次重新注册;每个 Session 下次被读取时用新规则重新折叠其日志,包括提供方加载之前执行过的命令,绑定发生变化的监听方会收到通知。注册结束后,其规则仍被识别,直到服务重启或另一项注册替换其 id 或可执行文件,因此卸载提供方(包括关闭时)不会改变已检查点的版本;只有仍有效的注册会执行引用反查。每次启动时投影先在没有规则的情况下注册,因为提供方要等 forge-session 启动后才注册各自的规则,它们的注册随后使投影重新注册一次。重新注册失败时,用此前的规则再次注册投影并记录警告;若这也失败,则记录错误,服务重启前客户端看不到绑定。
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { Context, FiberState, Service } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestKey, ChangeRequestRef, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestWatchOptions, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { appendPluginRecord, pluginRecordOf } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
@@ -33,6 +33,8 @@ declare module '@deepseek-ai/cordis' {
|
||||
interface SessionWatch {
|
||||
readonly session: Session
|
||||
readonly listeners: Set<SessionChangeRequestsListener>
|
||||
/** How fresh a status the Session's first watcher asked for, which every forge watch of the Session asks for. */
|
||||
readonly options: ChangeRequestWatchOptions
|
||||
/** Projection bindings that `forgeWatches` and the last notification reflect. */
|
||||
bindings: readonly BindingState[]
|
||||
readonly forgeWatches: Map<ChangeRequestKey, () => void>
|
||||
@@ -61,6 +63,8 @@ export class ForgeSessionService extends Service {
|
||||
private readonly watches = new Map<Session, SessionWatch>()
|
||||
private readonly discoveries = new Set<Promise<void>>()
|
||||
private readonly sessionLifetimes = new WeakMap<Session, AbortController>()
|
||||
/** Epoch milliseconds of the latest tool result of each Session's current turn. */
|
||||
private readonly toolResults = new WeakMap<Session, number>()
|
||||
private readonly lifetime = new AbortController()
|
||||
/** Rules whose registration is live. */
|
||||
private readonly rules = new Map<string, ForgeCommandRule>()
|
||||
@@ -184,19 +188,21 @@ export class ForgeSessionService extends Service {
|
||||
/**
|
||||
* Watch a Session's visible change requests as an effect on the calling
|
||||
* fiber. Every visible change request that a provider recognizes is polled
|
||||
* through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* for its snapshot through `ctx.forge` while the Session has a watcher. Listeners receive the
|
||||
* complete list after each later binding or provider change, or polling result; read the
|
||||
* current list with {@link changeRequests}. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param session - Session to watch.
|
||||
* @param listener - receives the complete visible list.
|
||||
* @param options - when the Session's first watcher needs a status newer than the latest one; a later watcher's
|
||||
* options change nothing.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(session: Session, listener: SessionChangeRequestsListener): () => void {
|
||||
watch(session: Session, listener: SessionChangeRequestsListener, options: ChangeRequestWatchOptions = {}): () => void {
|
||||
const dispose = this.ctx.effect(() => {
|
||||
let watch = this.watches.get(session)
|
||||
if (watch === undefined) {
|
||||
watch = { session, listeners: new Set(), bindings: this.state(session).bindings, forgeWatches: new Map() }
|
||||
watch = { session, listeners: new Set(), options, bindings: this.state(session).bindings, forgeWatches: new Map() }
|
||||
this.watches.set(session, watch)
|
||||
this.sync(watch)
|
||||
}
|
||||
@@ -310,12 +316,22 @@ export class ForgeSessionService extends Service {
|
||||
return entries
|
||||
}
|
||||
|
||||
/** Discover change requests for this result's pushes and refresh watchers after binding changes. */
|
||||
/**
|
||||
* Discover change requests for this result's pushes, refresh watchers after binding changes, and poll a Session's
|
||||
* change requests once a turn that ran a tool ends.
|
||||
*/
|
||||
private react(session: Session, event: SessionEvent): void {
|
||||
if (event.type === 'turn/end') {
|
||||
this.turnEnded(session)
|
||||
return
|
||||
}
|
||||
if (event.type !== 'tool/result' && event.type !== 'tool/ptc-dispatch' && pluginRecordOf(event)?.type !== BINDING_RECORD) return
|
||||
if (event.type === 'tool/result' || event.type === 'tool/ptc-dispatch') this.toolResults.set(session, Date.now())
|
||||
const state = this.state(session)
|
||||
for (const push of state.pushes) {
|
||||
if (push.seq === event.seq) void this.discover(session, push.remote, push.branch)
|
||||
if (push.seq !== event.seq) continue
|
||||
this.expectChanges(state.bindings, push.remote)
|
||||
void this.discover(session, push.remote, push.branch)
|
||||
}
|
||||
const watch = this.watches.get(session)
|
||||
if (watch === undefined || watch.bindings === state.bindings) return
|
||||
@@ -324,6 +340,30 @@ export class ForgeSessionService extends Service {
|
||||
this.notify(watch)
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll the watched change requests a Session shows once a turn of it that ran a tool ended, unless a poll of them
|
||||
* started after the turn's last tool result: a command of the turn may have merged, closed, or updated one.
|
||||
*/
|
||||
private turnEnded(session: Session): void {
|
||||
const since = this.toolResults.get(session)
|
||||
if (since === undefined) return
|
||||
this.toolResults.delete(session)
|
||||
const maxAgeMs = Date.now() - since
|
||||
for (const { ref } of this.entries(this.state(session).bindings)) {
|
||||
if (ref !== null) this.home.forge.refresh(ref, { maxAgeMs })
|
||||
}
|
||||
}
|
||||
|
||||
/** Announce to the registry that the visible change requests in the repository of a pushed remote are about to change. */
|
||||
private expectChanges(bindings: readonly BindingState[], remote: string): void {
|
||||
const repository = this.home.forge.repositoryFromRemote(remote)
|
||||
if (repository === undefined) return
|
||||
for (const { ref } of this.entries(bindings)) {
|
||||
// Keys compare repositories without case.
|
||||
if (ref !== null && changeRequestKey(ref) === changeRequestKey({ repository, number: ref.number })) this.home.forge.expectChange(ref)
|
||||
}
|
||||
}
|
||||
|
||||
/** Poll exactly the visible change requests that a provider recognizes. */
|
||||
private sync(watch: SessionWatch): void {
|
||||
const wanted = new Map<ChangeRequestKey, ChangeRequestRef>()
|
||||
@@ -336,7 +376,7 @@ export class ForgeSessionService extends Service {
|
||||
watch.forgeWatches.delete(key)
|
||||
}
|
||||
for (const [key, ref] of wanted) {
|
||||
if (!watch.forgeWatches.has(key)) watch.forgeWatches.set(key, this.home.forge.watch(ref, () => { this.notify(watch) }))
|
||||
if (!watch.forgeWatches.has(key)) watch.forgeWatches.set(key, this.home.forge.watch(ref, () => { this.notify(watch) }, watch.options))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -203,6 +203,16 @@ const turns = new WeakMap<Session, number>()
|
||||
* @param calls - shell calls with their rendered results.
|
||||
*/
|
||||
export function shellTurn(session: Session, calls: readonly ShellCall[]): void {
|
||||
startShellTurn(session, calls)()
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a turn in which the model runs `calls` in a single step, up to their results.
|
||||
* @param session - live Session receiving the events.
|
||||
* @param calls - shell calls with their rendered results.
|
||||
* @returns appends the end of the step and of the turn.
|
||||
*/
|
||||
export function startShellTurn(session: Session, calls: readonly ShellCall[]): () => void {
|
||||
const turn = (turns.get(session) ?? 0) + 1
|
||||
turns.set(session, turn)
|
||||
const step = 1
|
||||
@@ -228,8 +238,10 @@ export function shellTurn(session: Session, calls: readonly ShellCall[]): void {
|
||||
message: createToolResultMessage({ callId: brandString<ToolCallId>(call.callId), content: [{ type: 'text', text: call.output }], isError: call.isError ?? false }),
|
||||
}, { surfaceOp: 'append' })
|
||||
}
|
||||
session.append('step/end', { turn, step })
|
||||
session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
||||
return () => {
|
||||
session.append('step/end', { turn, step })
|
||||
session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
||||
}
|
||||
}
|
||||
|
||||
/** One shell call inside a program, the text its settled dispatch carries, and its tool arguments. */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import type { Mock } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import ForgeService from '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -10,7 +10,9 @@ import { compileRules } from '../src/commands.ts'
|
||||
import ForgeSessionService from '../src/index.ts'
|
||||
import type { Config, ForgeCommandRule, SessionChangeRequest, SessionChangeRequestsListener } from '../src/index.ts'
|
||||
import { forgeChangeRequestsProjection } from '../src/projection.ts'
|
||||
import { bench, demo, FakeProvider, programTurn, pull, pullUrl, pushOutput, settled, shellTurn, snapshot, TEA_COMMANDS } from './fixtures.ts'
|
||||
import {
|
||||
bench, demo, FakeProvider, programTurn, pull, pullUrl, pushOutput, settled, shellTurn, snapshot, startShellTurn, TEA_COMMANDS,
|
||||
} from './fixtures.ts'
|
||||
import type { Bench } from './fixtures.ts'
|
||||
|
||||
const contexts: Context[] = []
|
||||
@@ -321,6 +323,25 @@ describe('forgeSession watch', () => {
|
||||
return listener.mock.lastCall?.[0] ?? []
|
||||
}
|
||||
|
||||
it('asks for a status no older than its first watcher accepts, for each change request it polls', async () => {
|
||||
const { ctx, provider, session } = await open()
|
||||
create(session, 'create', pullUrl(1))
|
||||
const other = ctx.sessions.create()
|
||||
create(other, 'other', pullUrl(1))
|
||||
// Another watcher read the status before the Sessions are watched.
|
||||
const stop = ctx.forge.watch(pull(1), () => {})
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1]]) })
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
|
||||
ctx.forgeSession.watch(other, () => {})
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(provider.fetches).toEqual([[1]])
|
||||
|
||||
ctx.forgeSession.watch(session, () => {}, { maxAgeMs: 1 })
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1], [1]]) })
|
||||
stop()
|
||||
})
|
||||
|
||||
it('polls visible change requests and notifies after results and binding changes', async () => {
|
||||
const { ctx, provider, session } = await open()
|
||||
create(session, 'create', pullUrl(1))
|
||||
@@ -411,6 +432,62 @@ describe('forgeSession watch', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgeSession polls after commands', () => {
|
||||
const UNSERVED = 'https://github.com/octo/demo/pull/5'
|
||||
const pause = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms))
|
||||
|
||||
it('announces a change of the shown change requests in the repository a push went to', async () => {
|
||||
const { ctx, session } = await open()
|
||||
create(session, 'one', pullUrl(1))
|
||||
create(session, 'elsewhere', 'https://fake.test/other/repo/pull/2')
|
||||
create(session, 'unserved', UNSERVED)
|
||||
create(session, 'hidden', pullUrl(3))
|
||||
ctx.forgeSession.dismiss(session, pullUrl(3))
|
||||
const announced = vi.spyOn(ForgeService.prototype, 'expectChange')
|
||||
onTestFinished(() => { announced.mockRestore() })
|
||||
|
||||
push(session, 'push', 'feat')
|
||||
push(session, 'mirror', 'feat', 'unknown.test:octo/demo.git')
|
||||
|
||||
expect(announced.mock.calls).toEqual([[pull(1)]])
|
||||
})
|
||||
|
||||
it('polls the change requests a Session shows once a turn that ran a tool ends', async () => {
|
||||
const { ctx, provider, session } = await open()
|
||||
create(session, 'one', pullUrl(1))
|
||||
create(session, 'unserved', UNSERVED)
|
||||
ctx.forgeSession.watch(session, () => {})
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1]]) })
|
||||
await pause(5)
|
||||
|
||||
shellTurn(session, [{ callId: 'merge', command: 'gh pr merge 1 --squash', output: '' }])
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1], [1]]) })
|
||||
|
||||
// A turn without a tool result changed nothing on the code host.
|
||||
await pause(5)
|
||||
session.append('turn/start', { turn: 90 })
|
||||
session.append('turn/end', { turn: 90, reason: { kind: 'completed' } })
|
||||
await pause(20)
|
||||
expect(provider.fetches).toEqual([[1], [1]])
|
||||
})
|
||||
|
||||
it('polls nothing at the end of a turn when a poll started after its last tool result', async () => {
|
||||
const { ctx, provider, session } = await open()
|
||||
create(session, 'one', pullUrl(1))
|
||||
ctx.forgeSession.watch(session, () => {})
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1]]) })
|
||||
|
||||
const end = startShellTurn(session, [{ callId: 'merge', command: 'gh pr merge 1 --squash', output: '' }])
|
||||
await pause(5)
|
||||
ctx.forge.refresh(pull(1))
|
||||
await vi.waitFor(() => { expect(provider.fetches).toEqual([[1], [1]]) })
|
||||
end()
|
||||
await pause(20)
|
||||
|
||||
expect(provider.fetches).toEqual([[1], [1]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgeSession command rules', () => {
|
||||
const version = (ctx: Context, session: Session): number | undefined =>
|
||||
ctx.sessionProjections.checkpoint(session).forgeChangeRequests?.ver
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge/use-this-package:
|
||||
en: 521ff8f9951fd69d
|
||||
zh: 9d6f4781b996efa4
|
||||
en: efbd1b5d43e3f0df
|
||||
zh: 0eadf1c3c60a1450
|
||||
/deepseek-ai-dsh-experimental-forge/understand-the-implementation:
|
||||
en: e193cb547c47069b
|
||||
zh: faa517522402ea41
|
||||
en: 9d4bcb122585dbf4
|
||||
zh: 946bd5a110961332
|
||||
/deepseek-ai-dsh-experimental-forge/further-exploration:
|
||||
en: bb13125144d413d5
|
||||
zh: a6832dad7a093bfe
|
||||
|
||||
@@ -50,9 +50,11 @@ Providers may implement `rerunChecks(ref, { headSha }, signal)`, which reruns th
|
||||
|
||||
`fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle.
|
||||
|
||||
`ctx.forge.watch(ref, listener)` is also an effect. The first watcher of a change request polls it at once; `latest(ref)` returns the most recent result. Each forge has at most one polling fetch in flight, and that fetch includes every due change request of the forge. An open change request is polled every `activeIntervalMs` while checks are pending or mergeability is unknown, and every `idleIntervalMs` otherwise. Closed change requests use `idleIntervalMs` to detect reopening; merged requests stop automatic polling. `refresh(ref)` polls a watched change request at once, including after a terminal state; if a fetch is already in flight for its forge, another fetch starts immediately after it settles. A failed read repeats after `activeIntervalMs` doubled for each consecutive failure, up to `maxBackoffMs`, which must be at least `activeIntervalMs`. Unregistering a provider settles its watched change requests as `unavailable`. Polling stops when the last watcher leaves. The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge) lists the defaults.
|
||||
`ctx.forge.watch(ref, listener, options)` is also an effect. It watches the snapshot of a change request: the first snapshot watcher polls it at once, and a later one does when it passes `maxAgeMs`, the latest result is older, and no snapshot poll is in flight. `latest(ref)` returns the most recent snapshot result, which stays while only brief watchers remain. `ctx.forge.watchBrief(ref, listener, known)` watches the brief of a change request: its title, state, draft flag, mergeability, review decision, and combined check outcome. While a change request has a snapshot watcher, polls read its snapshot and brief watchers receive the brief it holds. Otherwise polls read its brief through the provider's `fetchBriefs`, or its snapshot when the provider has none. The first brief watcher of an unwatched change request polls it at once, unless it passes the state it already knows as `known`; the first poll then waits as it would after a read at `known.fetchedAt`, and a merged change request is not polled. Each forge has at most one snapshot fetch and one brief fetch in flight. Each includes every due change request of the forge at its level, and those past the midpoint of the wait after their latest status, so change requests that became due at different times come to share one fetch. An open change request is polled every `activeIntervalMs` while checks are pending, and every `idleIntervalMs` otherwise. A status that first reports an unknown mergeability is followed by one poll after `activeIntervalMs`; a change request that reports it again waits `idleIntervalMs`, because some never report another value. Closed change requests use `idleIntervalMs` to detect reopening; merged requests stop automatic polling. `refresh(ref)` polls a watched change request at once, including after a terminal state; if a fetch at its level is already in flight for its forge, another fetch starts immediately after it settles. `refresh(ref, { maxAgeMs })` asks for a status no older than `maxAgeMs`: it leaves alone a change request whose latest poll at either level, in flight or settled, started within `maxAgeMs`, and a merged one. `expectChange(ref)` announces that a watched change request is about to change, as after a push to its head branch: it is polled at once and then every `activeIntervalMs` until a status reports running checks or a closed or merged change request, for at most `idleIntervalMs`. A failed read repeats after `activeIntervalMs` doubled for each consecutive failure, up to `maxBackoffMs`, which must be at least `activeIntervalMs`; the change request joins no other fetch before that. A failed brief read reaches brief watchers only and leaves `latest(ref)` unchanged; a failed snapshot read reaches both kinds of watchers. Unregistering a provider settles its watched change requests as `unavailable`. Polling stops when the last watcher of either kind leaves. The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge) lists the defaults.
|
||||
|
||||
Reaching `fetchTimeoutMs` aborts the fetch signal with `FORGE_FETCH_TIMEOUT`. Providers must stop their work and settle when the signal aborts; rejected fetches become `unavailable` failures. A provider that ignores cancellation can stall polling and service disposal.
|
||||
A provider may name `snapshotBatchSize` and `briefBatchSize`, the most change requests of one host that one polling call of `fetch` and of `fetchBriefs` reads; each must be a positive safe integer, or registration is refused. A fetch then calls the provider once per that many due change requests of a host, compared without case, one call after another, and delivers the results of a call when it returns, so a call that fails or outlives its deadline fails only its own change requests. Without a size, one call reads every due change request of the forge. A change request that loses its last watcher while it waits for its call is not read, and one whose watchers changed what its polls read while it waited is read by the fetch of that level.
|
||||
|
||||
Each provider call has its own `fetchTimeoutMs` deadline. Reaching it aborts the call's signal with `FORGE_FETCH_TIMEOUT`. Providers must stop their work and settle when the signal aborts; rejected calls become `unavailable` failures of the change requests they read. A provider that ignores cancellation can stall polling and service disposal.
|
||||
|
||||
Providers may implement `submitReview` to publish a line comment or a completed review at an explicit head commit. The registry returns unsupported when that capability is absent and refreshes watched status after a submission. Successful writes return their web URL; failures distinguish changed heads, refusals, and unknown outcomes. Callers must reconcile unknown outcomes before another submission. Comments a user keeps for a later review go to the code host's pending review through `writeReview`, not to the polling registry.
|
||||
|
||||
@@ -70,7 +72,7 @@ Providers may declare `viewer`, the hosts they list change requests on for the s
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
One timer covers all watched change requests. When it fires, the service groups due change requests by forge and starts one batched provider fetch per idle forge. A listener that throws is logged and skipped. Disposing the service aborts in-flight fetches and waits for them to settle.
|
||||
One timer covers all watched change requests. When it fires, the service groups due change requests by forge and by what their polls read, adds to a group the change requests past the midpoint of their wait, and starts one batched provider fetch for each group whose earlier fetch has settled. A listener that throws is logged and skipped. Disposing the service aborts in-flight fetches and waits for them to settle.
|
||||
|
||||
| Source | Responsibility |
|
||||
|---|---|
|
||||
|
||||
@@ -50,9 +50,11 @@ kind: "package-reference"
|
||||
|
||||
`fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。
|
||||
|
||||
`ctx.forge.watch(ref, listener)` 同样是 effect。变更请求的第一个监听方会立即触发轮询;`latest(ref)` 返回最近一次结果。每个 forge 同时最多只有一次轮询读取在进行,这次读取包含该 forge 所有到期的变更请求。打开状态的变更请求在检查未完成或可合并性未知时每 `activeIntervalMs` 轮询一次,否则每 `idleIntervalMs` 轮询一次。已关闭的变更请求按 `idleIntervalMs` 轮询以检测重新打开;已合并的停止自动轮询。`refresh(ref)` 立即轮询一个被监听的变更请求,已结束的也包括在内;该 forge 已有读取在进行时,等待其结束后立即再读一次。读取失败后,重试间隔为 `activeIntervalMs` 按连续失败次数翻倍,最长 `maxBackoffMs`;该值必须大于或等于 `activeIntervalMs`。注销提供方会让其被监听的变更请求以 `unavailable` 结束。最后一个监听方离开后轮询停止。默认值见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge)。
|
||||
`ctx.forge.watch(ref, listener, options)` 同样是 effect。它监听变更请求的快照:第一个快照监听方会立即触发轮询;之后加入的监听方传入 `maxAgeMs`、最近一次结果比它更旧、且没有快照轮询在进行时,也会立即触发。`latest(ref)` 返回最近一次快照结果;只剩简报监听方时,这个结果仍然保留。`ctx.forge.watchBrief(ref, listener, known)` 监听变更请求的简报:标题、状态、草稿标记、可合并性、评审结论与检查汇总结果。变更请求有快照监听方时,轮询读取快照,简报监听方收到快照里的简报。否则轮询通过提供方的 `fetchBriefs` 读取简报;提供方没有该方法时读取快照。尚无监听方的变更请求迎来第一个简报监听方时会立即轮询,除非它用 `known` 传入自己已知的状态;这时首次轮询按“在 `known.fetchedAt` 读过一次”来安排,已合并的变更请求不轮询。每个 forge 同时最多有一次快照读取和一次简报读取在进行。每次读取包含该 forge 在对应层级上所有到期的变更请求,以及距上一次状态的等待已过半的变更请求,所以在不同时刻到期的变更请求会逐渐共用一次读取。打开状态的变更请求在检查未完成时每 `activeIntervalMs` 轮询一次,否则每 `idleIntervalMs` 轮询一次。状态第一次报告可合并性未知时,`activeIntervalMs` 后再轮询一次;再次报告未知的变更请求等待 `idleIntervalMs`,因为有些变更请求不会再报告其他值。已关闭的变更请求按 `idleIntervalMs` 轮询以检测重新打开;已合并的停止自动轮询。`refresh(ref)` 立即轮询一个被监听的变更请求,已结束的也包括在内;该 forge 在同一层级已有读取在进行时,等待其结束后立即再读一次。`refresh(ref, { maxAgeMs })` 要求不早于 `maxAgeMs` 的状态:任一层级最近一次轮询(正在进行或已结束)在 `maxAgeMs` 之内开始的变更请求不触动,已合并的也不触动。`expectChange(ref)` 预告一个被监听的变更请求即将变化,例如它的 head 分支刚被推送:立即轮询一次,之后每 `activeIntervalMs` 轮询一次,直到状态报告检查正在运行、或变更请求已关闭或已合并为止,最长持续 `idleIntervalMs`。读取失败后,重试间隔为 `activeIntervalMs` 按连续失败次数翻倍,最长 `maxBackoffMs`;该值必须大于或等于 `activeIntervalMs`;在此之前该变更请求不加入其他读取。简报读取失败只通知简报监听方,`latest(ref)` 不变;快照读取失败会通知两类监听方。注销提供方会让其被监听的变更请求以 `unavailable` 结束。两类监听方都离开后轮询停止。默认值见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge)。
|
||||
|
||||
达到 `fetchTimeoutMs` 时,读取信号会以 `FORGE_FETCH_TIMEOUT` 中止。提供方必须在信号中止时停止工作并结束请求;被拒绝的读取会转为 `unavailable` 失败。忽略取消的提供方可能阻塞轮询和服务销毁。
|
||||
提供方可以声明 `snapshotBatchSize` 与 `briefBatchSize`,即一次 `fetch` 轮询调用和一次 `fetchBriefs` 轮询调用最多读取同一主机的多少个变更请求;两者都必须是正安全整数,否则注册被拒绝。这时一次读取按主机(不区分大小写)对到期的变更请求分组,每这么多个调用提供方一次,依次调用,并在每次调用返回时发布它的结果;所以某次调用失败或超过时限时,只有它读取的变更请求失败。没有声明大小时,一次调用读取该 forge 所有到期的变更请求。等待调用期间失去最后一个监听方的变更请求不再读取;等待期间监听方改变了轮询读取内容的变更请求,由对应层级的读取来读。
|
||||
|
||||
每次提供方调用都有自己的 `fetchTimeoutMs` 时限。达到时限时,该调用的信号会以 `FORGE_FETCH_TIMEOUT` 中止。提供方必须在信号中止时停止工作并结束请求;被拒绝的调用会转为它所读取的变更请求的 `unavailable` 失败。忽略取消的提供方可能阻塞轮询和服务销毁。
|
||||
|
||||
provider 可以实现 `submitReview`,在指定的 head 提交上发布行内评论或完整评审。未实现该能力时,注册表返回不支持;提交结束后会刷新受关注的状态。成功的写操作返回网页 URL;失败区分 head 变化、明确拒绝与结果不明。调用方必须先核对结果不明的操作,再次提交。用户留待之后一起提交的评论通过 `writeReview` 写入代码托管平台的待提交评审,不由轮询注册表保存。
|
||||
|
||||
@@ -70,7 +72,7 @@ provider 可以实现 `submitReview`,在指定的 head 提交上发布行内
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
一个定时器覆盖所有被监听的变更请求。定时器触发时,服务按 forge 对到期的变更请求分组,并为每个空闲的 forge 发起一次批量读取。抛错的监听方会被记录日志并跳过。销毁服务会中止进行中的读取,并等待它们结束。
|
||||
一个定时器覆盖所有被监听的变更请求。定时器触发时,服务按 forge 和轮询读取的内容对到期的变更请求分组,把等待已过半的变更请求加入对应分组,并为上一次读取已结束的每个分组发起一次批量读取。抛错的监听方会被记录日志并跳过。销毁服务会中止进行中的读取,并等待它们结束。
|
||||
|
||||
| 源码 | 职责 |
|
||||
|---|---|
|
||||
|
||||
@@ -4,10 +4,11 @@ import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { changeRequestKey } from './keys.ts'
|
||||
import { nextPollDelay } from './schedule.ts'
|
||||
import { backoffDelay, nextPollDelay } from './schedule.ts'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestDescription, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot,
|
||||
ChangeRequestUpdate, Config,
|
||||
BranchUpdateRequest, ChangeRequestBrief, ChangeRequestBriefListener, ChangeRequestBriefUpdate, ChangeRequestDescription, ChangeRequestKey,
|
||||
ChangeRequestKnownState, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ChangeRequestWatchOptions,
|
||||
Config,
|
||||
ForgeCommitList, ForgeActionFailure, ForgeDescription, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest,
|
||||
ForgeReviewData,
|
||||
ForgeReviewChange, ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
|
||||
@@ -42,7 +43,19 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
type FetchResults = ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>
|
||||
/** What a poll reads: the brief of a change request, or the snapshot that holds it. */
|
||||
type StatusLevel = 'brief' | 'snapshot'
|
||||
|
||||
/** The results of one provider read, by what the provider returned. */
|
||||
type Reading =
|
||||
| { readonly kind: 'snapshot'; readonly results: ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure> }
|
||||
| { readonly kind: 'brief'; readonly results: ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure> }
|
||||
|
||||
/** The settled result of one poll of a watch; a failure names the level the poll read at. */
|
||||
type Outcome =
|
||||
| { readonly snapshot: ChangeRequestSnapshot }
|
||||
| { readonly brief: ChangeRequestBrief }
|
||||
| { readonly failure: ForgeFailure; readonly level: StatusLevel }
|
||||
|
||||
interface Registration {
|
||||
readonly provider: ForgeProvider
|
||||
@@ -53,10 +66,27 @@ interface Registration {
|
||||
interface Watch {
|
||||
readonly key: ChangeRequestKey
|
||||
readonly ref: ChangeRequestRef
|
||||
/** Watchers of the snapshot; polls read the snapshot while there is one, and the brief otherwise. */
|
||||
readonly listeners: Set<ChangeRequestListener>
|
||||
/** Watchers of the brief, which every poll result reaches. */
|
||||
readonly briefListeners: Set<ChangeRequestBriefListener>
|
||||
/** Result of the latest snapshot poll; it stays while only brief watchers remain. */
|
||||
latest: ChangeRequestUpdate | undefined
|
||||
/** Epoch milliseconds of the next poll; undefined while in flight or after a terminal state. */
|
||||
dueAt: number | undefined
|
||||
/**
|
||||
* Epoch milliseconds from which a poll of the same lane also reads this change request: the midpoint of the wait
|
||||
* after a status. Undefined after a failure, whose backoff the change request waits out in full.
|
||||
*/
|
||||
joinAt: number | undefined
|
||||
/** Level of the poll in flight, when there is one. */
|
||||
reading: StatusLevel | undefined
|
||||
/** Epoch milliseconds when the latest poll at either level started, or when the state a brief watcher knew was read. */
|
||||
polledAt: number | undefined
|
||||
/** Whether the latest status reported an unknown mergeability. */
|
||||
unknownMergeability: boolean
|
||||
/** Epoch milliseconds until which an announced change keeps polls at the active interval; undefined without one. */
|
||||
expectingUntil: number | undefined
|
||||
failures: number
|
||||
/** Head commit whose `stale` diff or review read last polled at once, so further stale reads at it wait for the regular poll. */
|
||||
staleHead: string | undefined
|
||||
@@ -64,13 +94,18 @@ interface Watch {
|
||||
|
||||
/**
|
||||
* Registry of forge providers. Watchers of one change request share a single
|
||||
* polling loop; each forge has at most one fetch in flight, which batches
|
||||
* every due change request of that forge.
|
||||
* polling loop, which reads its snapshot while a snapshot watcher remains and
|
||||
* its brief otherwise. Each forge has at most one snapshot fetch and one brief
|
||||
* fetch in flight; each batches every due change request of that forge at its
|
||||
* level, and those past the midpoint of the wait after a status, so change
|
||||
* requests that became due at different times come to share one fetch. A fetch
|
||||
* calls a provider that names a batch size once per that many change requests
|
||||
* of a host, and settles the results of each call when it returns.
|
||||
*/
|
||||
export class ForgeService extends Service {
|
||||
static Config: z<Config> = z.object({
|
||||
activeIntervalMs: z.number().default(30_000),
|
||||
idleIntervalMs: z.number().default(120_000),
|
||||
activeIntervalMs: z.number().default(15_000),
|
||||
idleIntervalMs: z.number().default(60_000),
|
||||
maxBackoffMs: z.number().default(600_000),
|
||||
fetchTimeoutMs: z.number().default(30_000),
|
||||
})
|
||||
@@ -78,6 +113,7 @@ export class ForgeService extends Service {
|
||||
private readonly config: Required<Config>
|
||||
private readonly providers = new Map<string, Registration>()
|
||||
private readonly watches = new Map<ChangeRequestKey, Watch>()
|
||||
/** Lanes with a fetch in flight, as {@link laneOf} names them. */
|
||||
private readonly fetching = new Set<string>()
|
||||
private readonly pending = new Set<Promise<void>>()
|
||||
private readonly lifetime = new AbortController()
|
||||
@@ -120,11 +156,18 @@ export class ForgeService extends Service {
|
||||
* results from the withdrawn registration are discarded.
|
||||
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case, and
|
||||
* when the provider names a batch size that is not a positive safe integer.
|
||||
*/
|
||||
register(provider: ForgeProvider): () => Promise<void> {
|
||||
const dispose = this.ctx.effect(() => {
|
||||
if (this.providers.has(provider.forge)) throw new Error(`forge: a provider for "${provider.forge}" is already registered`)
|
||||
for (const key of ['snapshotBatchSize', 'briefBatchSize'] as const) {
|
||||
const size = provider[key]
|
||||
if (size !== undefined && (!Number.isSafeInteger(size) || size <= 0)) {
|
||||
throw new Error(`forge: ${key} of the "${provider.forge}" provider must be a positive safe integer`)
|
||||
}
|
||||
}
|
||||
for (const { provider: other } of this.providers.values()) {
|
||||
const taken = new Set(other.hosts.map(host => host.toLowerCase()))
|
||||
const host = provider.hosts.find(candidate => taken.has(candidate.toLowerCase()))
|
||||
@@ -141,7 +184,8 @@ export class ForgeService extends Service {
|
||||
this.providers.delete(provider.forge)
|
||||
registration.lifetime.abort(new Error(`forge: provider "${provider.forge}" was unregistered`))
|
||||
for (const watch of [...this.watches.values()]) {
|
||||
if (watch.ref.repository.forge === provider.forge) this.settle(watch, this.missing(provider.forge), undefined)
|
||||
if (watch.ref.repository.forge !== provider.forge) continue
|
||||
this.settle(watch, { failure: this.missing(provider.forge), level: levelOf(watch) }, undefined)
|
||||
}
|
||||
this.providersChanged(provider.forge)
|
||||
this.schedule()
|
||||
@@ -575,58 +619,135 @@ export class ForgeService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch one change request as an effect on the calling fiber. The first
|
||||
* watcher starts polling at once; listeners receive every later result,
|
||||
* and `latest` returns the current one. Polling stops when the last watcher
|
||||
* leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* Watch the snapshot of one change request as an effect on the calling fiber. Its first snapshot watcher polls it at
|
||||
* once, and a later one does when `options.maxAgeMs` is given and the latest result is older. Listeners receive every
|
||||
* later snapshot poll result, and `latest` returns the current one. While a snapshot watcher remains, polls read the
|
||||
* snapshot; polling stops when the last watcher of the snapshot and the brief leaves. Listeners must not throw; a
|
||||
* thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives each polling result.
|
||||
* @param listener - receives each snapshot poll result.
|
||||
* @param options - when the watcher needs a status newer than the latest one.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener): () => void {
|
||||
const key = changeRequestKey(ref)
|
||||
watch(ref: ChangeRequestRef, listener: ChangeRequestListener, options: ChangeRequestWatchOptions = {}): () => void {
|
||||
const dispose = this.ctx.effect(() => {
|
||||
let watch = this.watches.get(key)
|
||||
if (watch === undefined) {
|
||||
watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0, staleHead: undefined }
|
||||
this.watches.set(key, watch)
|
||||
this.schedule()
|
||||
}
|
||||
const owned = watch
|
||||
owned.listeners.add(listener)
|
||||
const now = Date.now()
|
||||
const watch = this.open(ref, { dueAt: now, joinAt: undefined, polledAt: undefined, unknownMergeability: false })
|
||||
const { latest } = watch
|
||||
const outdated = latest === undefined ? watch.listeners.size === 0
|
||||
: options.maxAgeMs !== undefined && now - latest.fetchedAt > options.maxAgeMs
|
||||
watch.listeners.add(listener)
|
||||
// A snapshot poll in flight answers a watcher that joins it.
|
||||
if (outdated && watch.reading !== 'snapshot') watch.dueAt = now
|
||||
this.schedule()
|
||||
return () => {
|
||||
owned.listeners.delete(listener)
|
||||
if (owned.listeners.size === 0 && this.watches.get(key) === owned) {
|
||||
this.watches.delete(key)
|
||||
this.schedule()
|
||||
}
|
||||
watch.listeners.delete(listener)
|
||||
this.close(watch)
|
||||
}
|
||||
}, 'forge.watch()')
|
||||
return () => void dispose()
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch the brief of one change request as an effect on the calling fiber. Listeners receive the brief of every
|
||||
* later poll result: of a brief read while only brief watchers remain, and of a snapshot read otherwise. The first
|
||||
* watcher of a change request polls it at once, or as `known` times it. Polling stops when the last watcher of the
|
||||
* snapshot and the brief leaves. Listeners must not throw; a thrown error is logged and skipped.
|
||||
* @param ref - change request to poll.
|
||||
* @param listener - receives the brief of each poll result.
|
||||
* @param known - the state the caller last saw, which times the first poll of a change request without a watcher.
|
||||
* @returns the disposer that stops this watch.
|
||||
*/
|
||||
watchBrief(ref: ChangeRequestRef, listener: ChangeRequestBriefListener, known?: ChangeRequestKnownState): () => void {
|
||||
const dispose = this.ctx.effect(() => {
|
||||
let timing: WatchTiming = { dueAt: Date.now(), joinAt: undefined, polledAt: undefined, unknownMergeability: false }
|
||||
if (known !== undefined) {
|
||||
timing = {
|
||||
...waitOf(known.fetchedAt, nextPollDelay(known, this.config, false)),
|
||||
polledAt: known.fetchedAt,
|
||||
unknownMergeability: known.mergeability === 'unknown',
|
||||
}
|
||||
}
|
||||
const watch = this.open(ref, timing)
|
||||
watch.briefListeners.add(listener)
|
||||
this.schedule()
|
||||
return () => {
|
||||
watch.briefListeners.delete(listener)
|
||||
this.close(watch)
|
||||
}
|
||||
}, 'forge.watchBrief()')
|
||||
return () => void dispose()
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll a watched change request at once, including after a terminal state.
|
||||
* A fetch already in flight is followed immediately by another fetch; an
|
||||
* unwatched change request is unchanged.
|
||||
* unwatched change request is unchanged. With `options.maxAgeMs`, the caller
|
||||
* needs a status no older than that many milliseconds: a change request
|
||||
* whose latest poll at either level, in flight or settled, started within
|
||||
* them is left alone, and so is a merged one, whose status is final.
|
||||
* @param ref - change request to poll.
|
||||
* @param options - when the caller needs a status newer than the latest one.
|
||||
*/
|
||||
refresh(ref: ChangeRequestRef): void {
|
||||
refresh(ref: ChangeRequestRef, options: ChangeRequestWatchOptions = {}): void {
|
||||
const watch = this.watches.get(changeRequestKey(ref))
|
||||
if (watch === undefined) return
|
||||
watch.dueAt = Date.now()
|
||||
const now = Date.now()
|
||||
if (options.maxAgeMs !== undefined) {
|
||||
// Only a merged change request has no poll scheduled while none is in flight.
|
||||
if (watch.dueAt === undefined && watch.reading === undefined) return
|
||||
if (watch.polledAt !== undefined && now - watch.polledAt <= options.maxAgeMs) return
|
||||
}
|
||||
watch.dueAt = now
|
||||
this.schedule()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the latest polling result of a watched change request.
|
||||
* Announce that a watched change request is about to change, as after a push to its head branch. It is polled at
|
||||
* once and then every `activeIntervalMs`, until a status reports running checks or a closed or merged change
|
||||
* request, and for at most `idleIntervalMs`; after that the regular cadence applies. A fetch already in flight is
|
||||
* followed immediately by another fetch; an unwatched change request is unchanged.
|
||||
* @param ref - change request the caller expects to change.
|
||||
*/
|
||||
expectChange(ref: ChangeRequestRef): void {
|
||||
const watch = this.watches.get(changeRequestKey(ref))
|
||||
if (watch === undefined) return
|
||||
const now = Date.now()
|
||||
watch.expectingUntil = now + this.config.idleIntervalMs
|
||||
watch.dueAt = now
|
||||
this.schedule()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the latest snapshot poll result of a watched change request.
|
||||
* @param ref - change request to read.
|
||||
* @returns the latest result, or undefined before the first result or without a watch.
|
||||
* @returns the latest result, or undefined before the first snapshot poll settled or without a watch.
|
||||
*/
|
||||
latest(ref: ChangeRequestRef): ChangeRequestUpdate | undefined {
|
||||
return this.watches.get(changeRequestKey(ref))?.latest
|
||||
}
|
||||
|
||||
/** The watch of a change request, created with `timing` when it has none. */
|
||||
private open(ref: ChangeRequestRef, timing: WatchTiming): Watch {
|
||||
const key = changeRequestKey(ref)
|
||||
let watch = this.watches.get(key)
|
||||
if (watch === undefined) {
|
||||
watch = {
|
||||
key, ref, listeners: new Set(), briefListeners: new Set(), latest: undefined, reading: undefined, failures: 0, staleHead: undefined,
|
||||
expectingUntil: undefined, ...timing,
|
||||
}
|
||||
this.watches.set(key, watch)
|
||||
}
|
||||
return watch
|
||||
}
|
||||
|
||||
/** Stop polling a change request once its last watcher left. */
|
||||
private close(watch: Watch): void {
|
||||
if (watch.listeners.size > 0 || watch.briefListeners.size > 0) return
|
||||
this.watches.delete(watch.key)
|
||||
this.schedule()
|
||||
}
|
||||
|
||||
/** Poll a watched change request at once after the first `stale` read or write at `headSha`; later ones wait for the regular poll. */
|
||||
private staleRead(ref: ChangeRequestRef, headSha: string, code: ForgeFailure['code']): void {
|
||||
const watch = this.watches.get(changeRequestKey(ref))
|
||||
@@ -724,7 +845,7 @@ export class ForgeService extends Service {
|
||||
if (this.lifetime.signal.aborted) return
|
||||
let next: number | undefined
|
||||
for (const watch of this.watches.values()) {
|
||||
if (watch.dueAt === undefined || this.fetching.has(watch.ref.repository.forge)) continue
|
||||
if (watch.dueAt === undefined || this.fetching.has(laneOf(watch.ref.repository.forge, levelOf(watch)))) continue
|
||||
next = next === undefined ? watch.dueAt : Math.min(next, watch.dueAt)
|
||||
}
|
||||
if (next === undefined) return
|
||||
@@ -733,70 +854,146 @@ export class ForgeService extends Service {
|
||||
|
||||
private poll(): void {
|
||||
const now = Date.now()
|
||||
const due = new Map<string, Watch[]>()
|
||||
const lanes = new Map<string, { readonly forge: string; readonly level: StatusLevel; readonly batch: Watch[]; due: boolean }>()
|
||||
for (const watch of this.watches.values()) {
|
||||
const forge = watch.ref.repository.forge
|
||||
if (watch.dueAt === undefined || watch.dueAt > now || this.fetching.has(forge)) continue
|
||||
const batch = due.get(forge)
|
||||
if (batch === undefined) due.set(forge, [watch])
|
||||
else batch.push(watch)
|
||||
const level = levelOf(watch)
|
||||
const lane = laneOf(forge, level)
|
||||
if (watch.dueAt === undefined || this.fetching.has(lane)) continue
|
||||
const due = watch.dueAt <= now
|
||||
if (!due && (watch.joinAt === undefined || watch.joinAt > now)) continue
|
||||
let entry = lanes.get(lane)
|
||||
if (entry === undefined) lanes.set(lane, entry = { forge, level, batch: [], due: false })
|
||||
entry.batch.push(watch)
|
||||
entry.due ||= due
|
||||
}
|
||||
for (const [forge, batch] of due) {
|
||||
const task = this.fetch(forge, batch)
|
||||
for (const { forge, level, batch, due } of lanes.values()) {
|
||||
// Watches past the midpoint of their wait ride along with a due one; alone they wait.
|
||||
if (!due) continue
|
||||
const task = this.fetch(forge, level, batch)
|
||||
this.pending.add(task)
|
||||
void task.then(() => this.pending.delete(task))
|
||||
}
|
||||
this.schedule()
|
||||
}
|
||||
|
||||
/** Fetch one forge's batch; never rejects. */
|
||||
private async fetch(forge: string, batch: readonly Watch[]): Promise<void> {
|
||||
this.fetching.add(forge)
|
||||
for (const watch of batch) watch.dueAt = undefined
|
||||
let results: FetchResults | undefined
|
||||
let failure: ForgeFailure | undefined
|
||||
/**
|
||||
* Fetch one forge's batch at one level, as briefs when the level is `brief` and the provider reads them. The batch
|
||||
* is read in the parts {@link partsOf} names, one provider call after another; each call has its own
|
||||
* `fetchTimeoutMs` deadline, and its watches are settled before the next call starts, so a call that fails or
|
||||
* outlives its deadline fails only its own change requests. Never rejects.
|
||||
*/
|
||||
private async fetch(forge: string, level: StatusLevel, batch: readonly Watch[]): Promise<void> {
|
||||
const lane = laneOf(forge, level)
|
||||
this.fetching.add(lane)
|
||||
for (const watch of batch) {
|
||||
watch.dueAt = undefined
|
||||
watch.reading = level
|
||||
}
|
||||
const registration = this.providers.get(forge)
|
||||
try {
|
||||
if (registration === undefined) {
|
||||
failure = this.missing(forge)
|
||||
} else {
|
||||
using timeout = deadline(this.lifetime.signal, this.config.fetchTimeoutMs, 'FORGE_FETCH_TIMEOUT')
|
||||
results = await this.invoke(registration, timeout.signal,
|
||||
(provider, operation) => provider.fetch(batch.map(watch => watch.ref), operation))
|
||||
for (const part of partsOf(batch, registration?.provider, level)) {
|
||||
const reading = this.claim(part, level)
|
||||
if (reading.length === 0) continue
|
||||
const read = await this.read(forge, registration, level, reading)
|
||||
// The results of a withdrawn registration are discarded; its withdrawal settled the watches.
|
||||
if (this.lifetime.signal.aborted || registration !== this.providers.get(forge)) return
|
||||
for (const watch of reading) {
|
||||
// A watch whose level changed during this call may be in a call of the other lane by now.
|
||||
if (watch.reading === level) watch.reading = undefined
|
||||
if (this.watches.get(watch.key) !== watch) continue
|
||||
this.settle(watch, 'code' in read ? { failure: read, level } : outcomeOf(watch.key, level, read), watch.dueAt)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
failure = { code: 'unavailable', message: error instanceof Error ? error.message : String(error) }
|
||||
} finally {
|
||||
this.fetching.delete(forge)
|
||||
}
|
||||
if (this.lifetime.signal.aborted) return
|
||||
if (registration !== this.providers.get(forge)) {
|
||||
this.fetching.delete(lane)
|
||||
for (const watch of batch) if (watch.reading === level) watch.reading = undefined
|
||||
this.schedule()
|
||||
return
|
||||
}
|
||||
for (const watch of batch) {
|
||||
if (this.watches.get(watch.key) !== watch) continue
|
||||
const result = failure ?? results?.get(watch.key) ?? { code: 'unavailable', message: `provider returned no result for ${watch.key}` }
|
||||
this.settle(watch, result, watch.dueAt)
|
||||
}
|
||||
this.schedule()
|
||||
}
|
||||
|
||||
private settle(watch: Watch, result: ChangeRequestSnapshot | ForgeFailure, refreshAt: number | undefined): void {
|
||||
/**
|
||||
* Take the watches of one part that its provider call reads: those still watched that no fetch of the other level
|
||||
* has read since the fetch started. A watch whose watchers changed its level while it waited is made due for the
|
||||
* fetch of that level instead.
|
||||
*/
|
||||
private claim(part: readonly Watch[], level: StatusLevel): Watch[] {
|
||||
const startedAt = Date.now()
|
||||
const reading: Watch[] = []
|
||||
let moved = false
|
||||
for (const watch of part) {
|
||||
if (this.watches.get(watch.key) !== watch || watch.reading !== level) continue
|
||||
if (levelOf(watch) !== level) {
|
||||
watch.reading = undefined
|
||||
watch.dueAt ??= startedAt
|
||||
moved = true
|
||||
continue
|
||||
}
|
||||
// This call answers a refresh that was asked for while the watch waited for it.
|
||||
watch.dueAt = undefined
|
||||
watch.polledAt = startedAt
|
||||
reading.push(watch)
|
||||
}
|
||||
if (moved) this.schedule()
|
||||
return reading
|
||||
}
|
||||
|
||||
/** Read one part of a batch within its own `fetchTimeoutMs` deadline; a call that rejects or outlives it is the part's failure. */
|
||||
private async read(
|
||||
forge: string, registration: Registration | undefined, level: StatusLevel, part: readonly Watch[],
|
||||
): Promise<Reading | ForgeFailure> {
|
||||
if (registration === undefined) return this.missing(forge)
|
||||
try {
|
||||
using timeout = deadline(this.lifetime.signal, this.config.fetchTimeoutMs, 'FORGE_FETCH_TIMEOUT')
|
||||
const refs = part.map(watch => watch.ref)
|
||||
return await this.invoke(registration, timeout.signal, async (provider, operation): Promise<Reading> =>
|
||||
level === 'brief' && provider.fetchBriefs !== undefined
|
||||
? { kind: 'brief', results: await provider.fetchBriefs(refs, operation) }
|
||||
: { kind: 'snapshot', results: await provider.fetch(refs, operation) })
|
||||
} catch (error) {
|
||||
return { code: 'unavailable', message: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record one poll result of a watch, time its next poll, and deliver the result: a snapshot or a snapshot-level
|
||||
* failure to both kinds of watchers, a brief or a brief-level failure to brief watchers only.
|
||||
*/
|
||||
private settle(watch: Watch, outcome: Outcome, refreshAt: number | undefined): void {
|
||||
const fetchedAt = Date.now()
|
||||
let update: ChangeRequestUpdate
|
||||
if ('code' in result) {
|
||||
const { key } = watch
|
||||
let update: ChangeRequestUpdate | undefined
|
||||
let brief: ChangeRequestBriefUpdate
|
||||
let wait: Pick<Watch, 'dueAt' | 'joinAt'>
|
||||
if ('failure' in outcome) {
|
||||
watch.failures++
|
||||
update = { key: watch.key, fetchedAt, failure: result }
|
||||
brief = { key, fetchedAt, failure: outcome.failure }
|
||||
if (outcome.level === 'snapshot') update = brief
|
||||
wait = { dueAt: fetchedAt + backoffDelay(watch.failures, this.config), joinAt: undefined }
|
||||
} else {
|
||||
watch.failures = 0
|
||||
update = { key: watch.key, fetchedAt, snapshot: result }
|
||||
if ('snapshot' in outcome) update = { key, fetchedAt, snapshot: outcome.snapshot }
|
||||
const state = 'snapshot' in outcome ? outcome.snapshot : outcome.brief
|
||||
brief = { key, fetchedAt, brief: state }
|
||||
let delay = nextPollDelay(state, this.config, watch.unknownMergeability)
|
||||
if (watch.expectingUntil !== undefined) {
|
||||
// Running checks are the announced change, and nothing follows a closed or merged change request.
|
||||
if (state.state !== 'open' || state.checksRollup === 'pending' || fetchedAt >= watch.expectingUntil) watch.expectingUntil = undefined
|
||||
else delay = this.config.activeIntervalMs
|
||||
}
|
||||
wait = waitOf(fetchedAt, delay)
|
||||
watch.unknownMergeability = state.mergeability === 'unknown'
|
||||
}
|
||||
watch.latest = update
|
||||
const delay = nextPollDelay(result, watch.failures, this.config)
|
||||
if (update !== undefined) watch.latest = update
|
||||
// A refresh requested after this fetch started needs a subsequent fetch, even for a terminal result.
|
||||
watch.dueAt = refreshAt ?? (delay === undefined ? undefined : fetchedAt + delay)
|
||||
for (const listener of [...watch.listeners]) {
|
||||
watch.dueAt = refreshAt ?? wait.dueAt
|
||||
watch.joinAt = refreshAt === undefined ? wait.joinAt : undefined
|
||||
if (update !== undefined) this.deliver(watch.listeners, update)
|
||||
this.deliver(watch.briefListeners, brief)
|
||||
}
|
||||
|
||||
private deliver<U>(listeners: ReadonlySet<(update: U) => void>, update: U): void {
|
||||
for (const listener of [...listeners]) {
|
||||
try {
|
||||
listener(update)
|
||||
} catch (error) {
|
||||
@@ -806,6 +1003,58 @@ export class ForgeService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/** What a new watch starts with: when it polls first, and what its watcher already knows. */
|
||||
type WatchTiming = Pick<Watch, 'dueAt' | 'joinAt' | 'polledAt' | 'unknownMergeability'>
|
||||
|
||||
/**
|
||||
* Time the poll after a status.
|
||||
* @param settledAt - epoch milliseconds when the status was read.
|
||||
* @param delay - the wait {@link nextPollDelay} chose, or undefined after a terminal state.
|
||||
* @returns when the change request is due, and the midpoint of the wait, from which a poll of its lane reads it too.
|
||||
*/
|
||||
function waitOf(settledAt: number, delay: number | undefined): Pick<Watch, 'dueAt' | 'joinAt'> {
|
||||
return delay === undefined ? { dueAt: undefined, joinAt: undefined } : { dueAt: settledAt + delay, joinAt: settledAt + delay / 2 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the batch of one fetch into the parts that one provider call reads each.
|
||||
* @param batch - watches of one forge that are read at `level`.
|
||||
* @param provider - the forge's provider, or undefined without one.
|
||||
* @param level - what the fetch reads.
|
||||
* @returns the whole batch as one part, unless the provider names a batch size for the method that reads `level`:
|
||||
* then the watches of each host, compared without case, in parts of at most that size.
|
||||
*/
|
||||
function partsOf(batch: readonly Watch[], provider: ForgeProvider | undefined, level: StatusLevel): readonly (readonly Watch[])[] {
|
||||
const size = level === 'brief' && provider?.fetchBriefs !== undefined ? provider.briefBatchSize : provider?.snapshotBatchSize
|
||||
if (size === undefined) return [batch]
|
||||
const parts: Watch[][] = []
|
||||
for (const hosted of Map.groupBy(batch, watch => watch.ref.repository.host.toLowerCase()).values()) {
|
||||
for (let start = 0; start < hosted.length; start += size) parts.push(hosted.slice(start, start + size))
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
/** The level polls of a watch read at: the snapshot while a snapshot watcher remains. */
|
||||
function levelOf(watch: Watch): StatusLevel {
|
||||
return watch.listeners.size > 0 ? 'snapshot' : 'brief'
|
||||
}
|
||||
|
||||
/** Name the fetch lane of one forge at one level; a level holds no colon, so no two lanes share a name. */
|
||||
function laneOf(forge: string, level: StatusLevel): string {
|
||||
return `${level}:${forge}`
|
||||
}
|
||||
|
||||
/** The outcome of one provider read for one of its change requests, read at `level`. */
|
||||
function outcomeOf(key: ChangeRequestKey, level: StatusLevel, reading: Reading): Outcome {
|
||||
const missing: Outcome = { failure: { code: 'unavailable', message: `provider returned no result for ${key}` }, level }
|
||||
if (reading.kind === 'snapshot') {
|
||||
const result = reading.results.get(key)
|
||||
return result === undefined ? missing : 'code' in result ? { failure: result, level } : { snapshot: result }
|
||||
}
|
||||
const result = reading.results.get(key)
|
||||
return result === undefined ? missing : 'code' in result ? { failure: result, level } : { brief: result }
|
||||
}
|
||||
|
||||
const UNSUPPORTED_VIEWER: ForgeFailure = { code: 'unsupported', message: 'This provider does not read viewer lists' }
|
||||
|
||||
/** The viewer reads of one provider, bound to it. */
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/** Poll cadence for watched change requests. */
|
||||
|
||||
import type { ChangeRequestSnapshot, ForgeFailure } from './types.ts'
|
||||
import type { ChangeRequestBrief } from './types.ts'
|
||||
|
||||
/** Resolved intervals that pace polling. */
|
||||
export interface PollIntervals {
|
||||
/** Delay while checks run or mergeability is unknown. */
|
||||
/** Delay while checks run, and once after a status first reports an unknown mergeability. */
|
||||
readonly activeIntervalMs: number
|
||||
/** Delay for a closed request or an open request whose checks have settled. */
|
||||
readonly idleIntervalMs: number
|
||||
@@ -13,21 +13,34 @@ export interface PollIntervals {
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose the delay before the next poll of one change request. Failures back
|
||||
* off exponentially from the active interval; merged change requests stop
|
||||
* polling, while closed ones use the idle cadence to detect reopening.
|
||||
* @param result - latest snapshot or failure.
|
||||
* @param failures - consecutive failures, counting `result` when it is one.
|
||||
* Choose the delay before the poll after a status. Merged change requests stop
|
||||
* polling, while closed ones use the idle cadence to detect reopening. An
|
||||
* unknown mergeability, which a code host reports while it computes one, earns
|
||||
* the active interval for one poll; a change request that reports it again
|
||||
* waits the idle interval, because some never report another value.
|
||||
* @param status - state of the latest snapshot or brief.
|
||||
* @param intervals - configured cadence.
|
||||
* @param unknownBefore - whether the status before `status` also reported an unknown mergeability.
|
||||
* @returns the delay in milliseconds, or undefined after a terminal state.
|
||||
*/
|
||||
export function nextPollDelay(
|
||||
result: ChangeRequestSnapshot | ForgeFailure,
|
||||
failures: number,
|
||||
status: Pick<ChangeRequestBrief, 'state' | 'mergeability' | 'checksRollup'>,
|
||||
intervals: PollIntervals,
|
||||
unknownBefore: boolean,
|
||||
): number | undefined {
|
||||
if ('code' in result) return Math.min(intervals.maxBackoffMs, intervals.activeIntervalMs * 2 ** failures)
|
||||
if (result.state === 'merged') return undefined
|
||||
if (result.state === 'closed') return intervals.idleIntervalMs
|
||||
return result.checksRollup === 'pending' || result.mergeability === 'unknown' ? intervals.activeIntervalMs : intervals.idleIntervalMs
|
||||
if (status.state === 'merged') return undefined
|
||||
if (status.state === 'closed') return intervals.idleIntervalMs
|
||||
const computing = status.mergeability === 'unknown' && !unknownBefore
|
||||
return status.checksRollup === 'pending' || computing ? intervals.activeIntervalMs : intervals.idleIntervalMs
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose the delay before the poll after a failed one: the active interval doubled for each consecutive failure, up
|
||||
* to `maxBackoffMs`.
|
||||
* @param failures - consecutive failures, counting the latest.
|
||||
* @param intervals - configured cadence.
|
||||
* @returns the delay in milliseconds.
|
||||
*/
|
||||
export function backoffDelay(failures: number, intervals: PollIntervals): number {
|
||||
return Math.min(intervals.maxBackoffMs, intervals.activeIntervalMs * 2 ** failures)
|
||||
}
|
||||
@@ -179,6 +179,14 @@ export interface ChangeRequestSnapshot {
|
||||
readonly closedAt: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields of a {@link ChangeRequestSnapshot} that name a change request and its state in a list. A provider can
|
||||
* read them for many change requests in one request, without the checks, reviewers, and merge rules of a snapshot.
|
||||
*/
|
||||
export type ChangeRequestBrief = Pick<
|
||||
ChangeRequestSnapshot, 'ref' | 'url' | 'title' | 'state' | 'draft' | 'mergeability' | 'reviewDecision' | 'checksRollup'
|
||||
>
|
||||
|
||||
/** Why a provider could not read a change request. */
|
||||
export interface ForgeFailure {
|
||||
/**
|
||||
@@ -208,6 +216,20 @@ export type ChangeRequestUpdate = {
|
||||
readonly failure: ForgeFailure
|
||||
})
|
||||
|
||||
/** Latest brief delivered to brief watchers of one change request, from a brief read or from a snapshot read. */
|
||||
export type ChangeRequestBriefUpdate = {
|
||||
/** Canonical identity of the watched change request. */
|
||||
readonly key: ChangeRequestKey
|
||||
/** Epoch milliseconds when the result settled. */
|
||||
readonly fetchedAt: number
|
||||
} & ({
|
||||
/** Brief read from the host. */
|
||||
readonly brief: ChangeRequestBrief
|
||||
} | {
|
||||
/** Reason the brief could not be read. */
|
||||
readonly failure: ForgeFailure
|
||||
})
|
||||
|
||||
/** A merge the user confirmed for the head commit they saw. */
|
||||
export interface MergeRequest {
|
||||
/** How the commits enter the base branch. */
|
||||
@@ -684,6 +706,23 @@ export interface ForgeProvider {
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>>
|
||||
/**
|
||||
* Read the briefs of several change requests, returning one result per requested key. Omission declares that the
|
||||
* provider reads briefs as snapshots through {@link ForgeProvider.fetch}.
|
||||
*/
|
||||
fetchBriefs?(
|
||||
refs: readonly ChangeRequestRef[],
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>>
|
||||
/**
|
||||
* Most change requests of one host that one polling call of {@link ForgeProvider.fetch} reads, a positive safe
|
||||
* integer. The registry then calls `fetch` once for every that many due change requests of a host, one call after
|
||||
* another, each within its own fetch deadline, and publishes the results of a call when it returns. Omission
|
||||
* declares that one call reads every due change request of the forge.
|
||||
*/
|
||||
readonly snapshotBatchSize?: number
|
||||
/** The same bound for one polling call of {@link ForgeProvider.fetchBriefs}. */
|
||||
readonly briefBatchSize?: number
|
||||
/** Read all checks for one change request on demand; omission declares that only the polling preview is available. */
|
||||
fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure>
|
||||
/** Find open change requests whose head is `branch` in `repository`, excluding the default branch and forks. */
|
||||
@@ -763,14 +802,41 @@ export interface ForgeProvider {
|
||||
*/
|
||||
export type ChangeRequestListener = (update: ChangeRequestUpdate) => void
|
||||
|
||||
/**
|
||||
* Receives every polling result for one change request watched for its brief.
|
||||
* @param update - the settled result.
|
||||
*/
|
||||
export type ChangeRequestBriefListener = (update: ChangeRequestBriefUpdate) => void
|
||||
|
||||
/** When a watcher that joins a watched change request, or a refresh of one, needs a status newer than the latest one. */
|
||||
export interface ChangeRequestWatchOptions {
|
||||
/**
|
||||
* Age in milliseconds past which the latest status is too old. A watcher that joins a change request whose
|
||||
* snapshot was already read polls at once when the latest snapshot or failure is older and no snapshot poll is in
|
||||
* flight; without it, the watcher waits for the regular poll. A refresh polls at once unless the change request is
|
||||
* merged or its latest poll at either level, in flight or settled, started within it; without it, a refresh always
|
||||
* polls.
|
||||
*/
|
||||
readonly maxAgeMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The state a brief watcher last saw for a change request it starts to watch, which times the first poll as a brief
|
||||
* read at `fetchedAt` would: a merged change request is not polled, and any other one once its interval has passed.
|
||||
*/
|
||||
export interface ChangeRequestKnownState extends Pick<ChangeRequestBrief, 'state' | 'mergeability' | 'checksRollup'> {
|
||||
/** Epoch milliseconds when the state was read. */
|
||||
readonly fetchedAt: number
|
||||
}
|
||||
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
export interface Config {
|
||||
/** Poll interval in milliseconds while checks run or mergeability is unknown. */
|
||||
/** Poll interval in milliseconds while checks run, and for one poll after a status first reports an unknown mergeability. */
|
||||
activeIntervalMs?: number
|
||||
/** Poll interval in milliseconds for a closed request or an open request whose checks have settled. */
|
||||
idleIntervalMs?: number
|
||||
/** Largest delay in milliseconds between polls after consecutive failures. */
|
||||
maxBackoffMs?: number
|
||||
/** Deadline in milliseconds for one provider fetch. */
|
||||
/** Deadline in milliseconds for one provider fetch: one polling call, or one read of complete checks. */
|
||||
fetchTimeoutMs?: number
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
/** Brief watches: what a poll reads for them, when it runs, and what each kind of watcher receives. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { changeRequestKey } from '../src/index.ts'
|
||||
import type {
|
||||
ChangeRequestBriefUpdate, ChangeRequestKey, ChangeRequestKnownState, ChangeRequestRef, ChangeRequestUpdate, ChangeRequestWatchOptions,
|
||||
ForgeFailure,
|
||||
} from '../src/types.ts'
|
||||
import { brief, BriefProvider, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts'
|
||||
|
||||
const config = { activeIntervalMs: 1_000, idleIntervalMs: 5_000, maxBackoffMs: 6_000, fetchTimeoutMs: 500 }
|
||||
const START = 1_000_000
|
||||
const key = changeRequestKey(ref(1))
|
||||
const missing: ForgeFailure = { code: 'not-found', message: 'missing' }
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: START })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx?.fiber.dispose()
|
||||
ctx = undefined
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
async function setup(provider: FakeProvider): Promise<Context> {
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, provider)
|
||||
return ctx
|
||||
}
|
||||
|
||||
/** A provider that reads briefs, holding an open snapshot whose checks passed for each numbered change request. */
|
||||
function briefProvider(...numbers: number[]): BriefProvider {
|
||||
const provider = new BriefProvider()
|
||||
for (const number of numbers) provider.results.set(changeRequestKey(ref(number)), snapshot(ref(number)))
|
||||
return provider
|
||||
}
|
||||
|
||||
function briefs(
|
||||
context: Context, target: ChangeRequestRef = ref(1), known?: ChangeRequestKnownState,
|
||||
): { updates: ChangeRequestBriefUpdate[]; unwatch: () => void } {
|
||||
const updates: ChangeRequestBriefUpdate[] = []
|
||||
const unwatch = context.forge.watchBrief(target, (update) => { updates.push(update) }, known)
|
||||
return { updates, unwatch }
|
||||
}
|
||||
|
||||
function snapshots(
|
||||
context: Context, target: ChangeRequestRef = ref(1), options?: ChangeRequestWatchOptions,
|
||||
): { updates: ChangeRequestUpdate[]; unwatch: () => void } {
|
||||
const updates: ChangeRequestUpdate[] = []
|
||||
const unwatch = context.forge.watch(target, (update) => { updates.push(update) }, options)
|
||||
return { updates, unwatch }
|
||||
}
|
||||
|
||||
/** A read that stays pending until released or until its signal aborts. */
|
||||
function hold<T>(result: (target: ChangeRequestRef) => T): {
|
||||
readonly read: (refs: readonly ChangeRequestRef[], signal: AbortSignal) => Promise<ReadonlyMap<ChangeRequestKey, T>>
|
||||
readonly release: () => void
|
||||
} {
|
||||
const releases: (() => void)[] = []
|
||||
return {
|
||||
read: (refs, signal) => new Promise((resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(signal.reason as Error) })
|
||||
releases.push(() => { resolve(new Map(refs.map(target => [changeRequestKey(target), result(target)] as const))) })
|
||||
}),
|
||||
release: () => {
|
||||
for (const release of releases.splice(0)) release()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('forge brief watch', () => {
|
||||
it('reads a change request that only brief watchers watch through fetchBriefs', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
const { updates } = briefs(context)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(provider.briefFetches).toEqual([[ref(1)]])
|
||||
expect(provider.fetches).toEqual([])
|
||||
expect(updates).toEqual([{ key, fetchedAt: START, brief: brief(snapshot(ref(1))) }])
|
||||
expect(context.forge.latest(ref(1))).toBeUndefined()
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)], [ref(1)]])
|
||||
})
|
||||
|
||||
it('reads snapshots for brief watchers when the provider reads no briefs', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1)))
|
||||
const context = await setup(provider)
|
||||
const { updates } = briefs(context)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(provider.fetches).toEqual([[ref(1)]])
|
||||
expect(updates).toEqual([{ key, fetchedAt: START, brief: snapshot(ref(1)) }])
|
||||
expect(context.forge.latest(ref(1))).toEqual({ key, fetchedAt: START, snapshot: snapshot(ref(1)) })
|
||||
})
|
||||
|
||||
it('reads the snapshot while a snapshot watcher remains, delivers its brief, and reads the brief again once it left', async () => {
|
||||
const provider = briefProvider()
|
||||
const running = snapshot(ref(1), { checksRollup: 'pending' })
|
||||
provider.results.set(key, running)
|
||||
const context = await setup(provider)
|
||||
const list = briefs(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
const panel = snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toEqual([[ref(1)]])
|
||||
expect(panel.updates).toEqual([{ key, fetchedAt: START, snapshot: running }])
|
||||
expect(list.updates).toEqual([{ key, fetchedAt: START, brief: brief(running) }, { key, fetchedAt: START, brief: running }])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
|
||||
panel.unwatch()
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(provider.briefFetches).toHaveLength(2)
|
||||
expect(list.updates.at(-1)).toEqual({ key, fetchedAt: START + 2_000, brief: brief(running) })
|
||||
expect(context.forge.latest(ref(1))).toEqual({ key, fetchedAt: START + 1_000, snapshot: running })
|
||||
})
|
||||
|
||||
it('reads at once for a later snapshot watcher only when the latest result is older than its maxAgeMs', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
|
||||
snapshots(context)
|
||||
snapshots(context, ref(1), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
|
||||
const fresh = snapshots(context, ref(1), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(fresh.updates).toEqual([{ key, fetchedAt: START + 600, snapshot: snapshot(ref(1)) }])
|
||||
})
|
||||
|
||||
it('keeps the latest snapshot for a watcher that joins a brief watch, and reads a newer one when it asks', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
briefs(context)
|
||||
snapshots(context).unwatch()
|
||||
const first = snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
first.unwatch()
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
|
||||
const waiting = snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
expect(context.forge.latest(ref(1))).toEqual({ key, fetchedAt: START, snapshot: snapshot(ref(1)) })
|
||||
waiting.unwatch()
|
||||
|
||||
const fresh = snapshots(context, ref(1), { maxAgeMs: 1_000 })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(fresh.updates).toEqual([{ key, fetchedAt: START + 2_000, snapshot: snapshot(ref(1)) }])
|
||||
})
|
||||
|
||||
it('runs one snapshot fetch and one brief fetch of a forge side by side', async () => {
|
||||
const provider = briefProvider()
|
||||
const snapshotReads = hold(target => snapshot(target))
|
||||
const briefReads = hold(target => brief(snapshot(target)))
|
||||
provider.fetchImpl = snapshotReads.read
|
||||
provider.briefImpl = briefReads.read
|
||||
const context = await setup(provider)
|
||||
briefs(context, ref(1))
|
||||
snapshots(context, ref(2))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)]])
|
||||
expect(provider.fetches).toEqual([[ref(2)]])
|
||||
|
||||
briefs(context, ref(3))
|
||||
snapshots(context, ref(4))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
|
||||
snapshotReads.release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toEqual([[ref(2)], [ref(4)]])
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
|
||||
briefReads.release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)], [ref(3)]])
|
||||
})
|
||||
|
||||
it('times the first poll of a brief watch from the state its watcher knows', async () => {
|
||||
const provider = briefProvider(1, 2, 3)
|
||||
const context = await setup(provider)
|
||||
briefs(context, ref(1), { state: 'merged', mergeability: 'unknown', checksRollup: 'none', fetchedAt: 0 })
|
||||
briefs(context, ref(2), { state: 'open', mergeability: 'mergeable', checksRollup: 'success', fetchedAt: START - 2_000 })
|
||||
briefs(context, ref(3), { state: 'open', mergeability: 'mergeable', checksRollup: 'pending', fetchedAt: START - 2_000 })
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2_999)
|
||||
expect(provider.briefFetches).toEqual([[ref(3)]])
|
||||
// The third one, read 3 of its 5 seconds ago, rides along.
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toEqual([[ref(3)], [ref(2), ref(3)]])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(provider.briefFetches.flat()).not.toContainEqual(ref(1))
|
||||
context.forge.refresh(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches.at(-1)).toEqual([ref(1)])
|
||||
})
|
||||
|
||||
it('ignores the known state of a change request that already has a watcher', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
briefs(context)
|
||||
briefs(context, ref(1), { state: 'merged', mergeability: 'unknown', checksRollup: 'none', fetchedAt: 0 })
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(provider.briefFetches).toEqual([[ref(1)]])
|
||||
})
|
||||
|
||||
it('delivers a failed brief read to brief watchers only, keeps the latest snapshot, and backs off', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
const list = briefs(context)
|
||||
const panel = snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
panel.unwatch()
|
||||
provider.results.set(key, missing)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
|
||||
expect(list.updates.at(-1)).toEqual({ key, fetchedAt: START + 5_000, failure: missing })
|
||||
expect(panel.updates).toHaveLength(1)
|
||||
expect(context.forge.latest(ref(1))).toEqual({ key, fetchedAt: START, snapshot: snapshot(ref(1)) })
|
||||
await vi.advanceTimersByTimeAsync(1_999)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('delivers a failed snapshot read to both kinds of watchers', async () => {
|
||||
const provider = briefProvider()
|
||||
const context = await setup(provider)
|
||||
const list = briefs(context)
|
||||
const panel = snapshots(context)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(panel.updates).toEqual([{ key, fetchedAt: START, failure: missing }])
|
||||
expect(list.updates).toEqual([{ key, fetchedAt: START, failure: missing }])
|
||||
expect(context.forge.latest(ref(1))).toEqual({ key, fetchedAt: START, failure: missing })
|
||||
})
|
||||
|
||||
it('reports a brief read that names no result for a change request, and one that rejects', async () => {
|
||||
const provider = briefProvider(1)
|
||||
provider.briefImpl = async () => new Map()
|
||||
const context = await setup(provider)
|
||||
const list = briefs(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(list.updates).toEqual([{ key, fetchedAt: START, failure: { code: 'unavailable', message: `provider returned no result for ${key}` } }])
|
||||
|
||||
provider.briefImpl = async () => { throw new Error('briefs down') }
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(list.updates.at(-1)).toEqual({ key, fetchedAt: START + 2_000, failure: { code: 'unavailable', message: 'briefs down' } })
|
||||
})
|
||||
|
||||
it('fails the watches of a withdrawn provider at the level each is read at', async () => {
|
||||
const provider = briefProvider(1, 2)
|
||||
ctx = await forgeContext(config)
|
||||
const fiber = await provide(ctx, provider)
|
||||
const list = briefs(ctx, ref(1))
|
||||
const panel = snapshots(ctx, ref(2))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
await fiber.dispose()
|
||||
|
||||
const failure = { code: 'unavailable', message: 'no provider is registered for "fake"' }
|
||||
expect(list.updates.at(-1)).toEqual({ key, fetchedAt: START, failure })
|
||||
expect(panel.updates.at(-1)).toEqual({ key: changeRequestKey(ref(2)), fetchedAt: START, failure })
|
||||
expect(ctx.forge.latest(ref(1))).toBeUndefined()
|
||||
expect(ctx.forge.latest(ref(2))).toEqual({ key: changeRequestKey(ref(2)), fetchedAt: START, failure })
|
||||
})
|
||||
|
||||
it('keeps polling until the last watcher of either kind left', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
const list = briefs(context)
|
||||
const panel = snapshots(context)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
list.unwatch()
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
|
||||
panel.unwatch()
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(provider.briefFetches).toEqual([])
|
||||
expect(context.forge.latest(ref(1))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('skips a brief listener that throws', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), () => { throw new Error('listener failed') })
|
||||
const list = briefs(context)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(list.updates).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('stops a brief watch when the fiber that started it is disposed', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
const fiber = context.plugin({
|
||||
inject: ['forge'],
|
||||
apply(child: Context) {
|
||||
child.forge.watchBrief(ref(1), () => {})
|
||||
},
|
||||
})
|
||||
await fiber
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
|
||||
await fiber.dispose()
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,355 @@
|
||||
/**
|
||||
* When polls run: which change requests one fetch reads together, how an unknown mergeability and an announced change
|
||||
* are paced, and when a refresh reads.
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { changeRequestKey } from '../src/index.ts'
|
||||
import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestUpdate } from '../src/types.ts'
|
||||
import { brief, BriefProvider, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts'
|
||||
|
||||
const config = { activeIntervalMs: 1_000, idleIntervalMs: 4_000, maxBackoffMs: 16_000, fetchTimeoutMs: 500 }
|
||||
const START = 1_000_000
|
||||
const key = changeRequestKey(ref(1))
|
||||
const ignore = (): void => undefined
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: START })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx?.fiber.dispose()
|
||||
ctx = undefined
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
async function setup(provider: FakeProvider, overrides: typeof config | Record<string, never> = config): Promise<Context> {
|
||||
ctx = await forgeContext(overrides)
|
||||
await provide(ctx, provider)
|
||||
return ctx
|
||||
}
|
||||
|
||||
/** A provider that reads briefs, holding an open snapshot whose checks passed for each numbered change request. */
|
||||
function briefProvider(...numbers: number[]): BriefProvider {
|
||||
const provider = new BriefProvider()
|
||||
for (const number of numbers) provider.results.set(changeRequestKey(ref(number)), snapshot(ref(number)))
|
||||
return provider
|
||||
}
|
||||
|
||||
/** Make every read of `provider` at one level stay pending until released or until its signal aborts. */
|
||||
function hold(provider: BriefProvider, level: 'brief' | 'snapshot'): () => void {
|
||||
const releases: (() => void)[] = []
|
||||
const pending = <T>(result: (target: ChangeRequestRef) => T) => (refs: readonly ChangeRequestRef[], signal: AbortSignal) =>
|
||||
new Promise<ReadonlyMap<ChangeRequestKey, T>>((resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(signal.reason as Error) })
|
||||
releases.push(() => { resolve(new Map(refs.map(target => [changeRequestKey(target), result(target)] as const))) })
|
||||
})
|
||||
if (level === 'brief') provider.briefImpl = pending(target => brief(snapshot(target)))
|
||||
else provider.fetchImpl = pending(target => snapshot(target))
|
||||
return () => {
|
||||
for (const release of releases.splice(0)) release()
|
||||
}
|
||||
}
|
||||
|
||||
describe('forge poll cadence', () => {
|
||||
it('reads a change request past the midpoint of its wait with one that is due, so later polls share one fetch', async () => {
|
||||
const provider = briefProvider(1, 2)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
// The first change request, read 1 of its 4 seconds ago, is left out of the first poll of the second.
|
||||
context.forge.watchBrief(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)], [ref(2)]])
|
||||
|
||||
// No poll runs while both are only past their midpoints.
|
||||
await vi.advanceTimersByTimeAsync(2_999)
|
||||
expect(provider.briefFetches).toHaveLength(2)
|
||||
|
||||
// The second one, read 3 of its 4 seconds ago, rides along with the first.
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches.slice(2)).toEqual([[ref(1), ref(2)]])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(8_000)
|
||||
expect(provider.briefFetches.slice(3)).toEqual([[ref(1), ref(2)], [ref(1), ref(2)]])
|
||||
})
|
||||
|
||||
it('reads the change requests past their midpoints with the first poll of a new watch', async () => {
|
||||
const provider = briefProvider(1, 2)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
|
||||
context.forge.watchBrief(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(provider.briefFetches).toEqual([[ref(1)], [ref(1), ref(2)]])
|
||||
})
|
||||
|
||||
it('reads a failing change request only when its own backoff ends', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
context.forge.watchBrief(ref(2), ignore)
|
||||
|
||||
// The second change request fails every read and waits 2, 4, and then 8 seconds; at 10 seconds it is past the
|
||||
// midpoint of the 8, and the poll of the first one leaves it out.
|
||||
await vi.advanceTimersByTimeAsync(14_000)
|
||||
|
||||
expect(provider.briefFetches).toEqual([[ref(1), ref(2)], [ref(1), ref(2)], [ref(1), ref(2)], [ref(1)], [ref(1), ref(2)]])
|
||||
})
|
||||
|
||||
it('takes along only change requests read at the same level', async () => {
|
||||
const provider = briefProvider(1, 2)
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
context.forge.watchBrief(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
context.forge.refresh(ref(2))
|
||||
|
||||
// At 4 seconds the brief of the second one is past its midpoint while only the snapshot of the first is due.
|
||||
await vi.advanceTimersByTimeAsync(3_000)
|
||||
expect(provider.fetches).toEqual([[ref(1)], [ref(1)]])
|
||||
expect(provider.briefFetches).toEqual([[ref(2)], [ref(2)]])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.briefFetches).toEqual([[ref(2)], [ref(2)], [ref(2)]])
|
||||
})
|
||||
|
||||
it('polls once at the active interval after a status first reports an unknown mergeability, then at the idle interval', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { mergeability: 'unknown' }))
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
provider.results.set(key, snapshot(ref(1)))
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
|
||||
// Unknown again after a known value earns the active interval again.
|
||||
provider.results.set(key, snapshot(ref(1), { mergeability: 'unknown' }))
|
||||
await vi.advanceTimersByTimeAsync(4_000)
|
||||
expect(provider.fetches).toHaveLength(4)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.fetches).toHaveLength(5)
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.fetches).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('counts an unknown mergeability that the watcher of a brief already knew', async () => {
|
||||
const provider = briefProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { mergeability: 'unknown' }))
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore, { state: 'open', mergeability: 'unknown', checksRollup: 'success', fetchedAt: START - 1_000 })
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('leaves a change request alone when a refresh allows the age of its latest poll', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 500 })
|
||||
context.forge.refresh(ref(9), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toHaveLength(1)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('counts the read its watcher knew as the latest poll of a brief watch', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore, { state: 'open', mergeability: 'mergeable', checksRollup: 'success', fetchedAt: START - 100 })
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(401)
|
||||
expect(provider.briefFetches).toHaveLength(0)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 500 })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)]])
|
||||
})
|
||||
|
||||
it('follows a poll in flight with another one for a plain refresh only', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const release = hold(provider, 'snapshot')
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 0 })
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
|
||||
context.forge.refresh(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
context.forge.refresh(ref(1))
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('follows a poll in flight that started before the bound of a refresh with another one', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const release = hold(provider, 'snapshot')
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 300 })
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
|
||||
context.forge.refresh(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(200)
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 199 })
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('leaves a merged change request alone for a refresh with a maximum age, and polls it for a plain one', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { state: 'merged' }))
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
context.forge.refresh(ref(1), { maxAgeMs: 0 })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
|
||||
context.forge.refresh(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('polls an announced change at once and at the active interval for one idle interval, then at the regular cadence', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
|
||||
context.forge.expectChange(ref(1))
|
||||
context.forge.expectChange(ref(9))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.briefFetches).toEqual([[ref(1)], [ref(1)]])
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.briefFetches).toHaveLength(5)
|
||||
// The poll one idle interval after the announcement ends it.
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toHaveLength(6)
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.briefFetches).toHaveLength(6)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.briefFetches).toHaveLength(7)
|
||||
})
|
||||
|
||||
it('ends an announced change once a status reports running checks', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1)))
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
provider.results.set(key, snapshot(ref(1), { checksRollup: 'pending' }))
|
||||
context.forge.expectChange(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
provider.results.set(key, snapshot(ref(1)))
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
|
||||
// Checks that settled within the idle interval of the announcement are followed at the idle interval.
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(4)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['closed', 3],
|
||||
['merged', 2],
|
||||
] as const)('ends an announced change for a %s change request', async (state, fetches) => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { state }))
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
context.forge.expectChange(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(fetches)
|
||||
})
|
||||
|
||||
it('lets a snapshot poll in flight answer a watcher that joins with a maximum age', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const context = await setup(provider)
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(600)
|
||||
const release = hold(provider, 'snapshot')
|
||||
context.forge.refresh(ref(1))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
const updates: ChangeRequestUpdate[] = []
|
||||
context.forge.watch(ref(1), (update) => { updates.push(update) }, { maxAgeMs: 500 })
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
expect(updates).toEqual([{ key, fetchedAt: START + 600, snapshot: snapshot(ref(1)) }])
|
||||
})
|
||||
|
||||
it('reads the snapshot for its first watcher while a brief poll is in flight', async () => {
|
||||
const provider = briefProvider(1)
|
||||
const release = hold(provider, 'brief')
|
||||
const context = await setup(provider)
|
||||
context.forge.watchBrief(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
context.forge.watch(ref(1), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(provider.fetches).toEqual([[ref(1)]])
|
||||
|
||||
// The brief read that ends later leaves the watch as the snapshot read timed it.
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('polls every 15 seconds while checks run and every 60 seconds once they settled, by default', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { checksRollup: 'pending' }))
|
||||
const context = await setup(provider, {})
|
||||
context.forge.watch(ref(1), ignore)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(14_999)
|
||||
expect(provider.fetches).toHaveLength(1)
|
||||
provider.results.set(key, snapshot(ref(1)))
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
await vi.advanceTimersByTimeAsync(59_999)
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(provider.fetches).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
@@ -3,11 +3,12 @@ import type { Fiber } from '@deepseek-ai/cordis'
|
||||
import ForgeService, { changeRequestKey } from '../src/index.ts'
|
||||
import type { Config } from '../src/index.ts'
|
||||
import type {
|
||||
ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness,
|
||||
ForgeRepository, MergeRequest,
|
||||
ChangeRequestBrief, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider,
|
||||
ForgeReadiness, ForgeRepository, MergeRequest,
|
||||
} from '../src/types.ts'
|
||||
|
||||
type FetchResult = ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>
|
||||
type BriefResult = ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>
|
||||
|
||||
/** Repository served by the default fake provider. */
|
||||
export const demo: ForgeRepository = { forge: 'fake', host: 'fake.test', owner: 'Octo', name: 'Demo' }
|
||||
@@ -142,6 +143,28 @@ export class FakeProvider implements ForgeProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The brief a snapshot holds, without its other fields. */
|
||||
export function brief(value: ChangeRequestSnapshot): ChangeRequestBrief {
|
||||
const { ref: target, url, title, state, draft, mergeability, reviewDecision, checksRollup } = value
|
||||
return { ref: target, url, title, state, draft, mergeability, reviewDecision, checksRollup }
|
||||
}
|
||||
|
||||
/** A {@link FakeProvider} that also reads briefs: those of `results`, unless `briefImpl` answers. */
|
||||
export class BriefProvider extends FakeProvider {
|
||||
readonly briefFetches: (readonly ChangeRequestRef[])[] = []
|
||||
briefImpl: ((refs: readonly ChangeRequestRef[], signal: AbortSignal) => Promise<BriefResult>) | undefined
|
||||
|
||||
async fetchBriefs(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise<BriefResult> {
|
||||
this.briefFetches.push(refs)
|
||||
if (this.briefImpl !== undefined) return await this.briefImpl(refs, signal)
|
||||
return new Map(refs.map((target) => {
|
||||
const key = changeRequestKey(target)
|
||||
const result = this.results.get(key) ?? { code: 'not-found', message: 'missing' }
|
||||
return [key, 'code' in result ? result : brief(result)] as const
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/** Boot a context with only the forge service. */
|
||||
export async function forgeContext(config: Config = {}): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* Fetches of a provider that names a batch size: which change requests one call reads, when a call starts and
|
||||
* settles, and what a call that fails or outlives its deadline affects.
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { changeRequestKey } from '../src/index.ts'
|
||||
import type { ChangeRequestBriefUpdate, ChangeRequestKey, ChangeRequestRef, ChangeRequestUpdate, ForgeRepository } from '../src/types.ts'
|
||||
import { brief, BriefProvider, demo, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts'
|
||||
|
||||
const config = { activeIntervalMs: 1_000, idleIntervalMs: 4_000, maxBackoffMs: 16_000, fetchTimeoutMs: 500 }
|
||||
const START = 1_000_000
|
||||
const second: ForgeRepository = { ...demo, host: 'second.test' }
|
||||
const ignore = (): void => undefined
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: START })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx?.fiber.dispose()
|
||||
ctx = undefined
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
/** A provider of two hosts that reads briefs, holding an open snapshot whose checks passed for the numbered change requests of `demo`. */
|
||||
function provider(sizes: { readonly snapshotBatchSize?: number; readonly briefBatchSize?: number }, ...numbers: number[]): BriefProvider {
|
||||
const created = Object.assign(new BriefProvider('fake', ['fake.test', 'second.test']), sizes)
|
||||
for (const number of numbers) created.results.set(changeRequestKey(ref(number)), snapshot(ref(number)))
|
||||
return created
|
||||
}
|
||||
|
||||
function snapshots(context: Context, target: ChangeRequestRef): { updates: ChangeRequestUpdate[]; unwatch: () => void } {
|
||||
const updates: ChangeRequestUpdate[] = []
|
||||
return { updates, unwatch: context.forge.watch(target, (update) => { updates.push(update) }) }
|
||||
}
|
||||
|
||||
function briefs(context: Context, target: ChangeRequestRef): { updates: ChangeRequestBriefUpdate[]; unwatch: () => void } {
|
||||
const updates: ChangeRequestBriefUpdate[] = []
|
||||
return { updates, unwatch: context.forge.watchBrief(target, (update) => { updates.push(update) }) }
|
||||
}
|
||||
|
||||
/** Make every call of `target` at one level stay pending until released or until its signal aborts. */
|
||||
function hold(target: BriefProvider, level: 'brief' | 'snapshot'): () => void {
|
||||
const releases: (() => void)[] = []
|
||||
const pending = <T>(result: (read: ChangeRequestRef) => T) => (refs: readonly ChangeRequestRef[], signal: AbortSignal) =>
|
||||
new Promise<ReadonlyMap<ChangeRequestKey, T>>((resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(signal.reason as Error) })
|
||||
releases.push(() => { resolve(new Map(refs.map(read => [changeRequestKey(read), result(read)] as const))) })
|
||||
})
|
||||
if (level === 'brief') target.briefImpl = pending(read => brief(snapshot(read)))
|
||||
else target.fetchImpl = pending(read => snapshot(read))
|
||||
return () => {
|
||||
for (const release of releases.splice(0)) release()
|
||||
}
|
||||
}
|
||||
|
||||
/** Run every microtask that is ready, without running a timer. */
|
||||
async function microtasks(): Promise<void> {
|
||||
for (let turn = 0; turn < 50; turn++) await Promise.resolve()
|
||||
}
|
||||
|
||||
const numbers = (calls: readonly (readonly ChangeRequestRef[])[]): number[][] => calls.map(refs => refs.map(read => read.number))
|
||||
|
||||
describe('forge fetches in parts', () => {
|
||||
it('calls a provider once per snapshotBatchSize change requests of a host, compared without case, in order', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 2 })
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
const refs = [ref(1), ref(2, second), ref(3, { ...demo, host: 'FAKE.test' }), ref(4), ref(5, second), ref(6, second)]
|
||||
for (const target of refs) ctx.forge.watch(target, ignore)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 3], [4], [2, 5], [6]])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['briefBatchSize change requests through fetchBriefs', { snapshotBatchSize: 5, briefBatchSize: 2 }, [[1, 2], [3]]],
|
||||
['every due change request through fetchBriefs when only snapshotBatchSize is named', { snapshotBatchSize: 2 }, [[1, 2, 3]]],
|
||||
])('reads briefs in calls of %s', async (_, sizes, calls) => {
|
||||
const reader = provider(sizes, 1, 2, 3)
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
for (const number of [1, 2, 3]) ctx.forge.watchBrief(ref(number), ignore)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.briefFetches)).toEqual(calls)
|
||||
expect(reader.fetches).toEqual([])
|
||||
})
|
||||
|
||||
it('reads briefs in calls of snapshotBatchSize through a provider that reads no briefs', async () => {
|
||||
const reader = Object.assign(new FakeProvider(), { snapshotBatchSize: 2, briefBatchSize: 1 })
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
for (const number of [1, 2, 3]) ctx.forge.watchBrief(ref(number), ignore)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2], [3]])
|
||||
})
|
||||
|
||||
it('starts a call once the one before it returned, and settles the results of each call when it returns', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 2 })
|
||||
const release = hold(reader, 'snapshot')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
const watched = [1, 2, 3].map(number => snapshots(ctx!, ref(number)))
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2]])
|
||||
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2], [3]])
|
||||
expect(watched.map(watch => watch.updates.map(update => update.fetchedAt))).toEqual([[START + 100], [START + 100], []])
|
||||
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(watched[2]?.updates).toEqual([{ key: changeRequestKey(ref(3)), fetchedAt: START + 200, snapshot: snapshot(ref(3)) }])
|
||||
})
|
||||
|
||||
it('gives each call its own deadline, so a call that outlives it fails only its own change requests', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 2 })
|
||||
reader.fetchImpl = (refs, signal) => new Promise((resolve, reject) => {
|
||||
if (refs.some(read => read.number === 1)) signal.addEventListener('abort', () => { reject(signal.reason as Error) })
|
||||
else resolve(new Map(refs.map(read => [changeRequestKey(read), snapshot(read)] as const)))
|
||||
})
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
const watched = [1, 2, 3, 4].map(number => snapshots(ctx!, ref(number)))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(499)
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2]])
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
|
||||
const late = { code: 'unavailable', message: 'FORGE_FETCH_TIMEOUT after 500ms' }
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2], [3, 4]])
|
||||
expect(watched.map(watch => watch.updates)).toEqual([
|
||||
[{ key: changeRequestKey(ref(1)), fetchedAt: START + 500, failure: late }],
|
||||
[{ key: changeRequestKey(ref(2)), fetchedAt: START + 500, failure: late }],
|
||||
[{ key: changeRequestKey(ref(3)), fetchedAt: START + 500, snapshot: snapshot(ref(3)) }],
|
||||
[{ key: changeRequestKey(ref(4)), fetchedAt: START + 500, snapshot: snapshot(ref(4)) }],
|
||||
])
|
||||
})
|
||||
|
||||
it('fails only the change requests of a call that rejects', async () => {
|
||||
const reader = provider({ briefBatchSize: 1 }, 1, 2, 3)
|
||||
reader.briefImpl = async (refs) => {
|
||||
if (refs[0]?.number === 2) throw new Error('refused')
|
||||
return new Map(refs.map(read => [changeRequestKey(read), brief(snapshot(read))] as const))
|
||||
}
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
const watched = [1, 2, 3].map(number => briefs(ctx!, ref(number)))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(watched.map(watch => watch.updates.map(update => 'failure' in update ? update.failure.message : update.brief.title)))
|
||||
.toEqual([['Change 1'], ['refused'], ['Change 3']])
|
||||
})
|
||||
|
||||
it('calls nothing for a part whose watches all ended while they waited, and frees the forge for the next fetch', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 2 })
|
||||
const release = hold(reader, 'snapshot')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
const watched = [1, 2, 3].map(number => snapshots(ctx!, ref(number)))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
watched[2]?.unwatch()
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2]])
|
||||
|
||||
ctx.forge.watch(ref(4), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2], [4]])
|
||||
})
|
||||
|
||||
it('leaves out of a brief call a change request whose snapshot was read while it waited', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 1, briefBatchSize: 1 }, 1, 2)
|
||||
const release = hold(reader, 'brief')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
ctx.forge.watchBrief(ref(1), ignore)
|
||||
const list = briefs(ctx, ref(2))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
// A panel opens on the waiting change request: its snapshot is read at once, beside the brief call in flight.
|
||||
ctx.forge.watch(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(numbers(reader.fetches)).toEqual([[2]])
|
||||
expect(list.updates).toHaveLength(1)
|
||||
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(numbers(reader.briefFetches)).toEqual([[1]])
|
||||
expect(list.updates).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('lets the snapshot fetch read a change request that gained a snapshot watcher just before its brief call', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 1, briefBatchSize: 1 }, 1, 2)
|
||||
const release = hold(reader, 'brief')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
ctx.forge.watchBrief(ref(1), ignore)
|
||||
ctx.forge.watchBrief(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
// The call before its own returns before the timer of the new watcher runs.
|
||||
const panel = snapshots(ctx, ref(2))
|
||||
release()
|
||||
await microtasks()
|
||||
expect(numbers(reader.briefFetches)).toEqual([[1]])
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[2]])
|
||||
expect(numbers(reader.briefFetches)).toEqual([[1]])
|
||||
expect(panel.updates).toEqual([{ key: changeRequestKey(ref(2)), fetchedAt: START, snapshot: snapshot(ref(2)) }])
|
||||
})
|
||||
|
||||
it('lets the brief fetch read a change request that lost its snapshot watchers while it waited for a snapshot call', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 1, briefBatchSize: 1 }, 1, 2)
|
||||
const release = hold(reader, 'snapshot')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
ctx.forge.watch(ref(1), ignore)
|
||||
const panel = snapshots(ctx, ref(2))
|
||||
const list = briefs(ctx, ref(2))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
panel.unwatch()
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[1]])
|
||||
expect(numbers(reader.briefFetches)).toEqual([[2]])
|
||||
expect(list.updates).toEqual([{ key: changeRequestKey(ref(2)), fetchedAt: START, brief: brief(snapshot(ref(2))) }])
|
||||
})
|
||||
|
||||
it('answers a refresh asked for while a change request waited with the call that reads it', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 1 })
|
||||
const release = hold(reader, 'snapshot')
|
||||
ctx = await forgeContext(config)
|
||||
await provide(ctx, reader)
|
||||
ctx.forge.watch(ref(1), ignore)
|
||||
ctx.forge.watch(ref(2), ignore)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
ctx.forge.refresh(ref(2))
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
release()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[1], [2]])
|
||||
})
|
||||
|
||||
it('calls no further part of a provider that was withdrawn during a call', async () => {
|
||||
const reader = provider({ snapshotBatchSize: 2 })
|
||||
hold(reader, 'snapshot')
|
||||
ctx = await forgeContext(config)
|
||||
const fiber = await provide(ctx, reader)
|
||||
const watched = [1, 2, 3].map(number => snapshots(ctx!, ref(number)))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
await fiber.dispose()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(numbers(reader.fetches)).toEqual([[1, 2]])
|
||||
expect(watched.map(watch => watch.updates.map(update => 'failure' in update && update.failure.message)))
|
||||
.toEqual(Array.from({ length: 3 }, () => ['no provider is registered for "fake"']))
|
||||
})
|
||||
|
||||
it.each([
|
||||
['snapshotBatchSize', 0],
|
||||
['snapshotBatchSize', 2.5],
|
||||
['briefBatchSize', -1],
|
||||
['briefBatchSize', Number.MAX_SAFE_INTEGER + 1],
|
||||
] as const)('refuses a provider whose %s is %s', async (key, size) => {
|
||||
ctx = await forgeContext(config)
|
||||
|
||||
await expect(provide(ctx, Object.assign(new FakeProvider(), { [key]: size })))
|
||||
.rejects.toThrow(`forge: ${key} of the "fake" provider must be a positive safe integer`)
|
||||
expect(ctx.forge.describe('fake')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -119,17 +119,6 @@ describe('forge watch', () => {
|
||||
expect(provider.fetches).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('treats unknown mergeability as active work', async () => {
|
||||
const provider = new FakeProvider()
|
||||
provider.results.set(key, snapshot(ref(1), { mergeability: 'unknown' }))
|
||||
const context = await setup(provider)
|
||||
collect(context)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
|
||||
expect(provider.fetches).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('backs off after consecutive failures up to the cap and resets after success', async () => {
|
||||
const provider = new FakeProvider()
|
||||
const context = await setup(provider)
|
||||
|
||||
@@ -1340,14 +1340,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
{
|
||||
key: 'forge',
|
||||
summary: 'Registry of forge providers.',
|
||||
description: 'Registry of forge providers. Watchers of one change request share a single polling loop; each forge has at most one fetch in flight, which batches every due change request of that forge.',
|
||||
description: 'Registry of forge providers. Watchers of one change request share a single polling loop, which reads its snapshot while a snapshot watcher remains and its brief otherwise. Each forge has at most one snapshot fetch and one brief fetch in flight; each batches every due change request of that forge at its level, and those past the midpoint of the wait after a status, so change requests that became due at different times come to share one fetch. A fetch calls a provider that names a batch size once per that many change requests of a host, and settles the results of each call when it returns.',
|
||||
methods: [
|
||||
{
|
||||
signature: 'register(provider: ForgeProvider): () => Promise<void>',
|
||||
description: 'Register the provider of one forge family as an effect on the calling fiber. Watches of that forge receive an `unavailable` failure when the registration ends. Unregistering cancels and awaits its in-flight calls; results from the withdrawn registration are discarded.',
|
||||
parameters: [{ name: 'provider', description: 'provider to serve `provider.forge` on `provider.hosts`.' }],
|
||||
returns: 'the disposer that unregisters the provider and waits for its calls to finish.',
|
||||
throws: ['when another provider already serves the same forge or one of the same hosts, compared without case.'],
|
||||
throws: ['when another provider already serves the same forge or one of the same hosts, compared without case, and when the provider names a batch size that is not a positive safe integer.'],
|
||||
},
|
||||
{
|
||||
signature: 'describe(forge: string): ForgeDescription | undefined',
|
||||
@@ -1541,21 +1541,32 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['when no provider serves the change request\'s forge.'],
|
||||
},
|
||||
{
|
||||
signature: 'watch(ref: ChangeRequestRef, listener: ChangeRequestListener): () => void',
|
||||
description: 'Watch one change request as an effect on the calling fiber. The first watcher starts polling at once; listeners receive every later result, and `latest` returns the current one. Polling stops when the last watcher leaves. Listeners must not throw; a thrown error is logged and skipped.',
|
||||
parameters: [{ name: 'ref', description: 'change request to poll.' }, { name: 'listener', description: 'receives each polling result.' }],
|
||||
signature: 'watch(ref: ChangeRequestRef, listener: ChangeRequestListener, options: ChangeRequestWatchOptions = {}): () => void',
|
||||
description: 'Watch the snapshot of one change request as an effect on the calling fiber. Its first snapshot watcher polls it at once, and a later one does when `options.maxAgeMs` is given and the latest result is older. Listeners receive every later snapshot poll result, and `latest` returns the current one. While a snapshot watcher remains, polls read the snapshot; polling stops when the last watcher of the snapshot and the brief leaves. Listeners must not throw; a thrown error is logged and skipped.',
|
||||
parameters: [{ name: 'ref', description: 'change request to poll.' }, { name: 'listener', description: 'receives each snapshot poll result.' }, { name: 'options', description: 'when the watcher needs a status newer than the latest one.' }],
|
||||
returns: 'the disposer that stops this watch.',
|
||||
},
|
||||
{
|
||||
signature: 'refresh(ref: ChangeRequestRef): void',
|
||||
description: 'Poll a watched change request at once, including after a terminal state. A fetch already in flight is followed immediately by another fetch; an unwatched change request is unchanged.',
|
||||
parameters: [{ name: 'ref', description: 'change request to poll.' }],
|
||||
signature: 'watchBrief(ref: ChangeRequestRef, listener: ChangeRequestBriefListener, known?: ChangeRequestKnownState): () => void',
|
||||
description: 'Watch the brief of one change request as an effect on the calling fiber. Listeners receive the brief of every later poll result: of a brief read while only brief watchers remain, and of a snapshot read otherwise. The first watcher of a change request polls it at once, or as `known` times it. Polling stops when the last watcher of the snapshot and the brief leaves. Listeners must not throw; a thrown error is logged and skipped.',
|
||||
parameters: [{ name: 'ref', description: 'change request to poll.' }, { name: 'listener', description: 'receives the brief of each poll result.' }, { name: 'known', description: 'the state the caller last saw, which times the first poll of a change request without a watcher.' }],
|
||||
returns: 'the disposer that stops this watch.',
|
||||
},
|
||||
{
|
||||
signature: 'refresh(ref: ChangeRequestRef, options: ChangeRequestWatchOptions = {}): void',
|
||||
description: 'Poll a watched change request at once, including after a terminal state. A fetch already in flight is followed immediately by another fetch; an unwatched change request is unchanged. With `options.maxAgeMs`, the caller needs a status no older than that many milliseconds: a change request whose latest poll at either level, in flight or settled, started within them is left alone, and so is a merged one, whose status is final.',
|
||||
parameters: [{ name: 'ref', description: 'change request to poll.' }, { name: 'options', description: 'when the caller needs a status newer than the latest one.' }],
|
||||
},
|
||||
{
|
||||
signature: 'expectChange(ref: ChangeRequestRef): void',
|
||||
description: 'Announce that a watched change request is about to change, as after a push to its head branch. It is polled at once and then every `activeIntervalMs`, until a status reports running checks or a closed or merged change request, and for at most `idleIntervalMs`; after that the regular cadence applies. A fetch already in flight is followed immediately by another fetch; an unwatched change request is unchanged.',
|
||||
parameters: [{ name: 'ref', description: 'change request the caller expects to change.' }],
|
||||
},
|
||||
{
|
||||
signature: 'latest(ref: ChangeRequestRef): ChangeRequestUpdate | undefined',
|
||||
description: 'Read the latest polling result of a watched change request.',
|
||||
description: 'Read the latest snapshot poll result of a watched change request.',
|
||||
parameters: [{ name: 'ref', description: 'change request to read.' }],
|
||||
returns: 'the latest result, or undefined before the first result or without a watch.',
|
||||
returns: 'the latest result, or undefined before the first snapshot poll settled or without a watch.',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -1664,9 +1675,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['`forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-too-large` or `forgePanel/diff-failed` when the host does not provide the file.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>',
|
||||
description: 'Read the signed-in user\'s viewed marks on the files of a change request the review page shows.',
|
||||
parameters: [{ name: 'url', description: 'web URL of the change request.' }, { name: 'headSha', description: 'head commit of the shown diff.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
signature: '@Remote async reviewViewed(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeViewedFiles | null>',
|
||||
description: 'Read the signed-in user\'s viewed marks on the files of a change request the review page shows, as ForgePanelController.changeRequestViewed keeps them.',
|
||||
parameters: [{ name: 'url', description: 'web URL of the change request.' }, { name: 'headSha', description: 'head commit of the shown diff.' }, { name: 'fresh', description: 'whether to read the host although kept marks could answer, as after a refresh.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the marks, or null when the provider keeps no viewed marks.',
|
||||
throws: ['`forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does.'],
|
||||
},
|
||||
@@ -1756,6 +1767,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
parameters: [{ name: 'sessionId', description: 'Session whose panel refreshes; refreshing neither loads nor resumes it.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void>',
|
||||
description: 'Bring a followed Session\'s panel up to date after its surface showed again: reinspect the checkout, poll the change requests whose latest poll is older than `statusMaxAgeMs`, probe sign-in again unless the last probe found the host ready, and look the upstream branch up again while the Session shows no change request; an unfollowed Session is unchanged.',
|
||||
parameters: [{ name: 'sessionId', description: 'Session whose panel is revisited; revisiting neither loads nor resumes it.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff>',
|
||||
description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, with Git using the Session\'s sandbox policy.',
|
||||
@@ -1826,9 +1843,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['`forgePanel/lens-missing` while no lens holds the identity or once its registration ends; `forgePanel/lens-stale` before a change request\'s status was read, when the files differ from `request.version`, and when local files changed while the lens ran; `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | null>',
|
||||
description: 'Read the signed-in user\'s viewed marks on the files of a change request of a Session, which the host keeps for the whole change request.',
|
||||
parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'headSha', description: 'head commit of the shown diff; marks read at another head are refused.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
signature: '@Remote async changeRequestViewed( session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal, ): Promise<ForgeViewedFiles | null>',
|
||||
description: 'Read the signed-in user\'s viewed marks on the files of a change request of a Session, which the host keeps for the whole change request. Marks read at the same head are kept in memory and returned until they are `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a mark saved through `ctx.forge` at that head replaces the kept state of its file, so the read after a save costs no request.',
|
||||
parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'headSha', description: 'head commit of the shown diff; marks read at another head are refused.' }, { name: 'fresh', description: 'whether to read the host although kept marks could answer, as after a refresh.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the marks at `headSha`, or null when the provider keeps no viewed marks.',
|
||||
throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed` when the host does not provide the marks otherwise.'],
|
||||
},
|
||||
@@ -1968,9 +1985,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
parameters: [{ name: 'session', description: 'Session that owns the binding.' }, { name: 'url', description: 'web URL of the change request.' }],
|
||||
},
|
||||
{
|
||||
signature: 'watch(session: Session, listener: SessionChangeRequestsListener): () => void',
|
||||
description: 'Watch a Session\'s visible change requests as an effect on the calling fiber. Every visible change request that a provider recognizes is polled through `ctx.forge` while the Session has a watcher. Listeners receive the complete list after each later binding or provider change, or polling result; read the current list with changeRequests. Listeners must not throw; a thrown error is logged and skipped.',
|
||||
parameters: [{ name: 'session', description: 'Session to watch.' }, { name: 'listener', description: 'receives the complete visible list.' }],
|
||||
signature: 'watch(session: Session, listener: SessionChangeRequestsListener, options: ChangeRequestWatchOptions = {}): () => void',
|
||||
description: 'Watch a Session\'s visible change requests as an effect on the calling fiber. Every visible change request that a provider recognizes is polled for its snapshot through `ctx.forge` while the Session has a watcher. Listeners receive the complete list after each later binding or provider change, or polling result; read the current list with changeRequests. Listeners must not throw; a thrown error is logged and skipped.',
|
||||
parameters: [{ name: 'session', description: 'Session to watch.' }, { name: 'listener', description: 'receives the complete visible list.' }, { name: 'options', description: 'when the Session\'s first watcher needs a status newer than the latest one; a later watcher\'s options change nothing.' }],
|
||||
returns: 'the disposer that stops this watch.',
|
||||
},
|
||||
],
|
||||
@@ -6686,6 +6703,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ButtonProps',
|
||||
declaration: 'export interface ButtonProps {\n readonly label: string;\n readonly hotkey?: string | undefined;\n readonly disabled?: boolean | undefined;\n readonly onPress?: (() => unknown) | undefined;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestBrief',
|
||||
declaration: 'export type ChangeRequestBrief = Pick<ChangeRequestSnapshot, \'ref\' | \'url\' | \'title\' | \'state\' | \'draft\' | \'mergeability\' | \'reviewDecision\' | \'checksRollup\'>;',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestBriefListener',
|
||||
declaration: 'export type ChangeRequestBriefListener = (update: ChangeRequestBriefUpdate) => void;',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestBriefUpdate',
|
||||
declaration: 'export type ChangeRequestBriefUpdate = {\n readonly key: ChangeRequestKey;\n readonly fetchedAt: number;\n} & ({\n readonly brief: ChangeRequestBrief;\n} | {\n readonly failure: ForgeFailure;\n});',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestCheck',
|
||||
declaration: 'export interface ChangeRequestCheck {\n readonly name: string;\n readonly state: CheckState;\n readonly url: string | null;\n readonly workflow: string | null;\n readonly startedAt: string | null;\n readonly completedAt: string | null;\n readonly rerun: ForgeCheckId | null;\n}',
|
||||
@@ -6702,6 +6731,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ChangeRequestKey',
|
||||
declaration: 'export type ChangeRequestKey = Branded<\'ChangeRequestKey\'>;',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestKnownState',
|
||||
declaration: 'export interface ChangeRequestKnownState extends Pick<ChangeRequestBrief, \'state\' | \'mergeability\' | \'checksRollup\'> {\n readonly fetchedAt: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestLabel',
|
||||
declaration: 'export interface ChangeRequestLabel {\n readonly name: string;\n readonly color: string | null;\n}',
|
||||
@@ -6742,6 +6775,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ChangeRequestViewerReview',
|
||||
declaration: 'export interface ChangeRequestViewerReview {\n readonly verdict: ReviewVerdict;\n readonly reviewedSha: string | null;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestWatchOptions',
|
||||
declaration: 'export interface ChangeRequestWatchOptions {\n readonly maxAgeMs?: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeResult',
|
||||
declaration: 'export interface ChangeResult {\n changed: boolean;\n application: \'applied\' | \'restart-required\' | \'overridden\' | \'failed\' | \'cancelled\';\n restartReason?: RestartReason;\n stage: \'install\' | \'enable\' | \'remove\';\n target: string;\n enabled?: boolean;\n error?: ManagementError;\n warnings?: string[];\n packageResult?: PackageResult;\n bundle?: string;\n version?: string;\n pendingBuilds?: string[];\n approvedBuilds?: string[];\n registries?: Registry[];\n failedAt?: \'registry\' | \'spec-host\';\n}',
|
||||
@@ -7664,7 +7701,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgeProvider',
|
||||
declaration: 'export interface ForgeProvider {\n readonly forge: string;\n readonly hosts: readonly string[];\n readonly label: string;\n readonly changeRequestNoun: ChangeRequestNoun;\n readonly viewer?: ForgeViewerCapability;\n listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>;\n countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>;\n readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>;\n readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>;\n writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure>;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]>;\n readin /* …truncated — full shape in source */',
|
||||
declaration: 'export interface ForgeProvider {\n readonly forge: string;\n readonly hosts: readonly string[];\n readonly label: string;\n readonly changeRequestNoun: ChangeRequestNoun;\n readonly viewer?: ForgeViewerCapability;\n listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>;\n countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>;\n readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>;\n readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>;\n writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>>;\n fetchBriefs?(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestBrief | ForgeFailure>>;\n readonly snapshotBatchSize?: number;\n readonly briefBatchSize?: number;\n fetchCh /* …truncated — full shape in source */',
|
||||
},
|
||||
{
|
||||
name: 'ForgeReadiness',
|
||||
|
||||
@@ -435,7 +435,10 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
WorktreeCleanup: 'worktrees.md',
|
||||
WorktreeCreation: 'worktrees.md',
|
||||
RestoredWorktree: 'worktrees.md',
|
||||
ChangeRequestBriefListener: 'forge.md',
|
||||
ChangeRequestKnownState: 'forge.md',
|
||||
ChangeRequestListener: 'forge.md',
|
||||
ChangeRequestWatchOptions: 'forge.md',
|
||||
ChangeRequestRef: 'forge.md',
|
||||
ChangeRequestSnapshot: 'forge.md',
|
||||
ChangeRequestUpdate: 'forge.md',
|
||||
|
||||
@@ -2539,6 +2539,31 @@
|
||||
"symbol": "ChangeRequestListener",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestBrief",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestBriefUpdate",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestBriefListener",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestWatchOptions",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestKnownState",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "SessionChangeRequestsListener",
|
||||
|
||||
Reference in new issue
Block a user