perf(forge-panel): keep viewed marks on the Host and keep threads across a saved mark
Every saved viewed mark announced a review change, which dropped the review threads kept for the change request and made each open changes view read all viewed marks and all threads from the code host again. The Host now keeps the viewed marks it read for a change request by head commit, under the bounds the kept threads have. A mark saved through ctx.forge at that head replaces the kept state of its file, and the kept threads stay, since a viewed mark changes no thread. The read that follows a save is answered from memory, so a save costs the provider's write and no further read. The reader's refresh passes fresh and reads the code host again, as it does for threads. ReviewCache is generic over what it keeps and gains amend() for a write whose effect on the kept read is known.
This commit is contained in:
1 parent
40f74e81e6
commit
ac69d4b1a9
17 files changed
+309
-102
No files matched your search
@@ -2458,6 +2458,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')
|
||||
@@ -2467,6 +2478,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')
|
||||
|
||||
@@ -1272,11 +1272,15 @@ 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
|
||||
/**
|
||||
@@ -1333,7 +1337,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:823`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:824`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
|
||||
@@ -1274,11 +1274,15 @@ 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
|
||||
/**
|
||||
@@ -1335,7 +1339,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:823`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:824`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 44e46809de624c40
|
||||
zh: 934dd10fbc7b7b14
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: 36cdf82bcd410f9f
|
||||
zh: 8f4e48cae1e7b7e2
|
||||
en: ea018cbd4c2357cb
|
||||
zh: 1a73b620bf7ad1a0
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
|
||||
@@ -73,9 +73,9 @@ 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 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.
|
||||
|
||||
|
||||
@@ -73,9 +73,9 @@ 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.watchBrief` 监听每个已绑定变更请求的简报,同时告知自己持有的状态:已合并的不再读取,本进程此前的运行读过的等到间隔到期,其他已存的立即读取。已关闭的按空闲间隔轮询,已合并的保留监听,以接收显式刷新和面板的快照读取结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 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
|
||||
@@ -730,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') {
|
||||
@@ -742,6 +751,7 @@ export function ChangesView({
|
||||
setFailure(null)
|
||||
return
|
||||
}
|
||||
finishedAttempt.current = attempt
|
||||
setFinished(read)
|
||||
if (result.ok) {
|
||||
setLoaded({ key: dataKey, data: result.value })
|
||||
@@ -751,7 +761,7 @@ 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
|
||||
|
||||
@@ -378,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),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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'
|
||||
@@ -133,7 +133,9 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
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. */
|
||||
@@ -179,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 () => {
|
||||
@@ -228,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()
|
||||
@@ -495,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)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -984,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;
|
||||
@@ -995,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)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1472,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')
|
||||
@@ -1658,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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -620,11 +620,15 @@ 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
|
||||
/**
|
||||
|
||||
@@ -2140,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')
|
||||
|
||||
@@ -2222,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()
|
||||
@@ -2298,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'
|
||||
@@ -2066,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)
|
||||
|
||||
@@ -224,7 +224,7 @@ 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),
|
||||
@@ -285,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' })),
|
||||
@@ -1053,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)
|
||||
@@ -1734,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)
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -298,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 () => {
|
||||
@@ -439,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),
|
||||
@@ -474,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),
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user