feat(forge): list the signed-in user's change requests and read descriptions
ForgeProvider gains an optional viewer capability with listForViewer and countForViewer, which read the review-requested, authored, and involved lists of open change requests on a host, and readDescription, which reads a change request's Markdown description, labels, and image addresses a browser can load without a host session. ForgeFailure.code gains rate-limited. forge-github reads each list through one GraphQL search (one document that searches several lists draws a gateway error), counts all lists in one request, pairs uploaded images with the signed addresses of the rendered description, and reports GitHub rate limits as rate-limited. Refs #8312
This commit is contained in:
1 parent
5e7206f6c6
commit
f71ee7cb2e
35 files changed
+1637
-45
No files matched your search
@@ -1221,7 +1221,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:732`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1266,6 +1266,8 @@ export interface Config {
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
maxViewedFiles?: number
|
||||
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
|
||||
maxViewerItems?: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
|
||||
|
||||
@@ -1223,7 +1223,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:732`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1268,6 +1268,8 @@ export interface Config {
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
maxViewedFiles?: number
|
||||
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
|
||||
maxViewerItems?: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
|
||||
|
||||
@@ -19,7 +19,10 @@
|
||||
zh: 1b7d7671ec36a5b2
|
||||
/forges/overview-and-viewed-marks:
|
||||
en: fd5928603c9375b1
|
||||
zh: 1a3bca55344ff385
|
||||
zh: e5e32a588a18abae
|
||||
/forges/viewer-lists-and-descriptions:
|
||||
en: 05dba49e668fbd82
|
||||
zh: 7502689f5dd46118
|
||||
/forges/session-bindings:
|
||||
en: 13dfd36f2166bba0
|
||||
zh: a369434f52f04d57
|
||||
|
||||
+190
-2
@@ -45,6 +45,20 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'>
|
||||
interface ForgeProvider {
|
||||
/** Forge family name stored in every repository this provider returns. */
|
||||
readonly forge: string
|
||||
/**
|
||||
* Where and which lists of the signed-in user's change requests this provider reads. A provider declares `viewer` and
|
||||
* implements `listForViewer` and `countForViewer` together; omitting any declares that it reads no viewer lists.
|
||||
*/
|
||||
readonly viewer?: ForgeViewerCapability
|
||||
/**
|
||||
* Read one viewer list, most recently updated first. A query outside {@link ForgeProvider.viewer} resolves to an
|
||||
* `unsupported` failure.
|
||||
*/
|
||||
listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>
|
||||
/** Count the change requests in every list of {@link ForgeViewerCapability.filters} on one of its hosts. */
|
||||
countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */
|
||||
readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
|
||||
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
|
||||
/**
|
||||
@@ -317,9 +331,11 @@ interface ForgeFailure {
|
||||
* `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected;
|
||||
* `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails
|
||||
* the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of
|
||||
* a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure.
|
||||
* a later status can succeed; `rate-limited`: the host refused the read under its rate limit, so reading again
|
||||
* succeeds only after the limit resets; `unsupported`: the provider does not offer the read; `unavailable`: any other
|
||||
* failure.
|
||||
*/
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable'
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'rate-limited' | 'unsupported' | 'unavailable'
|
||||
/** Human-readable cause. */
|
||||
readonly message: string
|
||||
}
|
||||
@@ -709,6 +725,143 @@ interface ForgeViewedRequest {
|
||||
}
|
||||
```
|
||||
|
||||
## Viewer lists and descriptions
|
||||
|
||||
A provider that declares `viewer` reads three lists of open change requests that involve the signed-in user on each of its hosts: `review-requested`, `authored`, and `involved`, which never share a change request. `ctx.forge.viewerSources()` names each provider's hosts, lists, and `maxItems`; `ctx.forge.listForViewer` reads one list most recently updated first, as `ChangeRequestSummary` items without the checks, reviewers, and merge state of a snapshot; and `ctx.forge.countForViewer` reads the size of every list on one host. Neither read joins status polling: a caller polls a list itself and watches each change request it shows in full. A provider, host, or list that offers no viewer list resolves to `unsupported`, and a host that refuses under its rate limit resolves to `rate-limited`.
|
||||
|
||||
`ctx.forge.readDescription` reads the Markdown description and labels of a change request; raw HTML in its `body` must not render as HTML. `images` maps each image address a browser cannot load without the user's host session to an address the host issued for loading that image without one; those addresses stop loading at `imagesExpireAt`, after which a reader reads the description again. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns the searches and the image pairing.
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* A list of open change requests that involve the signed-in user: `review-requested` asks the user or one of the user's
|
||||
* teams for a review; `authored` names the user as author; `involved` names the user in any other way, as an assignee,
|
||||
* a commenter, a reviewer, or a mention, and holds none of the other two lists' change requests.
|
||||
*/
|
||||
type ForgeViewerFilter = 'review-requested' | 'authored' | 'involved'
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Hosts a provider lists change requests on for the signed-in user, and the lists it offers there. */
|
||||
interface ForgeViewerCapability {
|
||||
/** Lowercase host names, each one this provider serves. */
|
||||
readonly hosts: readonly string[]
|
||||
/** The lists the provider reads on each of `hosts`. */
|
||||
readonly filters: ReadonlySet<ForgeViewerFilter>
|
||||
/** Most change requests one read returns, a positive integer. */
|
||||
readonly maxItems: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A registered provider's viewer lists, as {@link ForgeViewerCapability} with the forge family that offers them. */
|
||||
interface ForgeViewerSource extends ForgeViewerCapability {
|
||||
/** Forge family of the provider. */
|
||||
readonly forge: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One read of a list of open change requests that involve the signed-in user on one host. */
|
||||
interface ForgeViewerQuery {
|
||||
/** Lowercase host name from the provider's {@link ForgeViewerCapability.hosts}. */
|
||||
readonly host: string
|
||||
/** The list to read, from the provider's {@link ForgeViewerCapability.filters}. */
|
||||
readonly filter: ForgeViewerFilter
|
||||
/** One repository to read in, or null for every repository the user can read on `host`. */
|
||||
readonly repository: Pick<ForgeRepository, 'owner' | 'name'> | null
|
||||
/** Most change requests returned, a positive integer no greater than {@link ForgeViewerCapability.maxItems}. */
|
||||
readonly limit: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The signed-in user's latest submitted review of a change request. */
|
||||
interface ChangeRequestViewerReview {
|
||||
/** Outcome of the review. */
|
||||
readonly verdict: ReviewVerdict
|
||||
/** Commit the review was on, or null when the host reports none. */
|
||||
readonly reviewedSha: string | null
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Status of one change request as a viewer list reports it, without the checks, reviewers, and merge state of a snapshot. */
|
||||
interface ChangeRequestSummary {
|
||||
/** The change request. */
|
||||
readonly ref: ChangeRequestRef
|
||||
/** Web page of the change request. */
|
||||
readonly url: string
|
||||
/** Title as the author wrote it. */
|
||||
readonly title: string
|
||||
/** Whether the author marked the change request as a draft. */
|
||||
readonly draft: boolean
|
||||
/** Author, or null when the host hides the account. */
|
||||
readonly author: ForgeCommentAuthor | null
|
||||
/** Commit object name at the head of the change request. */
|
||||
readonly headSha: string
|
||||
/** Combined check outcome on the head commit. */
|
||||
readonly checksRollup: ChecksRollup
|
||||
/** Aggregate review outcome. */
|
||||
readonly reviewDecision: ReviewDecision
|
||||
/** The signed-in user's latest submitted review, or null before the first. */
|
||||
readonly viewerReview: ChangeRequestViewerReview | null
|
||||
/**
|
||||
* The review request that asks the signed-in user, or null when none does: `team` names the team, as
|
||||
* `organization/slug`, when the request asks a team the user belongs to rather than the user.
|
||||
*/
|
||||
readonly viewerRequest: { readonly team: string | null } | null
|
||||
/** Issues the host closes once the change request merges, in host order, at most the provider's limit. */
|
||||
readonly closingIssues: readonly ChangeRequestIssue[]
|
||||
/** Whether the host reported more closing issues than `closingIssues` holds. */
|
||||
readonly closingIssuesTruncated: boolean
|
||||
/** ISO 8601 time of the host's last update to the change request. */
|
||||
readonly updatedAt: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One page of a viewer list, most recently updated first. */
|
||||
interface ForgeViewerList {
|
||||
/** Login of the signed-in user the provider read as. */
|
||||
readonly viewer: string
|
||||
/** Change requests most recently updated first, at most the query's limit. */
|
||||
readonly items: readonly ChangeRequestSummary[]
|
||||
/** Number of change requests the host reports in the whole list; more than `items` holds when the list was cut. */
|
||||
readonly total: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The description of a change request as its author wrote it. */
|
||||
interface ChangeRequestDescription {
|
||||
/** Markdown source; it may contain raw HTML, which readers must not render as HTML. Empty without a description. */
|
||||
readonly body: string
|
||||
/** Labels in host order, at most the provider's limit. */
|
||||
readonly labels: readonly ChangeRequestLabel[]
|
||||
/** Whether the change request has more labels than `labels` holds. */
|
||||
readonly labelsTruncated: boolean
|
||||
/**
|
||||
* Image addresses that a browser cannot load without the user's host session, each mapped to an address the host
|
||||
* issued for loading that image without one. Addresses not listed load as written.
|
||||
*/
|
||||
readonly images: Readonly<Record<string, string>>
|
||||
/** ISO 8601 time after which the addresses in `images` stop loading, or null when there are none or the host names no time. */
|
||||
readonly imagesExpireAt: string | null
|
||||
/** ISO 8601 time the change request was created. */
|
||||
readonly createdAt: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One label of a change request. */
|
||||
interface ChangeRequestLabel {
|
||||
/** Name as the host spells it. */
|
||||
readonly name: string
|
||||
/** Six-digit hexadecimal color without `#`, or null when the host reports none. */
|
||||
readonly color: string | null
|
||||
}
|
||||
```
|
||||
|
||||
## Session bindings
|
||||
|
||||
`ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules.
|
||||
@@ -1548,6 +1701,41 @@ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSi
|
||||
*/
|
||||
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* List the viewer lists every registered provider offers; `forge/providers-changed` announces a change.
|
||||
* @returns one source per provider that declares viewer lists and reads them, in registration order.
|
||||
*/
|
||||
viewerSources(): ForgeViewerSource[]
|
||||
|
||||
/**
|
||||
* Read one list of open change requests that involve the signed-in user.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param query - host, list, repository, and limit of the read.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Count the change requests in each viewer list a provider offers on one host.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param host - lowercase host name the provider lists on.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Read the description and labels of a change request.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
|
||||
+192
-2
@@ -45,6 +45,20 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'>
|
||||
interface ForgeProvider {
|
||||
/** Forge family name stored in every repository this provider returns. */
|
||||
readonly forge: string
|
||||
/**
|
||||
* Where and which lists of the signed-in user's change requests this provider reads. A provider declares `viewer` and
|
||||
* implements `listForViewer` and `countForViewer` together; omitting any declares that it reads no viewer lists.
|
||||
*/
|
||||
readonly viewer?: ForgeViewerCapability
|
||||
/**
|
||||
* Read one viewer list, most recently updated first. A query outside {@link ForgeProvider.viewer} resolves to an
|
||||
* `unsupported` failure.
|
||||
*/
|
||||
listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>
|
||||
/** Count the change requests in every list of {@link ForgeViewerCapability.filters} on one of its hosts. */
|
||||
countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */
|
||||
readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
|
||||
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
|
||||
/**
|
||||
@@ -317,9 +331,11 @@ interface ForgeFailure {
|
||||
* `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected;
|
||||
* `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails
|
||||
* the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of
|
||||
* a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure.
|
||||
* a later status can succeed; `rate-limited`: the host refused the read under its rate limit, so reading again
|
||||
* succeeds only after the limit resets; `unsupported`: the provider does not offer the read; `unavailable`: any other
|
||||
* failure.
|
||||
*/
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable'
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'rate-limited' | 'unsupported' | 'unavailable'
|
||||
/** Human-readable cause. */
|
||||
readonly message: string
|
||||
}
|
||||
@@ -711,6 +727,145 @@ interface ForgeViewedRequest {
|
||||
}
|
||||
```
|
||||
|
||||
<a id="viewer-lists-and-descriptions"></a>
|
||||
|
||||
## 登录用户的列表与描述
|
||||
|
||||
声明了 `viewer` 的提供方在它的每个主机上读取与登录用户有关的三类打开的变更请求:`review-requested`、`authored` 与 `involved`,三者互不重叠。`ctx.forge.viewerSources()` 列出每个提供方的主机、列表与 `maxItems`;`ctx.forge.listForViewer` 按最近更新在前读取一个列表,每项是 `ChangeRequestSummary`,不含快照的检查、评审者与合并状态;`ctx.forge.countForViewer` 读取一个主机上每个列表的总数。两者都不进入状态轮询:调用方自行轮询列表,并对完整展示的变更请求单独 watch。提供方、主机或列表不提供查看者列表时返回 `unsupported`,主机按限流拒绝时返回 `rate-limited`。
|
||||
|
||||
`ctx.forge.readDescription` 读取变更请求的 Markdown 描述与标签;`body` 中的原始 HTML 不得按 HTML 渲染。`images` 把浏览器在没有用户托管平台会话时无法加载的图片地址,映射为托管平台签发、无需会话即可加载该图片的地址;这些地址在 `imagesExpireAt` 之后失效,之后读者应重新读取描述。搜索与图片配对由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* A list of open change requests that involve the signed-in user: `review-requested` asks the user or one of the user's
|
||||
* teams for a review; `authored` names the user as author; `involved` names the user in any other way, as an assignee,
|
||||
* a commenter, a reviewer, or a mention, and holds none of the other two lists' change requests.
|
||||
*/
|
||||
type ForgeViewerFilter = 'review-requested' | 'authored' | 'involved'
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Hosts a provider lists change requests on for the signed-in user, and the lists it offers there. */
|
||||
interface ForgeViewerCapability {
|
||||
/** Lowercase host names, each one this provider serves. */
|
||||
readonly hosts: readonly string[]
|
||||
/** The lists the provider reads on each of `hosts`. */
|
||||
readonly filters: ReadonlySet<ForgeViewerFilter>
|
||||
/** Most change requests one read returns, a positive integer. */
|
||||
readonly maxItems: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A registered provider's viewer lists, as {@link ForgeViewerCapability} with the forge family that offers them. */
|
||||
interface ForgeViewerSource extends ForgeViewerCapability {
|
||||
/** Forge family of the provider. */
|
||||
readonly forge: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One read of a list of open change requests that involve the signed-in user on one host. */
|
||||
interface ForgeViewerQuery {
|
||||
/** Lowercase host name from the provider's {@link ForgeViewerCapability.hosts}. */
|
||||
readonly host: string
|
||||
/** The list to read, from the provider's {@link ForgeViewerCapability.filters}. */
|
||||
readonly filter: ForgeViewerFilter
|
||||
/** One repository to read in, or null for every repository the user can read on `host`. */
|
||||
readonly repository: Pick<ForgeRepository, 'owner' | 'name'> | null
|
||||
/** Most change requests returned, a positive integer no greater than {@link ForgeViewerCapability.maxItems}. */
|
||||
readonly limit: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The signed-in user's latest submitted review of a change request. */
|
||||
interface ChangeRequestViewerReview {
|
||||
/** Outcome of the review. */
|
||||
readonly verdict: ReviewVerdict
|
||||
/** Commit the review was on, or null when the host reports none. */
|
||||
readonly reviewedSha: string | null
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Status of one change request as a viewer list reports it, without the checks, reviewers, and merge state of a snapshot. */
|
||||
interface ChangeRequestSummary {
|
||||
/** The change request. */
|
||||
readonly ref: ChangeRequestRef
|
||||
/** Web page of the change request. */
|
||||
readonly url: string
|
||||
/** Title as the author wrote it. */
|
||||
readonly title: string
|
||||
/** Whether the author marked the change request as a draft. */
|
||||
readonly draft: boolean
|
||||
/** Author, or null when the host hides the account. */
|
||||
readonly author: ForgeCommentAuthor | null
|
||||
/** Commit object name at the head of the change request. */
|
||||
readonly headSha: string
|
||||
/** Combined check outcome on the head commit. */
|
||||
readonly checksRollup: ChecksRollup
|
||||
/** Aggregate review outcome. */
|
||||
readonly reviewDecision: ReviewDecision
|
||||
/** The signed-in user's latest submitted review, or null before the first. */
|
||||
readonly viewerReview: ChangeRequestViewerReview | null
|
||||
/**
|
||||
* The review request that asks the signed-in user, or null when none does: `team` names the team, as
|
||||
* `organization/slug`, when the request asks a team the user belongs to rather than the user.
|
||||
*/
|
||||
readonly viewerRequest: { readonly team: string | null } | null
|
||||
/** Issues the host closes once the change request merges, in host order, at most the provider's limit. */
|
||||
readonly closingIssues: readonly ChangeRequestIssue[]
|
||||
/** Whether the host reported more closing issues than `closingIssues` holds. */
|
||||
readonly closingIssuesTruncated: boolean
|
||||
/** ISO 8601 time of the host's last update to the change request. */
|
||||
readonly updatedAt: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One page of a viewer list, most recently updated first. */
|
||||
interface ForgeViewerList {
|
||||
/** Login of the signed-in user the provider read as. */
|
||||
readonly viewer: string
|
||||
/** Change requests most recently updated first, at most the query's limit. */
|
||||
readonly items: readonly ChangeRequestSummary[]
|
||||
/** Number of change requests the host reports in the whole list; more than `items` holds when the list was cut. */
|
||||
readonly total: number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The description of a change request as its author wrote it. */
|
||||
interface ChangeRequestDescription {
|
||||
/** Markdown source; it may contain raw HTML, which readers must not render as HTML. Empty without a description. */
|
||||
readonly body: string
|
||||
/** Labels in host order, at most the provider's limit. */
|
||||
readonly labels: readonly ChangeRequestLabel[]
|
||||
/** Whether the change request has more labels than `labels` holds. */
|
||||
readonly labelsTruncated: boolean
|
||||
/**
|
||||
* Image addresses that a browser cannot load without the user's host session, each mapped to an address the host
|
||||
* issued for loading that image without one. Addresses not listed load as written.
|
||||
*/
|
||||
readonly images: Readonly<Record<string, string>>
|
||||
/** ISO 8601 time after which the addresses in `images` stop loading, or null when there are none or the host names no time. */
|
||||
readonly imagesExpireAt: string | null
|
||||
/** ISO 8601 time the change request was created. */
|
||||
readonly createdAt: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One label of a change request. */
|
||||
interface ChangeRequestLabel {
|
||||
/** Name as the host spells it. */
|
||||
readonly name: string
|
||||
/** Six-digit hexadecimal color without `#`, or null when the host reports none. */
|
||||
readonly color: string | null
|
||||
}
|
||||
```
|
||||
|
||||
## Session 绑定
|
||||
|
||||
`ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。
|
||||
@@ -1550,6 +1705,41 @@ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSi
|
||||
*/
|
||||
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* List the viewer lists every registered provider offers; `forge/providers-changed` announces a change.
|
||||
* @returns one source per provider that declares viewer lists and reads them, in registration order.
|
||||
*/
|
||||
viewerSources(): ForgeViewerSource[]
|
||||
|
||||
/**
|
||||
* Read one list of open change requests that involve the signed-in user.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param query - host, list, repository, and limit of the read.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Count the change requests in each viewer list a provider offers on one host.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param host - lowercase host name the provider lists on.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Read the description and labels of a change request.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.2/forge-rate-limited-failure/guide.md
|
||||
/:
|
||||
en: a269b2e48637b03f
|
||||
zh: c9448349795ddcba
|
||||
/forgefailure-code-gains-rate-limited:
|
||||
en: 5454697431483a8d
|
||||
zh: 99ed198879564642
|
||||
/forgefailure-code-gains-rate-limited/change:
|
||||
en: 97194ff490de2bbe
|
||||
zh: 49f6c69fd0dff633
|
||||
/forgefailure-code-gains-rate-limited/migration:
|
||||
en: b7d9cfab3582d1ca
|
||||
zh: dbf6458a78bf8931
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "ForgeFailure.code gains rate-limited, which forge-github returns when GitHub refuses a read under its rate limit, so an exhaustive switch over the code no longer compiles."
|
||||
---
|
||||
|
||||
# `ForgeFailure.code` gains `rate-limited`
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
`ForgeFailure['code']` from `@deepseek-ai/dsh-experimental-forge` adds `'rate-limited'`: the host refused the read under its rate limit, and reading again succeeds only after the limit resets. [forge-github](../../../../packages/experimental/forge-github/README.md#use-this-package) now returns it for a GraphQL `RATE_LIMITED` error, HTTP 429, or a message that names a primary or secondary rate limit, which it reported as `unavailable` before. Status polls, check reads, review reads, diffs, file reads, viewer lists, and descriptions can all carry it.
|
||||
|
||||
A third-party plugin is affected when it switches exhaustively over `ForgeFailure['code']`, ending in `assertNever` or typing a `Record<ForgeFailure['code'], …>`, which then fails to compile, or when it treats every code other than the documented ones as impossible. A provider that never returns `rate-limited` keeps working unchanged.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Search for `ForgeFailure['code']`, `failure.code`, and `assertNever(` over forge failures in your plugin, and add a `'rate-limited'` case to each exhaustive switch or record. Read it like `unavailable` when you have no rate-limit handling, or wait before reading again when you do.
|
||||
2. A provider that detects its host's rate limit may return `{ code: 'rate-limited', message }` from any read that resolves to `ForgeFailure`.
|
||||
3. Run your typecheck; it passes once every exhaustive switch names the new code.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "ForgeFailure.code 新增 rate-limited,forge-github 在 GitHub 按限流拒绝读取时返回它,对该代码做穷尽 switch 的代码因此无法通过编译。"
|
||||
---
|
||||
|
||||
# `ForgeFailure.code` 新增 `rate-limited`
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`@deepseek-ai/dsh-experimental-forge` 的 `ForgeFailure['code']` 新增 `'rate-limited'`:托管平台按限流拒绝了读取,限额重置之后再读才会成功。[forge-github](../../../../packages/experimental/forge-github/README.zh.md#use-this-package) 遇到 GraphQL `RATE_LIMITED` 错误、HTTP 429,或提到主限流、次级限流的消息时返回它,此前这些情况都报告为 `unavailable`。状态轮询、检查读取、评审读取、diff、文件读取、登录用户的列表与描述读取都可能返回它。
|
||||
|
||||
受影响的是对 `ForgeFailure['code']` 做穷尽 switch 的第三方插件:以 `assertNever` 结尾、或声明了 `Record<ForgeFailure['code'], …>` 的代码会编译失败;把文档列出的代码之外的值都当作不可能出现的代码也会受影响。从不返回 `rate-limited` 的提供方无需修改。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 在插件中搜索 `ForgeFailure['code']`、`failure.code`,以及针对 forge 失败的 `assertNever(`,给每个穷尽的 switch 或 record 加上 `'rate-limited'`。没有限流处理时按 `unavailable` 对待;有限流处理时,等一段时间再读取。
|
||||
2. 能识别主机限流的提供方,可以在任何返回 `ForgeFailure` 的读取中返回 `{ code: 'rate-limited', message }`。
|
||||
3. 运行类型检查;所有穷尽的 switch 都列出新代码后即可通过。
|
||||
@@ -80,6 +80,7 @@ const REVIEW: Record<ChangeRequestSnapshot['reviewDecision'], ForgePanelKey> = {
|
||||
const FAILURE: Record<ForgeFailure['code'], ForgePanelKey> = {
|
||||
'not-found': 'change.failure.notFound',
|
||||
'unauthenticated': 'change.failure.unauthenticated',
|
||||
'rate-limited': 'change.failure.rateLimited',
|
||||
'too-large': 'change.failure.unavailable',
|
||||
'stale': 'change.failure.unavailable',
|
||||
'unsupported': 'change.failure.unavailable',
|
||||
|
||||
@@ -123,6 +123,7 @@ export const zh = {
|
||||
'change.failure.unavailable': '无法读取变更请求状态',
|
||||
'change.failure.notFound': '变更请求不存在或没有访问权限',
|
||||
'change.failure.unauthenticated': '登录后才能读取状态',
|
||||
'change.failure.rateLimited': '代码托管平台暂时限制了请求,稍后会自动重试',
|
||||
'change.unserved': '暂不支持读取该平台的变更请求状态',
|
||||
'change.view': '在浏览器中打开',
|
||||
'change.copy': '复制变更请求链接',
|
||||
@@ -570,6 +571,7 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'The change request status could not be read',
|
||||
'change.failure.notFound': 'The change request does not exist or is not accessible',
|
||||
'change.failure.unauthenticated': 'Sign in to read its status',
|
||||
'change.failure.rateLimited': 'The code host is limiting requests; reading again shortly',
|
||||
'change.unserved': 'Change request status is not supported for this code host yet',
|
||||
'change.view': 'Open in browser',
|
||||
'change.copy': 'Copy change request link',
|
||||
@@ -1021,6 +1023,7 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': '変更リクエストの状態を読み取れませんでした',
|
||||
'change.failure.notFound': '変更リクエストが存在しないか、アクセス権がありません',
|
||||
'change.failure.unauthenticated': '状態を読むにはログインしてください',
|
||||
'change.failure.rateLimited': 'コードホストがリクエストを制限しています。しばらくすると自動で再試行します',
|
||||
'change.unserved': 'このコードホストの変更リクエストの状態はまだサポートされていません',
|
||||
'change.view': 'ブラウザーで開く',
|
||||
'change.copy': '変更リクエストのリンクをコピー',
|
||||
@@ -1465,6 +1468,7 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'No se pudo leer el estado de la solicitud',
|
||||
'change.failure.notFound': 'La solicitud no existe o no tienes acceso',
|
||||
'change.failure.unauthenticated': 'Inicia sesión para ver su estado',
|
||||
'change.failure.rateLimited': 'El servidor de código está limitando las solicitudes; se reintentará en breve',
|
||||
'change.unserved': 'Este servicio de código aún no permite consultar el estado de las solicitudes',
|
||||
'change.view': 'Abrir en el navegador',
|
||||
'change.copy': 'Copiar enlace de la solicitud',
|
||||
@@ -1909,6 +1913,7 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'Impossible de lire l’état de la demande',
|
||||
'change.failure.notFound': 'La demande n’existe pas ou n’est pas accessible',
|
||||
'change.failure.unauthenticated': 'Connectez-vous pour voir son état',
|
||||
'change.failure.rateLimited': 'L’hébergeur de code limite les requêtes ; nouvel essai sous peu',
|
||||
'change.unserved': 'L’état des demandes n’est pas encore pris en charge pour cet hébergeur de code',
|
||||
'change.view': 'Ouvrir dans le navigateur',
|
||||
'change.copy': 'Copier le lien de la demande',
|
||||
@@ -2353,6 +2358,7 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'Der Status der Änderungsanfrage konnte nicht gelesen werden',
|
||||
'change.failure.notFound': 'Die Änderungsanfrage existiert nicht oder ist nicht zugänglich',
|
||||
'change.failure.unauthenticated': 'Anmelden, um den Status zu lesen',
|
||||
'change.failure.rateLimited': 'Der Code-Host begrenzt Anfragen; neuer Versuch in Kürze',
|
||||
'change.unserved': 'Der Status von Änderungsanfragen wird für diesen Code-Host noch nicht unterstützt',
|
||||
'change.view': 'Im Browser öffnen',
|
||||
'change.copy': 'Link zur Änderungsanfrage kopieren',
|
||||
@@ -2797,6 +2803,7 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'Не удалось прочитать состояние запроса',
|
||||
'change.failure.notFound': 'Запрос не существует или недоступен',
|
||||
'change.failure.unauthenticated': 'Войдите, чтобы увидеть состояние',
|
||||
'change.failure.rateLimited': 'Хостинг кода ограничивает запросы; скоро будет повторная попытка',
|
||||
'change.unserved': 'Состояние запросов этого хостинга кода пока не поддерживается',
|
||||
'change.view': 'Открыть в браузере',
|
||||
'change.copy': 'Копировать ссылку на запрос',
|
||||
@@ -3241,6 +3248,7 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'change.failure.unavailable': 'Não foi possível ler o status da solicitação',
|
||||
'change.failure.notFound': 'A solicitação não existe ou não está acessível',
|
||||
'change.failure.unauthenticated': 'Entre para ver o status',
|
||||
'change.failure.rateLimited': 'O host de código está limitando as solicitações; nova tentativa em breve',
|
||||
'change.unserved': 'O status de solicitações deste serviço de código ainda não é compatível',
|
||||
'change.view': 'Abrir no navegador',
|
||||
'change.copy': 'Copiar link da solicitação',
|
||||
|
||||
@@ -1289,6 +1289,7 @@ function readError(failure: ForgeFailure): RemoteError {
|
||||
case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
|
||||
case 'not-found':
|
||||
case 'unauthenticated':
|
||||
case 'rate-limited':
|
||||
case 'unsupported':
|
||||
case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {})
|
||||
/* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
|
||||
@@ -1309,6 +1310,7 @@ function reviewError(failure: ForgeFailure): RemoteError {
|
||||
case 'not-found':
|
||||
case 'unauthenticated':
|
||||
case 'too-large':
|
||||
case 'rate-limited':
|
||||
case 'unavailable': return new RemoteError('forgePanel/review-failed', failure.message, {})
|
||||
/* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
|
||||
default: return assertNever(failure.code, 'ForgeFailure.code')
|
||||
|
||||
@@ -184,6 +184,7 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
it.each([
|
||||
['not-found', en['change.failure.notFound']],
|
||||
['unauthenticated', en['change.failure.unauthenticated']],
|
||||
['rate-limited', en['change.failure.rateLimited']],
|
||||
['unavailable', en['change.failure.unavailable']],
|
||||
] as const)('explains a %s read failure in place of the summary and retries it', (code, text) => {
|
||||
const failure: ForgeFailure = { code, message: 'detail' }
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge-github/use-this-package:
|
||||
en: 7e0ba1b3e7bdc1d6
|
||||
zh: 4e6f269af19b444d
|
||||
en: 2b46adc572339052
|
||||
zh: 5a88126e1bea48f8
|
||||
/deepseek-ai-dsh-experimental-forge-github/understand-the-implementation:
|
||||
en: 9b639e511e850042
|
||||
zh: 25a1a3bde330e7da
|
||||
|
||||
@@ -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`, and `maxViewedFiles` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, `maxReviewThreads`, `maxCommits`, and `maxViewedFiles` 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`, `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 serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `[email protected]:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://<host>/<owner>/<name>/pull/<number>` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname <host>`: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none.
|
||||
|
||||
@@ -42,11 +42,11 @@ Polling returns the first 100 head-commit check contexts without following pages
|
||||
|
||||
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.
|
||||
|
||||
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`; rate limits and other failures become `unavailable`. Head lookups preserve the same diagnostic in their rejection.
|
||||
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.
|
||||
|
||||
A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready <number> --repo <host>/<owner>/<name>`. Merging calls `PUT repos/<owner>/<name>/pulls/<number>/merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`.
|
||||
|
||||
`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. Each status snapshot carries `baseRefOid` as `baseSha`, and leaves it out when GitHub reports no full commit there; given it, `diff` starts this comparison while the GraphQL query confirms the head, and a stale head or another base commit cancels the early comparison and waits for it to end before `diff` returns. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos/<owner>/<name>/contents/<path>?ref=<commit>` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://<host>/<owner>/<name>/blob/<commit>/<path>`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. `mergeBase` reads `merge_base_commit.sha` from `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1`, a page of the comparison that lists no files, and returns `unavailable` when the answer is not a full commit. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`.
|
||||
`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. Each status snapshot carries `baseRefOid` as `baseSha`, and leaves it out when GitHub reports no full commit there; given it, `diff` starts this comparison while the GraphQL query confirms the head, and a stale head or another base commit cancels the early comparison and waits for it to end before `diff` returns. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos/<owner>/<name>/contents/<path>?ref=<commit>` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://<host>/<owner>/<name>/blob/<commit>/<path>`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. `mergeBase` reads `merge_base_commit.sha` from `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1`, a page of the comparison that lists no files, and returns `unavailable` when the answer is not a full commit. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, `rate-limited` for HTTP 429 or a message that names a primary or secondary rate limit, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`.
|
||||
|
||||
Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints.
|
||||
|
||||
@@ -60,6 +60,8 @@ Every status read also reads the overview of each pull request: up to 25 review
|
||||
|
||||
`viewedFiles` lists the pull request's files through GraphQL, 100 per page, up to `maxViewedFiles` (default 3,000) files, and sets `truncated` when GitHub counts more; GitHub's `VIEWED`, `UNVIEWED`, and `DISMISSED` map to `viewed`, `unviewed`, and `dismissed`, and an unknown state to `unviewed`. A page whose head is not the requested commit makes the read `stale`, and a page that does not advance makes it `unavailable`. `setViewed` checks the head, then calls `markFileAsViewed` or `unmarkFileAsViewed`; GitHub keeps one viewed mark per file and user, whatever the commit. `rerunChecks` reads the complete checks, returns `stale` when the head moved, and posts `repos/<owner>/<name>/actions/runs/<run>/rerun-failed-jobs` once for each workflow run with a failed check and no pending one, as GitHub offers no rerun of a run in progress; it tries every such run, reports the refused ones together, and stops early only for missing credentials. GitHub reruns the failed jobs with the jobs that depend on them. `requestReviews` resolves user logins and `organization/slug` team names to node ids in one GraphQL query and calls `requestReviews` with `union: true`, so existing requests stay; bot logins, given the `[bot]` suffix, go to `requestReviewsByLogin` afterwards, which GitHub Enterprise Server 3.19 and 3.20 lack. `reviewerCandidates` lists up to 20 assignable users whose login or name contains the query, and with an empty query GitHub's suggested reviewers first; the author is left out. `updateBranch` checks the head, then calls `updatePullRequestBranch` with the update method and `expectedHeadOid`, so GitHub refuses once new commits arrived. These mutations go through the sender `writeReview` uses, with their GraphQL document and variables as JSON on stdin, and are never retried: a refusal becomes `failed` and an answer that does not confirm the outcome becomes `unknown`, each with GitHub's message.
|
||||
|
||||
`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to `maxViewerItems` (default 50) pull requests per read. `listForViewer` reads one list through one GraphQL `search` of open pull requests in unarchived repositories, most recently updated first: `review-requested:@me`, which also matches a request to one of the user's teams, `author:@me`, or `involves:@me -author:@me -review-requested:@me`, so the lists share no pull request; a repository adds `repo:<owner>/<name>`, and a name that is not a valid owner or repository segment returns `not-found` without a request. GitHub answers one document that searches several lists with a gateway error, so each list is its own request. Each item carries the viewer's latest submitted review, the review request that asks the viewer or one of the viewer's teams, the head commit's combined check state, and up to three closing issues; results that are not pull requests are left out. `countForViewer` reads every list's `issueCount` in one request. Search reads a search index, so a pull request can appear in or leave a list some minutes after the change. `readDescription` reads `body`, `bodyHTML`, `createdAt`, and up to 100 labels in one GraphQL query. On a private repository an uploaded image's Markdown address, `https://<host>/user-attachments/assets/<uuid>`, answers only with the user's GitHub session, while `bodyHTML` names the same upload at a signed `private-user-images` address that loads without one for five minutes; `images` maps each Markdown address to the signed address of the same upload, and `imagesExpireAt` is the earliest `exp` of their tokens. `bodyHTML` is read for these addresses only.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
|
||||
@@ -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` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads`、`maxCommits` 与 `maxViewedFiles` 见[配置目录](../../../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`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 必须是正安全整数,`maxViewerItems` 最大为 100;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads`、`maxCommits`、`maxViewedFiles` 与 `maxViewerItems` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。
|
||||
|
||||
当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `[email protected]:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://<host>/<owner>/<name>/pull/<number>` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname <host>`:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。
|
||||
|
||||
@@ -42,11 +42,11 @@ kind: "package-reference"
|
||||
|
||||
每次状态读取按每页最多 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`;限流与其他失败转为 `unavailable`。head 查找在拒绝时保留相同诊断。
|
||||
未完成的检查运行(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 查找在拒绝时保留相同诊断。
|
||||
|
||||
pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready <number> --repo <host>/<owner>/<name>`。合并经 `gh api` 调用 `PUT repos/<owner>/<name>/pulls/<number>/merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。
|
||||
|
||||
`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos/<owner>/<name>/contents/<path>?ref=<commit>`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://<host>/<owner>/<name>/blob/<commit>/<path>`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。`mergeBase` 从 `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1` 读取 `merge_base_commit.sha`;这一页比较结果不列文件。返回值不是完整提交时为 `unavailable`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。
|
||||
`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos/<owner>/<name>/contents/<path>?ref=<commit>`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://<host>/<owner>/<name>/blob/<commit>/<path>`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。`mergeBase` 从 `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1` 读取 `merge_base_commit.sha`;这一页比较结果不列文件。返回值不是完整提交时为 `unavailable`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,HTTP 429 或提到主限流、次级限流的消息为 `rate-limited`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。
|
||||
|
||||
提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。
|
||||
|
||||
@@ -60,6 +60,8 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
|
||||
`viewedFiles` 经 GraphQL 每页 100 个列出 pull request 的文件,最多 `maxViewedFiles`(默认 3,000)个,GitHub 统计到更多时设置 `truncated`;GitHub 的 `VIEWED`、`UNVIEWED` 与 `DISMISSED` 分别映射为 `viewed`、`unviewed` 与 `dismissed`,未知状态映射为 `unviewed`。某页的 head 不是请求的提交时读取为 `stale`,分页不前进时为 `unavailable`。`setViewed` 先检查 head,再调用 `markFileAsViewed` 或 `unmarkFileAsViewed`;GitHub 对每个文件和用户只保存一个已审阅标记,与提交无关。`rerunChecks` 读取完整检查,head 已移动时返回 `stale`,再对每个含失败检查且没有进行中检查的工作流运行 POST 一次 `repos/<owner>/<name>/actions/runs/<run>/rerun-failed-jobs`,因为 GitHub 不提供运行中工作流的重跑;它会尝试每个这样的运行,汇总报告被拒绝的运行,只在缺少凭据时提前停止。GitHub 会重跑失败的 job 及依赖它们的 job。`requestReviews` 在一次 GraphQL 查询中把用户登录名与 `organization/slug` 形式的团队名解析为节点 id,再以 `union: true` 调用 `requestReviews`,保留已有请求;bot 登录名加上 `[bot]` 后缀后,随后交给 `requestReviewsByLogin`,GitHub Enterprise Server 3.19 与 3.20 没有该 mutation。`reviewerCandidates` 列出登录名或名称包含查询文本的最多 20 个可指派用户,查询为空时 GitHub 建议的评审者排在最前;作者被略去。`updateBranch` 先检查 head,再以更新方式与 `expectedHeadOid` 调用 `updatePullRequestBranch`,因此新提交到来后 GitHub 会拒绝。这些写操作与 `writeReview` 使用同一个发送方式,把 GraphQL 文档与变量作为 JSON 经标准输入发送,且从不重试:拒绝为 `failed`,无法确认结果的答复为 `unknown`,都附 GitHub 的原因。
|
||||
|
||||
`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 `maxViewerItems`(默认 50)个拉取请求。`listForViewer` 用一次 GraphQL `search` 读取一个列表:未归档仓库中打开的拉取请求,按最近更新在前;三个列表的限定词分别为 `review-requested:@me`(也匹配请求给用户所在团队的评审)、`author:@me` 与 `involves:@me -author:@me -review-requested:@me`,因此互不重叠;限定仓库时追加 `repo:<owner>/<name>`,owner 或仓库名不是合法片段时不发请求,直接返回 `not-found`。GitHub 对在一个文档里搜索多个列表的请求返回网关错误,所以每个列表单独请求。每项带有当前用户最近提交的评审、请求当前用户或其所在团队评审的那条请求、head 提交的检查汇总,以及最多三个会关闭的 issue;不是拉取请求的结果被忽略。`countForViewer` 在一次请求中读取每个列表的 `issueCount`。search 读的是搜索索引,所以拉取请求在变化后可能要过几分钟才进入或离开列表。`readDescription` 用一次 GraphQL 查询读取 `body`、`bodyHTML`、`createdAt` 与最多 100 个标签。私有仓库中,上传图片在 Markdown 里的地址 `https://<host>/user-attachments/assets/<uuid>` 只在带有用户 GitHub 会话时才返回图片,而 `bodyHTML` 为同一上传给出带签名的 `private-user-images` 地址,五分钟内无需会话即可加载;`images` 把每个 Markdown 地址映射到同一上传的签名地址,`imagesExpireAt` 为这些令牌中最早的 `exp`。读取 `bodyHTML` 只为得到这些地址。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/** Pull request descriptions through GraphQL, with the image addresses a browser can load without a GitHub session. */
|
||||
|
||||
import type { ChangeRequestDescription, ChangeRequestRef, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { checkedRepository } from './urls.ts'
|
||||
|
||||
/** Most labels one read lists, GitHub's connection maximum. */
|
||||
const LABELS = 100
|
||||
|
||||
/** One pull request's description, its rendered form, and its labels; variables `owner`, `name`, and the integer `number`. */
|
||||
export const DESCRIPTION_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
pullRequest(number: $number) { body bodyHTML createdAt labels(first: ${LABELS}) { totalCount nodes { name color } } }
|
||||
}
|
||||
}`
|
||||
|
||||
const descriptionSchema = z.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
pullRequest: z.object({
|
||||
body: z.string(),
|
||||
bodyHTML: z.string(),
|
||||
createdAt: z.string(),
|
||||
labels: z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
nodes: z.array(z.object({ name: z.string(), color: z.string() })),
|
||||
}),
|
||||
}).nullable(),
|
||||
}).nullable(),
|
||||
}),
|
||||
})
|
||||
|
||||
/** A UUID, as GitHub names an uploaded attachment. */
|
||||
const UUID = String.raw`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
|
||||
|
||||
/** An attachment address in Markdown: `https://<host>/user-attachments/assets/<uuid>`. */
|
||||
const ATTACHMENT = new RegExp(String.raw`https://[^\s"'()<>]+/user-attachments/assets/(${UUID})`, 'gi')
|
||||
|
||||
/** A rendered image source signed for loading without a session, ending in `-<uuid>.<ext>?jwt=<token>`. */
|
||||
const SIGNED = new RegExp(String.raw`<img\b[^>]*\bsrc="(https://[^"]+-(${UUID})\.[a-z0-9]+\?[^"]*\bjwt=([^"&]+)[^"]*)"`, 'gi')
|
||||
|
||||
const HEX_COLOR = /^[0-9a-f]{6}$/i
|
||||
|
||||
const claimsSchema = z.object({ exp: z.number() })
|
||||
|
||||
/**
|
||||
* Read a pull request's description. On a private repository an uploaded image's Markdown address answers only with the
|
||||
* user's GitHub session, while the rendered description names a short-lived signed address for the same upload; each
|
||||
* upload the Markdown names is mapped to its signed address. The rendered description is used for nothing else.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param ref - pull request.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the description, or why GitHub did not provide it.
|
||||
*/
|
||||
export async function readDescription(
|
||||
read: GraphqlReader, ref: ChangeRequestRef, signal: AbortSignal,
|
||||
): Promise<ChangeRequestDescription | ForgeFailure> {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const output = await read(['api', 'graphql', '--hostname', host, '-f', `query=${DESCRIPTION_QUERY}`, '-f', `owner=${owner}`,
|
||||
'-f', `name=${name}`, '-F', `number=${ref.number}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = descriptionSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the description read' }
|
||||
const pull = parsed.data.data.repository?.pullRequest
|
||||
if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` }
|
||||
const { images, expiresAt } = signedImages(pull.body, pull.bodyHTML)
|
||||
return {
|
||||
body: pull.body,
|
||||
labels: pull.labels.nodes.map(label => ({ name: label.name, color: HEX_COLOR.test(label.color) ? label.color.toLowerCase() : null })),
|
||||
labelsTruncated: pull.labels.totalCount > pull.labels.nodes.length,
|
||||
images,
|
||||
imagesExpireAt: expiresAt,
|
||||
createdAt: pull.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pair each attachment address in the Markdown with the signed address the rendered description gives its upload.
|
||||
* @param body - Markdown source.
|
||||
* @param html - GitHub's rendering of `body`.
|
||||
* @returns the pairs, and the earliest expiry the signed addresses name, or null when none names one.
|
||||
*/
|
||||
function signedImages(body: string, html: string): { readonly images: Record<string, string>; readonly expiresAt: string | null } {
|
||||
const signed = new Map<string, { readonly url: string; readonly expires: number | undefined }>()
|
||||
for (const [, source = '', uuid = '', token = ''] of html.matchAll(SIGNED)) {
|
||||
const url = source.replaceAll('&', '&')
|
||||
signed.set(uuid.toLowerCase(), { url, expires: expiryOf(token) })
|
||||
}
|
||||
const images: Record<string, string> = {}
|
||||
let earliest: number | undefined
|
||||
for (const [address = '', uuid = ''] of body.matchAll(ATTACHMENT)) {
|
||||
const match = signed.get(uuid.toLowerCase())
|
||||
if (match === undefined) continue
|
||||
images[address] = match.url
|
||||
if (match.expires !== undefined) earliest = Math.min(earliest ?? match.expires, match.expires)
|
||||
}
|
||||
return { images, expiresAt: earliest === undefined ? null : new Date(earliest * 1000).toISOString() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the expiry of a signed address from its JSON Web Token.
|
||||
* @param token - the `jwt` query value.
|
||||
* @returns the `exp` claim in epoch seconds, or undefined when the token names none.
|
||||
*/
|
||||
function expiryOf(token: string): number | undefined {
|
||||
const [, payload] = token.split('.')
|
||||
if (payload === undefined) return undefined
|
||||
let claims: unknown
|
||||
try {
|
||||
claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
||||
} catch (error) {
|
||||
void error // A token GitHub did not sign as JSON names no expiry.
|
||||
return undefined
|
||||
}
|
||||
const parsed = claimsSchema.safeParse(claims)
|
||||
return parsed.success ? parsed.data.exp : undefined
|
||||
}
|
||||
@@ -255,7 +255,7 @@ const MERGERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE'])
|
||||
const TRIAGERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE', 'TRIAGE'])
|
||||
|
||||
/** Outcome of a submitted review by GitHub state; a pending review is not submitted. */
|
||||
const VERDICTS: Readonly<Record<string, ReviewVerdict>> = {
|
||||
export const VERDICTS: Readonly<Record<string, ReviewVerdict>> = {
|
||||
APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed',
|
||||
}
|
||||
|
||||
@@ -357,8 +357,10 @@ export async function mapSnapshotResponse(
|
||||
?? (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) results.set(key, { code: error.type === 'NOT_FOUND' ? 'not-found' : 'unavailable', message: error.message })
|
||||
else if (raw === null || raw === undefined) results.set(key, { code: 'not-found', message: 'pull request not found' })
|
||||
} 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' })
|
||||
}
|
||||
return results
|
||||
@@ -657,7 +659,12 @@ function statusContextState(state: string): CheckState {
|
||||
}
|
||||
}
|
||||
|
||||
function checksRollup(state: string | undefined): ChecksRollup {
|
||||
/**
|
||||
* Map GitHub's `StatusCheckRollup.state`.
|
||||
* @param state - the rollup state, or undefined for a head commit without checks.
|
||||
* @returns the combined check outcome; states outside the documented set read as pending.
|
||||
*/
|
||||
export function checksRollup(state: string | undefined): ChecksRollup {
|
||||
switch (state) {
|
||||
case undefined: return 'none'
|
||||
case 'SUCCESS': return 'success'
|
||||
@@ -675,7 +682,12 @@ function mergeability(value: string): Mergeability {
|
||||
}
|
||||
}
|
||||
|
||||
function reviewDecision(value: string | null): ReviewDecision {
|
||||
/**
|
||||
* Map GitHub's `PullRequest.reviewDecision`.
|
||||
* @param value - the decision, or null when the base branch requires none.
|
||||
* @returns the aggregate review outcome.
|
||||
*/
|
||||
export function reviewDecision(value: string | null): ReviewDecision {
|
||||
switch (value) {
|
||||
case 'APPROVED': return 'approved'
|
||||
case 'CHANGES_REQUESTED': return 'changes-requested'
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface Config {
|
||||
maxCommits?: number
|
||||
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
|
||||
maxViewedFiles?: number
|
||||
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
|
||||
maxViewerItems?: number
|
||||
}
|
||||
|
||||
export const Config: z<Config> = z.object({
|
||||
@@ -39,8 +41,12 @@ export const Config: z<Config> = z.object({
|
||||
maxReviewThreads: z.number().default(1_000),
|
||||
maxCommits: z.number().default(250),
|
||||
maxViewedFiles: z.number().default(3_000),
|
||||
maxViewerItems: z.number().default(50),
|
||||
})
|
||||
|
||||
/** Most results one GitHub search page returns. */
|
||||
const SEARCH_PAGE = 100
|
||||
|
||||
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
@@ -53,8 +59,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'] as const) {
|
||||
for (const key of ['maxOutputBytes', 'maxReviewThreads', '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}`)
|
||||
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved))
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure,
|
||||
BranchUpdateRequest, 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,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -23,9 +24,17 @@ import { readViewed, writeViewed } from './viewed.ts'
|
||||
import { gitHubReviewerCandidates, requestGitHubReviews, updateGitHubBranch } from './overview.ts'
|
||||
import { writeGitHubReview } from './review-writes.ts'
|
||||
import { readReviewThreads } from './threads.ts'
|
||||
import { readDescription } from './description.ts'
|
||||
import { countViewerLists, readViewerList, VIEWER_FILTERS } from './viewer.ts'
|
||||
|
||||
const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
|
||||
|
||||
/** GitHub's wording of a primary or secondary rate limit refusal, in a GraphQL error or a REST error body. */
|
||||
const RATE_LIMIT = /\brate limit\b/i
|
||||
|
||||
/** HTTP status GitHub answers when a client sends requests too quickly. */
|
||||
const TOO_MANY_REQUESTS = '429'
|
||||
|
||||
/** Status code `gh api` appends to the message of a failed request. */
|
||||
const HTTP_STATUS = /\(HTTP (\d{3})\)/
|
||||
|
||||
@@ -48,11 +57,14 @@ export interface GitHubLimits {
|
||||
readonly maxCommits: number
|
||||
/** Most files whose viewed marks one read lists. */
|
||||
readonly maxViewedFiles: number
|
||||
/** Most pull requests one viewer list read returns, at most GitHub's search page size of 100. */
|
||||
readonly maxViewerItems: number
|
||||
}
|
||||
|
||||
/** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
|
||||
export class GitHubProvider implements ForgeProvider {
|
||||
readonly forge = 'github'
|
||||
readonly viewer: ForgeViewerCapability
|
||||
private readonly hosts: ReadonlySet<string>
|
||||
|
||||
async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
|
||||
@@ -86,11 +98,46 @@ 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, and listed
|
||||
* viewed files.
|
||||
* @param limits - bounds on retained check and review bytes, counted and read review threads, 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.viewer = { hosts: [...this.hosts], filters: VIEWER_FILTERS, maxItems: limits.maxViewerItems }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one list of the signed-in user's open pull requests through one GraphQL search.
|
||||
* @see readViewerList
|
||||
* @throws when the limit is not a positive integer no greater than `maxViewerItems`.
|
||||
*/
|
||||
async listForViewer(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure> {
|
||||
const failure = this.hostFailure(query.host)
|
||||
if (failure !== undefined) return failure
|
||||
if (!Number.isSafeInteger(query.limit) || query.limit <= 0 || query.limit > this.limits.maxViewerItems) {
|
||||
throw new Error(`forge-github: viewer list limit must be a positive integer no greater than ${this.limits.maxViewerItems}`)
|
||||
}
|
||||
return await readViewerList(this.graphql, query, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the signed-in user's open pull requests in every list through one GraphQL request.
|
||||
* @see countViewerLists
|
||||
*/
|
||||
async countForViewer(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> {
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return failure
|
||||
return await countViewerLists(this.graphql, host, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a pull request's description and labels through GraphQL.
|
||||
* @see readDescription
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) return failure
|
||||
return await readDescription(this.graphql, ref, signal)
|
||||
}
|
||||
|
||||
repositoryFromRemote(url: string): ForgeRepository | undefined {
|
||||
@@ -390,6 +437,7 @@ export class GitHubProvider implements ForgeProvider {
|
||||
const { message, status } = refusal(output)
|
||||
if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
|
||||
if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message }
|
||||
if (status === TOO_MANY_REQUESTS || RATE_LIMIT.test(message)) return { code: 'rate-limited', message }
|
||||
return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message }
|
||||
}
|
||||
|
||||
@@ -534,7 +582,8 @@ function responseFailure(output: GhOutput, body: unknown): ForgeFailure {
|
||||
? firstLine(body.message) : undefined
|
||||
const message = firstLine(output.stderr) ?? detail
|
||||
?? (output.exitCode === 0 ? 'unexpected GitHub response' : `gh exited with ${output.exitCode}`)
|
||||
return { code: AUTHENTICATION.test(message) ? 'unauthenticated' : 'unavailable', message }
|
||||
const limited = typeof body === 'object' && body !== null && 'type' in body && body.type === 'RATE_LIMITED'
|
||||
return { code: AUTHENTICATION.test(message) ? 'unauthenticated' : limited || RATE_LIMIT.test(message) ? 'rate-limited' : 'unavailable', message }
|
||||
}
|
||||
|
||||
function parseJson(text: string): unknown {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/** Lists of the signed-in user's open pull requests through the GitHub GraphQL search. */
|
||||
|
||||
import type {
|
||||
ChangeRequestSummary, ForgeFailure, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { checksRollup, reviewDecision, VERDICTS } from './graphql.ts'
|
||||
import { isSegment } from './urls.ts'
|
||||
|
||||
/** The lists GitHub search reads, each the same search the GitHub pull request page offers. */
|
||||
export const VIEWER_FILTERS: ReadonlySet<ForgeViewerFilter> = new Set(['review-requested', 'authored', 'involved'])
|
||||
|
||||
/** Most closing issues one list item names. */
|
||||
const CLOSING_ISSUES = 3
|
||||
|
||||
/**
|
||||
* Search qualifiers of each list. `involved` leaves out the other two lists, so the three never share a pull request;
|
||||
* `review-requested:@me` also matches a request to one of the user's teams.
|
||||
*/
|
||||
const QUALIFIERS: Readonly<Record<ForgeViewerFilter, string>> = {
|
||||
'review-requested': 'review-requested:@me',
|
||||
'authored': 'author:@me',
|
||||
'involved': 'involves:@me -author:@me -review-requested:@me',
|
||||
}
|
||||
|
||||
const ROW_FIELDS = `number title url isDraft updatedAt headRefOid reviewDecision
|
||||
repository { name owner { login } }
|
||||
author { __typename login avatarUrl }
|
||||
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
|
||||
viewerLatestReview { state commit { oid } }
|
||||
viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } }
|
||||
closingIssuesReferences(first: ${CLOSING_ISSUES}) { totalCount nodes { number title state url repository { name owner { login } } } }`
|
||||
|
||||
/** One page of one list with the signed-in user; variables `q` and the integer `first`. */
|
||||
export const VIEWER_LIST_QUERY = `query($q: String!, $first: Int!) {
|
||||
viewer { login }
|
||||
search(type: ISSUE, query: $q, first: $first) { issueCount nodes { __typename ... on PullRequest { ${ROW_FIELDS} } } }
|
||||
}`
|
||||
|
||||
/** The size of every list in one request; variables `review`, `authored`, and `involved`. */
|
||||
export const VIEWER_COUNT_QUERY = `query($review: String!, $authored: String!, $involved: String!) {
|
||||
review: search(type: ISSUE, query: $review, first: 0) { issueCount }
|
||||
authored: search(type: ISSUE, query: $authored, first: 0) { issueCount }
|
||||
involved: search(type: ISSUE, query: $involved, first: 0) { issueCount }
|
||||
}`
|
||||
|
||||
const ownerSchema = z.object({ name: z.string(), owner: z.object({ login: z.string() }) })
|
||||
|
||||
const rowSchema = z.object({
|
||||
__typename: z.literal('PullRequest'),
|
||||
number: z.number().int().positive(),
|
||||
title: z.string(),
|
||||
url: z.string(),
|
||||
isDraft: z.boolean(),
|
||||
updatedAt: z.string(),
|
||||
headRefOid: z.string(),
|
||||
reviewDecision: z.string().nullable(),
|
||||
repository: ownerSchema,
|
||||
author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(),
|
||||
commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ state: z.string() }).nullable() }) })) }),
|
||||
viewerLatestReview: z.object({ state: z.string(), commit: z.object({ oid: z.string() }).nullable() }).nullable(),
|
||||
viewerLatestReviewRequest: z.object({
|
||||
requestedReviewer: z.object({ __typename: z.string(), combinedSlug: z.string().optional() }).nullable(),
|
||||
}).nullable(),
|
||||
closingIssuesReferences: z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
nodes: z.array(z.object({
|
||||
number: z.number().int().positive(), title: z.string(), state: z.string(), url: z.string(), repository: ownerSchema,
|
||||
})),
|
||||
}),
|
||||
})
|
||||
|
||||
const listSchema = z.object({
|
||||
data: z.object({
|
||||
viewer: z.object({ login: z.string() }),
|
||||
search: z.object({ issueCount: z.number().int().nonnegative(), nodes: z.array(z.unknown()) }),
|
||||
}),
|
||||
})
|
||||
|
||||
const countSchema = z.object({
|
||||
data: z.object({
|
||||
review: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
authored: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
involved: z.object({ issueCount: z.number().int().nonnegative() }),
|
||||
}),
|
||||
})
|
||||
|
||||
/**
|
||||
* Build the search text of one list.
|
||||
* @param filter - the list.
|
||||
* @param repository - one repository to search in, or null for every repository the user can read.
|
||||
* @returns the search text, most recently updated first, or undefined for a repository whose owner or name cannot be
|
||||
* a search qualifier.
|
||||
*/
|
||||
export function searchText(filter: ForgeViewerFilter, repository: ForgeViewerQuery['repository']): string | undefined {
|
||||
if (repository !== null && (!isSegment(repository.owner) || !isSegment(repository.name))) return undefined
|
||||
const scope = repository === null ? '' : ` repo:${repository.owner}/${repository.name}`
|
||||
return `is:pr is:open archived:false ${QUALIFIERS[filter]}${scope} sort:updated-desc`
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one list through one search request: GitHub answers a search of several lists in one document with a gateway
|
||||
* error, so every list is its own request. A search result that is not a pull request, or names a repository this
|
||||
* provider cannot address, is left out.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param query - host, list, repository, and a limit the caller already bounded.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the list, or why GitHub did not provide it.
|
||||
*/
|
||||
export async function readViewerList(
|
||||
read: GraphqlReader, query: ForgeViewerQuery, signal: AbortSignal,
|
||||
): Promise<ForgeViewerList | ForgeFailure> {
|
||||
const text = searchText(query.filter, query.repository)
|
||||
if (text === undefined) return { code: 'not-found', message: 'the repository name cannot be searched' }
|
||||
const output = await read(['api', 'graphql', '--hostname', query.host, '-f', `query=${VIEWER_LIST_QUERY}`, '-f', `q=${text}`,
|
||||
'-F', `first=${query.limit}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = listSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request search' }
|
||||
const items: ChangeRequestSummary[] = []
|
||||
for (const node of parsed.data.data.search.nodes) {
|
||||
const row = rowSchema.safeParse(node)
|
||||
if (!row.success) continue
|
||||
const item = summaryOf(query.host, row.data)
|
||||
if (item !== undefined) items.push(item)
|
||||
}
|
||||
return { viewer: parsed.data.data.viewer.login, items, total: parsed.data.data.search.issueCount }
|
||||
}
|
||||
|
||||
/**
|
||||
* Count every list on one host in one request.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param host - host to count on.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the size of each list, or why GitHub did not provide them.
|
||||
*/
|
||||
export async function countViewerLists(
|
||||
read: GraphqlReader, host: string, signal: AbortSignal,
|
||||
): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> {
|
||||
const text = (filter: ForgeViewerFilter): string => `is:pr is:open archived:false ${QUALIFIERS[filter]}`
|
||||
const output = await read(['api', 'graphql', '--hostname', host, '-f', `query=${VIEWER_COUNT_QUERY}`,
|
||||
'-f', `review=${text('review-requested')}`, '-f', `authored=${text('authored')}`, '-f', `involved=${text('involved')}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = countSchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request count' }
|
||||
const { review, authored, involved } = parsed.data.data
|
||||
return new Map<ForgeViewerFilter, number>([
|
||||
['review-requested', review.issueCount], ['authored', authored.issueCount], ['involved', involved.issueCount],
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one search result.
|
||||
* @param host - host the search ran on.
|
||||
* @param row - the pull request fields.
|
||||
* @returns the summary, or undefined for a repository this provider cannot address.
|
||||
*/
|
||||
function summaryOf(host: string, row: z.infer<typeof rowSchema>): ChangeRequestSummary | undefined {
|
||||
const { owner: { login: owner }, name } = row.repository
|
||||
if (!isSegment(owner) || !isSegment(name)) return undefined
|
||||
const review = row.viewerLatestReview
|
||||
const verdict = review === null ? undefined : VERDICTS[review.state]
|
||||
const reviewer = row.viewerLatestReviewRequest?.requestedReviewer
|
||||
return {
|
||||
ref: { repository: { forge: 'github', host, owner, name }, number: row.number },
|
||||
url: row.url,
|
||||
title: row.title,
|
||||
draft: row.isDraft,
|
||||
author: row.author === null ? null : { login: row.author.login, avatarUrl: row.author.avatarUrl, bot: row.author.__typename === 'Bot' },
|
||||
headSha: row.headRefOid,
|
||||
checksRollup: checksRollup(row.commits.nodes[0]?.commit.statusCheckRollup?.state),
|
||||
reviewDecision: reviewDecision(row.reviewDecision),
|
||||
viewerReview: review === null || verdict === undefined ? null : { verdict, reviewedSha: review.commit?.oid ?? null },
|
||||
viewerRequest: reviewer == null ? null : { team: reviewer.__typename === 'Team' ? reviewer.combinedSlug ?? null : null },
|
||||
closingIssues: row.closingIssuesReferences.nodes.flatMap((issue) => {
|
||||
const { owner: { login: issueOwner }, name: issueName } = issue.repository
|
||||
if (!isSegment(issueOwner) || !isSegment(issueName)) return []
|
||||
return [{
|
||||
repository: { forge: 'github', host, owner: issueOwner, name: issueName },
|
||||
number: issue.number,
|
||||
title: issue.title,
|
||||
state: issue.state === 'OPEN' ? 'open' as const : 'closed' as const,
|
||||
url: issue.url,
|
||||
}]
|
||||
}),
|
||||
closingIssuesTruncated: row.closingIssuesReferences.totalCount > row.closingIssuesReferences.nodes.length,
|
||||
updatedAt: row.updatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { GhOutput, GhRunner } from '../src/gh.ts'
|
||||
import { DESCRIPTION_QUERY } from '../src/description.ts'
|
||||
import { GitHubProvider } from '../src/provider.ts'
|
||||
import type { GitHubLimits } from '../src/provider.ts'
|
||||
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,
|
||||
}
|
||||
|
||||
function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner; calls: string[][] } {
|
||||
const calls: string[][] = []
|
||||
return { calls, run: async (args) => { calls.push([...args]); return handler(args) } }
|
||||
}
|
||||
|
||||
function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr }
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com'], limits)
|
||||
}
|
||||
|
||||
const FIRST = '07901e44-8333-47f0-9422-94a73c19d18c'
|
||||
const SECOND = '389b0451-394a-434e-b4e5-76a74f021acf'
|
||||
const THIRD = 'bc19499b-80a6-4aaf-bd24-313216c9863c'
|
||||
|
||||
/** A JSON Web Token whose payload is `claims`, as GitHub signs private image addresses. */
|
||||
function token(claims: unknown): string {
|
||||
return `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.c2ln`
|
||||
}
|
||||
|
||||
function signed(uuid: string, jwt: string, extension = 'png'): string {
|
||||
return `https://private-user-images.githubusercontent.com/1/2-${uuid}.${extension}?jwt=${jwt}`
|
||||
}
|
||||
|
||||
function descriptionBody(pullRequest: unknown): Record<string, unknown> {
|
||||
return { data: { repository: { pullRequest } } }
|
||||
}
|
||||
|
||||
describe('GitHub descriptions', () => {
|
||||
it('reads the body and labels and maps each uploaded image to the signed address the rendering gives it', async () => {
|
||||
const body = [
|
||||
'Motivation', '',
|
||||
``,
|
||||
`<img width="400" src="https://github.com/user-attachments/assets/${SECOND}" />`,
|
||||
``,
|
||||
'',
|
||||
`again https://github.com/user-attachments/assets/${FIRST}`,
|
||||
].join('\n')
|
||||
const html = [
|
||||
`<p><a href="x"><img src="${signed(FIRST, token({ exp: 1794367597, nbf: 1794367297 }))}" alt="shot"></a></p>`,
|
||||
`<img width="400" src="${signed(SECOND.toUpperCase(), token({ exp: 1794367500 }))}&size=2">`,
|
||||
`<img src="${signed(THIRD, token({ nbf: 1 }), 'gif')}">`,
|
||||
'<img src="https://camo.githubusercontent.com/abc" data-canonical-src="https://img.shields.io/badge/x-y-blue">',
|
||||
].join('\n')
|
||||
const gh = fakeGh(() => output(descriptionBody({
|
||||
body, bodyHTML: html, createdAt: '2026-11-08T12:00:00Z',
|
||||
labels: { totalCount: 3, nodes: [{ name: 'kind/feature', color: 'A2EEEF' }, { name: 'area/web', color: 'not-a-color' }] },
|
||||
})))
|
||||
|
||||
const result = await provider(gh.run).readDescription(pull(8149), signal)
|
||||
|
||||
expect(gh.calls).toEqual([['api', 'graphql', '--hostname', 'github.com', '-f', `query=${DESCRIPTION_QUERY}`, '-f', 'owner=octo',
|
||||
'-f', 'name=demo', '-F', 'number=8149']])
|
||||
expect(result).toEqual({
|
||||
body,
|
||||
labels: [{ name: 'kind/feature', color: 'a2eeef' }, { name: 'area/web', color: null }],
|
||||
labelsTruncated: true,
|
||||
images: {
|
||||
[`https://github.com/user-attachments/assets/${FIRST}`]: signed(FIRST, token({ exp: 1794367597, nbf: 1794367297 })),
|
||||
[`https://github.com/user-attachments/assets/${SECOND}`]: `${signed(SECOND.toUpperCase(), token({ exp: 1794367500 }))}&size=2`,
|
||||
[`https://github.com/user-attachments/assets/${THIRD}`]: signed(THIRD, token({ nbf: 1 }), 'gif'),
|
||||
},
|
||||
imagesExpireAt: new Date(1794367500 * 1000).toISOString(),
|
||||
createdAt: '2026-11-08T12:00:00Z',
|
||||
})
|
||||
})
|
||||
|
||||
it('maps nothing when the rendering names no signed address, and names no expiry for tokens without one', async () => {
|
||||
const attachment = `https://github.com/user-attachments/assets/${FIRST}`
|
||||
const read = async (html: string): Promise<unknown> => await provider(fakeGh(() => output(descriptionBody({
|
||||
body: ``, bodyHTML: html, createdAt: '2026-11-08T12:00:00Z', labels: { totalCount: 0, nodes: [] },
|
||||
}))).run).readDescription(pull(1), signal)
|
||||
|
||||
await expect(read(`<img src="${attachment}">`)).resolves.toMatchObject({ images: {}, imagesExpireAt: null, labelsTruncated: false })
|
||||
await expect(read(`<img src="${signed(SECOND, token({ exp: 1 }))}">`)).resolves.toMatchObject({ images: {}, imagesExpireAt: null })
|
||||
for (const jwt of ['no-dot', 'a.!!!.c', `a.${Buffer.from('not json').toString('base64url')}.c`, token({ exp: 'soon' })]) {
|
||||
await expect(read(`<img src="${signed(FIRST, jwt)}">`)).resolves.toMatchObject({ images: { [attachment]: signed(FIRST, jwt) }, imagesExpireAt: null })
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a missing pull request', output(descriptionBody(null)), { code: 'not-found', message: 'pull request 3 was not found' }],
|
||||
['a missing repository', output({ data: { repository: null } }), { code: 'not-found', message: 'pull request 3 was not found' }],
|
||||
['an unexpected answer', output(descriptionBody({ body: 1 })), { code: 'unavailable', message: 'unexpected GitHub response to the description read' }],
|
||||
['a refusal', output('', 1, 'gh: Something went wrong (HTTP 502)'), { code: 'unavailable', message: 'gh: Something went wrong (HTTP 502)' }],
|
||||
])('reports %s', async (_, answer, failure) => {
|
||||
await expect(provider(fakeGh(() => answer).run).readDescription(pull(3), signal)).resolves.toEqual(failure)
|
||||
})
|
||||
|
||||
it('refuses an unconfigured host without asking GitHub', async () => {
|
||||
const gh = fakeGh(() => output(''))
|
||||
await expect(provider(gh.run).readDescription(pull(1, { forge: 'github', host: 'other.example', owner: 'o', name: 'n' }), signal))
|
||||
.resolves.toEqual({ code: 'unavailable', message: 'forge-github: host "other.example" is not configured' })
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -36,6 +36,15 @@ describe('forge-github plugin', () => {
|
||||
expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('offers the three viewer lists on its hosts, 50 pull requests per read by default', async () => {
|
||||
const context = await forge()
|
||||
await context.plugin(ForgeGitHub, { hosts: ['github.com', 'ghe.corp.example'] })
|
||||
|
||||
expect(context.forge.viewerSources()).toEqual([{
|
||||
forge: 'github', hosts: ['github.com', 'ghe.corp.example'], filters: new Set(['review-requested', 'authored', 'involved']), maxItems: 50,
|
||||
}])
|
||||
})
|
||||
|
||||
it('unregisters the provider when its fiber is disposed', async () => {
|
||||
const context = await forge()
|
||||
const fiber = context.plugin(ForgeGitHub, {})
|
||||
@@ -60,6 +69,8 @@ describe('forge-github plugin', () => {
|
||||
[{ 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'],
|
||||
[{ 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) => {
|
||||
const context = await forge()
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr }
|
||||
}
|
||||
|
||||
const limits: GitHubLimits = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000 }
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits)
|
||||
@@ -107,13 +109,13 @@ describe('GitHub provider fetch', () => {
|
||||
expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ title: 'Change 2' })
|
||||
})
|
||||
|
||||
it('reports a review thread page that GitHub refuses', async () => {
|
||||
it('reports a review thread page that GitHub refuses under its rate limit', async () => {
|
||||
const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`)
|
||||
? output({ message: 'API rate limit exceeded' }, 1, 'gh: API rate limit exceeded (HTTP 403)')
|
||||
: output({ data: { r0: { p0: pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) } } }))
|
||||
|
||||
await expect(provider(gh.run).fetchChecks(pull(1), signal))
|
||||
.resolves.toEqual({ code: 'unavailable', message: 'gh: API rate limit exceeded (HTTP 403)' })
|
||||
.resolves.toEqual({ code: 'rate-limited', message: 'gh: API rate limit exceeded (HTTP 403)' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -174,16 +176,18 @@ describe('GitHub provider fetch', () => {
|
||||
})
|
||||
|
||||
it.each([
|
||||
[output({ message: 'API rate limit exceeded' }, 1), 'API rate limit exceeded'],
|
||||
[output({ errors: [{ message: 'Check page failed' }] }, 1), 'Check page failed'],
|
||||
[output({ data: { node: { contexts: { pageInfo: { hasNextPage: true, endCursor: 'page-1' }, nodes: [] } } } }), 'GitHub check pagination did not advance'],
|
||||
[output({ data: { node: { contexts: { pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] } } } }), 'GitHub check pagination did not advance'],
|
||||
])('rejects an incomplete check read without losing another pull request', async (page, message) => {
|
||||
[output({ message: 'API rate limit exceeded' }, 1), 'rate-limited', 'API rate limit exceeded'],
|
||||
[output({ errors: [{ message: 'Check page failed' }] }, 1), 'unavailable', 'Check page failed'],
|
||||
[output({ data: { node: { contexts: { pageInfo: { hasNextPage: true, endCursor: 'page-1' }, nodes: [] } } } }), 'unavailable',
|
||||
'GitHub check pagination did not advance'],
|
||||
[output({ data: { node: { contexts: { pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] } } } }), 'unavailable',
|
||||
'GitHub check pagination did not advance'],
|
||||
])('rejects an incomplete check read without losing another pull request', async (page, code, message) => {
|
||||
const gh = fakeGh(args => args.includes('id=fixed-rollup') ? page : output({ data: { r0: { p0: firstPage(), p1: pullRequestNode(2) } } }))
|
||||
const subject = provider(gh.run)
|
||||
const results = await subject.fetch([pull(1), pull(2)], signal)
|
||||
const details = await subject.fetchChecks(pull(1), signal)
|
||||
expect(details).toEqual({ code: 'unavailable', message })
|
||||
expect(details).toEqual({ code, message })
|
||||
expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ title: 'Change 2' })
|
||||
expect(gh.calls).toHaveLength(3)
|
||||
})
|
||||
@@ -229,7 +233,7 @@ describe('GitHub provider fetch', () => {
|
||||
|
||||
it.each([
|
||||
[{ message: 'Bad credentials' }, 1, 'gh: Bad credentials (HTTP 401)', 'unauthenticated', 'gh: Bad credentials (HTTP 401)'],
|
||||
[{ message: 'API rate limit exceeded' }, 1, 'gh: API rate limit exceeded (HTTP 403)', 'unavailable', 'gh: API rate limit exceeded (HTTP 403)'],
|
||||
[{ message: 'API rate limit exceeded' }, 1, 'gh: API rate limit exceeded (HTTP 403)', 'rate-limited', 'gh: API rate limit exceeded (HTTP 403)'],
|
||||
[{ message: 'Bad credentials' }, 1, '', 'unauthenticated', 'Bad credentials'],
|
||||
[{ message: '' }, 0, '', 'unavailable', 'unexpected GitHub response'],
|
||||
[null, 1, '', 'unavailable', 'gh exited with 1'],
|
||||
@@ -241,6 +245,11 @@ describe('GitHub provider fetch', () => {
|
||||
await expect(subject.findByHead(demo, 'topic', signal)).rejects.toThrow(`head branch lookup failed: ${message}`)
|
||||
})
|
||||
|
||||
it('reports a GraphQL rate limit error on a pull request as rate-limited', async () => {
|
||||
const gh = fakeGh(() => output({ data: { r0: null }, errors: [{ type: 'RATE_LIMITED', path: ['r0'], message: 'API rate limit exceeded' }] }))
|
||||
expect([...(await provider(gh.run).fetch([pull(1)], signal)).values()]).toEqual([{ code: 'rate-limited', message: 'API rate limit exceeded' }])
|
||||
})
|
||||
|
||||
it('rejects unconfigured hosts without querying them and still fetches allowed hosts', async () => {
|
||||
const gh = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1) } } }))
|
||||
const denied = pull(2, { ...enterprise, host: 'unconfigured.example' })
|
||||
|
||||
@@ -53,7 +53,7 @@ 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 })
|
||||
return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50 })
|
||||
}
|
||||
|
||||
function payload(field: string, value: unknown = { id: 'x' }): GhOutput {
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 }
|
||||
const LIMITS = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, 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: '' }
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { GhOutput, GhRunner } from '../src/gh.ts'
|
||||
import { GitHubProvider } from '../src/provider.ts'
|
||||
import type { GitHubLimits } from '../src/provider.ts'
|
||||
import { searchText, VIEWER_COUNT_QUERY, VIEWER_LIST_QUERY } from '../src/viewer.ts'
|
||||
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner; calls: string[][] } {
|
||||
const calls: string[][] = []
|
||||
return { calls, run: async (args) => { calls.push([...args]); return handler(args) } }
|
||||
}
|
||||
|
||||
function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr }
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits)
|
||||
}
|
||||
|
||||
/** One search result node with the fields the viewer list query selects. */
|
||||
function row(number: number, overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
__typename: 'PullRequest',
|
||||
number,
|
||||
title: `Change ${number}`,
|
||||
url: `https://github.com/octo/demo/pull/${number}`,
|
||||
isDraft: false,
|
||||
updatedAt: '2026-11-10T09:29:00Z',
|
||||
headRefOid: 'f'.repeat(40),
|
||||
reviewDecision: null,
|
||||
repository: { name: 'demo', owner: { login: 'octo' } },
|
||||
author: { __typename: 'User', login: 'turtle', avatarUrl: 'https://avatars.example/turtle' },
|
||||
commits: { nodes: [{ commit: { statusCheckRollup: { state: 'FAILURE' } } }] },
|
||||
viewerLatestReview: null,
|
||||
viewerLatestReviewRequest: { requestedReviewer: { __typename: 'User' } },
|
||||
closingIssuesReferences: { totalCount: 0, nodes: [] },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function listBody(nodes: unknown[], issueCount = nodes.length): Record<string, unknown> {
|
||||
return { data: { viewer: { login: 'LegGasai' }, search: { issueCount, nodes } } }
|
||||
}
|
||||
|
||||
const query = { host: 'github.com', filter: 'review-requested' as const, repository: null, limit: 20 }
|
||||
|
||||
describe('GitHub viewer lists', () => {
|
||||
it('declares the three lists on every configured host with its item limit', () => {
|
||||
expect(provider(fakeGh(() => output('')).run).viewer).toEqual({
|
||||
hosts: ['github.com', 'ghe.corp.example'], filters: new Set(['review-requested', 'authored', 'involved']), maxItems: 50,
|
||||
})
|
||||
})
|
||||
|
||||
it('builds one search per list, scoped to a repository when asked, and refuses a name that cannot be a qualifier', () => {
|
||||
expect(searchText('review-requested', null)).toBe('is:pr is:open archived:false review-requested:@me sort:updated-desc')
|
||||
expect(searchText('authored', { owner: 'octo', name: 'demo' })).toBe('is:pr is:open archived:false author:@me repo:octo/demo sort:updated-desc')
|
||||
expect(searchText('involved', null))
|
||||
.toBe('is:pr is:open archived:false involves:@me -author:@me -review-requested:@me sort:updated-desc')
|
||||
expect(searchText('authored', { owner: 'octo demo', name: 'x' })).toBeUndefined()
|
||||
expect(searchText('authored', { owner: 'octo', name: 'a:b' })).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads one list through one search on the queried host and maps each pull request', async () => {
|
||||
const gh = fakeGh(() => output(listBody([
|
||||
row(8225, {
|
||||
closingIssuesReferences: {
|
||||
totalCount: 4,
|
||||
nodes: [
|
||||
{ number: 8224, title: 'Identify the client', state: 'OPEN', url: 'https://github.com/octo/demo/issues/8224', repository: { name: 'demo', owner: { login: 'octo' } } },
|
||||
{ number: 9, title: 'Closed elsewhere', state: 'CLOSED', url: 'https://github.com/octo/other/issues/9', repository: { name: 'other', owner: { login: 'octo' } } },
|
||||
{ number: 10, title: 'Bad repository', state: 'OPEN', url: 'https://github.com/x/y/issues/10', repository: { name: 'a b', owner: { login: 'x' } } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
row(7155, {
|
||||
isDraft: true,
|
||||
reviewDecision: 'CHANGES_REQUESTED',
|
||||
author: { __typename: 'Bot', login: 'dependabot', avatarUrl: null },
|
||||
commits: { nodes: [] },
|
||||
viewerLatestReview: { state: 'CHANGES_REQUESTED', commit: { oid: '2'.repeat(40) } },
|
||||
viewerLatestReviewRequest: { requestedReviewer: { __typename: 'Team', combinedSlug: 'octo/core' } },
|
||||
}),
|
||||
row(6, { author: null, viewerLatestReview: { state: 'PENDING', commit: null }, viewerLatestReviewRequest: null }),
|
||||
row(7, { viewerLatestReview: { state: 'COMMENTED', commit: null }, viewerLatestReviewRequest: { requestedReviewer: { __typename: 'Team' } } }),
|
||||
row(8, { viewerLatestReviewRequest: { requestedReviewer: null } }),
|
||||
row(9, { repository: { name: 'bad name', owner: { login: 'octo' } } }),
|
||||
{ __typename: 'Issue' },
|
||||
{},
|
||||
], 32)))
|
||||
|
||||
const result = await provider(gh.run).listForViewer(query, signal)
|
||||
|
||||
expect(gh.calls).toEqual([['api', 'graphql', '--hostname', 'github.com', '-f', `query=${VIEWER_LIST_QUERY}`,
|
||||
'-f', 'q=is:pr is:open archived:false review-requested:@me sort:updated-desc', '-F', 'first=20']])
|
||||
expect(result).toEqual({
|
||||
viewer: 'LegGasai',
|
||||
total: 32,
|
||||
items: [
|
||||
{
|
||||
ref: { repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 8225 },
|
||||
url: 'https://github.com/octo/demo/pull/8225',
|
||||
title: 'Change 8225',
|
||||
draft: false,
|
||||
author: { login: 'turtle', avatarUrl: 'https://avatars.example/turtle', bot: false },
|
||||
headSha: 'f'.repeat(40),
|
||||
checksRollup: 'failure',
|
||||
reviewDecision: 'none',
|
||||
viewerReview: null,
|
||||
viewerRequest: { team: null },
|
||||
closingIssues: [
|
||||
{ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 8224, title: 'Identify the client', state: 'open', url: 'https://github.com/octo/demo/issues/8224' },
|
||||
{ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'other' }, number: 9, title: 'Closed elsewhere', state: 'closed', url: 'https://github.com/octo/other/issues/9' },
|
||||
],
|
||||
closingIssuesTruncated: true,
|
||||
updatedAt: '2026-11-10T09:29:00Z',
|
||||
},
|
||||
expect.objectContaining({
|
||||
draft: true,
|
||||
author: { login: 'dependabot', avatarUrl: null, bot: true },
|
||||
checksRollup: 'none',
|
||||
reviewDecision: 'changes-requested',
|
||||
viewerReview: { verdict: 'changes-requested', reviewedSha: '2'.repeat(40) },
|
||||
viewerRequest: { team: 'octo/core' },
|
||||
closingIssuesTruncated: false,
|
||||
}),
|
||||
expect.objectContaining({ title: 'Change 6', author: null, viewerReview: null, viewerRequest: null }),
|
||||
expect.objectContaining({ title: 'Change 7', viewerReview: { verdict: 'commented', reviewedSha: null }, viewerRequest: { team: null } }),
|
||||
expect.objectContaining({ title: 'Change 8', viewerRequest: null }),
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('scopes a read to one repository and refuses a repository name search cannot express without asking GitHub', async () => {
|
||||
const gh = fakeGh(() => output(listBody([])))
|
||||
const subject = provider(gh.run)
|
||||
await subject.listForViewer({ ...query, filter: 'authored', repository: { owner: 'octo', name: 'demo' } }, signal)
|
||||
expect(gh.calls[0]).toContain('q=is:pr is:open archived:false author:@me repo:octo/demo sort:updated-desc')
|
||||
await expect(subject.listForViewer({ ...query, repository: { owner: 'octo', name: 'a b' } }, signal))
|
||||
.resolves.toEqual({ code: 'not-found', message: 'the repository name cannot be searched' })
|
||||
expect(gh.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it.each([0, -1, 1.5, 51])('rejects a limit of %s outside 1 to maxViewerItems', async (limit) => {
|
||||
const gh = fakeGh(() => output(listBody([])))
|
||||
await expect(provider(gh.run).listForViewer({ ...query, limit }, signal))
|
||||
.rejects.toThrow('forge-github: viewer list limit must be a positive integer no greater than 50')
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses an unconfigured host without asking GitHub', async () => {
|
||||
const gh = fakeGh(() => output(listBody([])))
|
||||
const subject = provider(gh.run)
|
||||
const denied = { code: 'unavailable', message: 'forge-github: host "unconfigured.example" is not configured' }
|
||||
await expect(subject.listForViewer({ ...query, host: 'unconfigured.example' }, signal)).resolves.toEqual(denied)
|
||||
await expect(subject.countForViewer('unconfigured.example', signal)).resolves.toEqual(denied)
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a body that is not a search', output({ data: { viewer: { login: 'octo' } } }), { code: 'unavailable', message: 'unexpected GitHub response to the pull request search' }],
|
||||
['a rate limit', output({ errors: [{ type: 'RATE_LIMITED', message: 'API rate limit exceeded for user ID 1.' }] }, 1, 'gh: API rate limit exceeded for user ID 1.'),
|
||||
{ code: 'rate-limited', message: 'gh: API rate limit exceeded for user ID 1.' }],
|
||||
['a secondary rate limit', output({ message: 'You have exceeded a secondary rate limit.' }, 1, 'gh: You have exceeded a secondary rate limit. (HTTP 403)'),
|
||||
{ code: 'rate-limited', message: 'You have exceeded a secondary rate limit.' }],
|
||||
['too many requests', output('', 1, 'gh: Too Many Requests (HTTP 429)'), { code: 'rate-limited', message: 'gh: Too Many Requests (HTTP 429)' }],
|
||||
['a rate limit error in a complete answer', output({ data: null, errors: [{ type: 'RATE_LIMITED', message: 'Throttled' }] }),
|
||||
{ code: 'rate-limited', message: 'Throttled' }],
|
||||
['a sign-in failure', output({ message: 'Bad credentials' }, 1, 'gh: Bad credentials (HTTP 401)'), { code: 'unauthenticated', message: 'Bad credentials' }],
|
||||
])('reports %s', async (_, answer, failure) => {
|
||||
await expect(provider(fakeGh(() => answer).run).listForViewer(query, signal)).resolves.toEqual(failure)
|
||||
})
|
||||
|
||||
it('counts every list on a host in one request', async () => {
|
||||
const gh = fakeGh(() => output({ data: { review: { issueCount: 32 }, authored: { issueCount: 23 }, involved: { issueCount: 15 } } }))
|
||||
await expect(provider(gh.run).countForViewer('ghe.corp.example', signal))
|
||||
.resolves.toEqual(new Map([['review-requested', 32], ['authored', 23], ['involved', 15]]))
|
||||
expect(gh.calls).toEqual([['api', 'graphql', '--hostname', 'ghe.corp.example', '-f', `query=${VIEWER_COUNT_QUERY}`,
|
||||
'-f', 'review=is:pr is:open archived:false review-requested:@me', '-f', 'authored=is:pr is:open archived:false author:@me',
|
||||
'-f', 'involved=is:pr is:open archived:false involves:@me -author:@me -review-requested:@me']])
|
||||
})
|
||||
|
||||
it('reports a count GitHub refuses or answers unexpectedly', async () => {
|
||||
await expect(provider(fakeGh(() => output('', 1, 'gh: Something went wrong (HTTP 502)')).run).countForViewer('github.com', signal))
|
||||
.resolves.toEqual({ code: 'unavailable', message: 'gh: Something went wrong (HTTP 502)' })
|
||||
await expect(provider(fakeGh(() => output({ data: { review: { issueCount: 1 } } })).run).countForViewer('github.com', signal))
|
||||
.resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response to the pull request count' })
|
||||
})
|
||||
})
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge/use-this-package:
|
||||
en: cb87b11162a52273
|
||||
zh: c16a36d01c4fb53a
|
||||
en: 6bc6343156327121
|
||||
zh: 0ea271ca98ab0fdb
|
||||
/deepseek-ai-dsh-experimental-forge/understand-the-implementation:
|
||||
en: e193cb547c47069b
|
||||
zh: faa517522402ea41
|
||||
|
||||
@@ -60,6 +60,8 @@ Providers may implement `readReview` to read a change request's review threads a
|
||||
|
||||
Providers may implement `writeReview` to change a change request's review threads and the signed-in user's pending review. `writeReview(ref, write, signal)` takes one `ForgeReviewWrite`: a reply, published at once or with `pending` inside the pending review; resolving or unresolving a thread; editing or deleting a comment; adding a line comment at the head to the pending review; or submitting or discarding the pending review. A pending reply or comment starts a pending review when the user has none. The provider writes only while the head is still `write.headSha`; otherwise it returns `stale`, which polls a watched change request as a stale read does, and after any other result the registry polls a watched change request at once. A write is never retried, and an `unknown` result must be checked on the host before the write is tried again. The registry returns `unsupported` when the provider lacks the method. `ForgeReviewData` names the user's pending review and whether the user may reply to and resolve each thread, edit and delete each comment, and add to, submit, and discard a pending review; a provider without `writeReview` reports none of these permissions.
|
||||
|
||||
Providers may declare `viewer`, the hosts they list change requests on for the signed-in user with the lists they offer and `maxItems`, and implement `listForViewer` and `countForViewer` with it; `ctx.forge.viewerSources()` names every such provider. `listForViewer(query, signal)` reads one of the `review-requested`, `authored`, or `involved` lists on one host, optionally in one repository, most recently updated first; `countForViewer(host, signal)` reads the size of every list. A host refusing under its rate limit returns the failure code `rate-limited`. Providers may also implement `readDescription(ref, signal)`, which reads a change request's Markdown description, labels, and the image addresses a browser can load without the user's host session. The registry returns `unsupported` for a provider, host, or list without the read. Neither read joins status polling.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
|
||||
@@ -60,6 +60,8 @@ provider 可以实现 `submitReview`,在指定的 head 提交上发布行内
|
||||
|
||||
提供方可以实现 `writeReview`,修改变更请求的评审讨论和当前登录用户的待提交评审。`writeReview(ref, write, signal)` 接收一个 `ForgeReviewWrite`:回复讨论,立即发布,或在 `pending` 时加入待提交评审;把讨论标记为已解决或取消解决;编辑或删除评论;在 head 上添加一条行内评论到待提交评审;或提交、丢弃待提交评审。用户还没有待提交评审时,待提交的回复或评论会先开始一个评审。只有 head 仍是 `write.headSha` 时提供方才会写入;否则返回 `stale`,并像读取遇到 `stale` 时那样重新轮询被关注的变更请求;其他结果之后,注册表都会立即重新轮询被关注的变更请求。写操作从不重试;结果为 `unknown` 时,必须先在托管平台上核对,再重试。提供方未实现该方法时,注册表返回 `unsupported`。`ForgeReviewData` 给出用户的待提交评审,以及用户能否回复和解决每个讨论、编辑和删除每条评论、向待提交评审添加评论并提交或丢弃它;未实现 `writeReview` 的提供方不报告任何这类权限。
|
||||
|
||||
提供方可以声明 `viewer`(它为登录用户列出变更请求的主机、提供的列表与 `maxItems`),并同时实现 `listForViewer` 与 `countForViewer`;`ctx.forge.viewerSources()` 列出所有这样的提供方。`listForViewer(query, signal)` 在一个主机上读取 `review-requested`、`authored` 或 `involved` 中的一个列表,可限定一个仓库,按最近更新在前;`countForViewer(host, signal)` 读取每个列表的总数。主机按限流拒绝时返回失败代码 `rate-limited`。提供方还可以实现 `readDescription(ref, signal)`,读取变更请求的 Markdown 描述、标签,以及浏览器无需用户托管平台会话即可加载的图片地址。提供方、主机或列表不提供读取时,注册表返回 `unsupported`。这些读取都不进入状态轮询。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
|
||||
@@ -6,11 +6,12 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { changeRequestKey } from './keys.ts'
|
||||
import { nextPollDelay } from './schedule.ts'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config,
|
||||
BranchUpdateRequest, ChangeRequestDescription, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot,
|
||||
ChangeRequestUpdate, Config,
|
||||
ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData,
|
||||
ForgeReviewChange, ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
|
||||
ForgeReviewWriteResult,
|
||||
ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
|
||||
ForgeViewedFiles, ForgeViewedRequest, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery, ForgeViewerSource, MergeRequest,
|
||||
} from './types.ts'
|
||||
|
||||
export { changeRequestKey } from './keys.ts'
|
||||
@@ -456,6 +457,64 @@ export class ForgeService extends Service {
|
||||
?? Promise.resolve({ code: 'unsupported', message: 'This provider does not name merge bases' } as const))
|
||||
}
|
||||
|
||||
/**
|
||||
* List the viewer lists every registered provider offers; `forge/providers-changed` announces a change.
|
||||
* @returns one source per provider that declares viewer lists and reads them, in registration order.
|
||||
*/
|
||||
viewerSources(): ForgeViewerSource[] {
|
||||
const sources: ForgeViewerSource[] = []
|
||||
for (const { provider } of this.providers.values()) {
|
||||
const { viewer } = provider
|
||||
if (viewer !== undefined && provider.listForViewer !== undefined && provider.countForViewer !== undefined) {
|
||||
sources.push({ forge: provider.forge, hosts: viewer.hosts, filters: viewer.filters, maxItems: viewer.maxItems })
|
||||
}
|
||||
}
|
||||
return sources
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one list of open change requests that involve the signed-in user.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param query - host, list, repository, and limit of the read.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure> {
|
||||
return await this.invoke(this.registration(forge), signal, (provider, operation) => {
|
||||
const reads = viewerReads(provider, query.host, query.filter)
|
||||
return 'code' in reads ? Promise.resolve(reads) : reads.list(query, operation)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the change requests in each viewer list a provider offers on one host.
|
||||
* @param forge - forge family of a registered provider.
|
||||
* @param host - lowercase host name the provider lists on.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`.
|
||||
* @throws when no provider serves `forge`, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> {
|
||||
return await this.invoke(this.registration(forge), signal, (provider, operation) => {
|
||||
const reads = viewerReads(provider, host, undefined)
|
||||
return 'code' in reads ? Promise.resolve(reads) : reads.count(host, operation)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the description and labels of a change request.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure> {
|
||||
return await this.invoke(this.registration(ref.repository.forge), signal,
|
||||
(provider, operation) => provider.readDescription?.(ref, operation)
|
||||
?? Promise.resolve({ code: 'unsupported', message: 'This provider does not read descriptions' } as const))
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
@@ -731,4 +790,29 @@ export class ForgeService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
const UNSUPPORTED_VIEWER: ForgeFailure = { code: 'unsupported', message: 'This provider does not read viewer lists' }
|
||||
|
||||
/** The viewer reads of one provider, bound to it. */
|
||||
interface ViewerReads {
|
||||
readonly list: NonNullable<ForgeProvider['listForViewer']>
|
||||
readonly count: NonNullable<ForgeProvider['countForViewer']>
|
||||
}
|
||||
|
||||
/**
|
||||
* The viewer reads a provider offers on a host.
|
||||
* @param provider - registered provider.
|
||||
* @param host - host the read names.
|
||||
* @param filter - list the read names, or undefined for the counts of every list.
|
||||
* @returns the bound reads, or an `unsupported` failure naming the missing host or list.
|
||||
*/
|
||||
function viewerReads(provider: ForgeProvider, host: string, filter: ForgeViewerFilter | undefined): ViewerReads | ForgeFailure {
|
||||
const { viewer } = provider
|
||||
const list = provider.listForViewer?.bind(provider)
|
||||
const count = provider.countForViewer?.bind(provider)
|
||||
if (viewer === undefined || list === undefined || count === undefined) return UNSUPPORTED_VIEWER
|
||||
if (!viewer.hosts.includes(host)) return { code: 'unsupported', message: `This provider does not list change requests on ${host}` }
|
||||
if (filter !== undefined && !viewer.filters.has(filter)) return { code: 'unsupported', message: `This provider does not read the ${filter} list` }
|
||||
return { list, count }
|
||||
}
|
||||
|
||||
export default ForgeService
|
||||
@@ -185,9 +185,11 @@ export interface ForgeFailure {
|
||||
* `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected;
|
||||
* `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails
|
||||
* the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of
|
||||
* a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure.
|
||||
* a later status can succeed; `rate-limited`: the host refused the read under its rate limit, so reading again
|
||||
* succeeds only after the limit resets; `unsupported`: the provider does not offer the read; `unavailable`: any other
|
||||
* failure.
|
||||
*/
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable'
|
||||
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'rate-limited' | 'unsupported' | 'unavailable'
|
||||
/** Human-readable cause. */
|
||||
readonly message: string
|
||||
}
|
||||
@@ -482,6 +484,119 @@ export interface ForgeViewedRequest {
|
||||
readonly headSha: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of open change requests that involve the signed-in user: `review-requested` asks the user or one of the user's
|
||||
* teams for a review; `authored` names the user as author; `involved` names the user in any other way, as an assignee,
|
||||
* a commenter, a reviewer, or a mention, and holds none of the other two lists' change requests.
|
||||
*/
|
||||
export type ForgeViewerFilter = 'review-requested' | 'authored' | 'involved'
|
||||
|
||||
/** Hosts a provider lists change requests on for the signed-in user, and the lists it offers there. */
|
||||
export interface ForgeViewerCapability {
|
||||
/** Lowercase host names, each one this provider serves. */
|
||||
readonly hosts: readonly string[]
|
||||
/** The lists the provider reads on each of `hosts`. */
|
||||
readonly filters: ReadonlySet<ForgeViewerFilter>
|
||||
/** Most change requests one read returns, a positive integer. */
|
||||
readonly maxItems: number
|
||||
}
|
||||
|
||||
/** A registered provider's viewer lists, as {@link ForgeViewerCapability} with the forge family that offers them. */
|
||||
export interface ForgeViewerSource extends ForgeViewerCapability {
|
||||
/** Forge family of the provider. */
|
||||
readonly forge: string
|
||||
}
|
||||
|
||||
/** One read of a list of open change requests that involve the signed-in user on one host. */
|
||||
export interface ForgeViewerQuery {
|
||||
/** Lowercase host name from the provider's {@link ForgeViewerCapability.hosts}. */
|
||||
readonly host: string
|
||||
/** The list to read, from the provider's {@link ForgeViewerCapability.filters}. */
|
||||
readonly filter: ForgeViewerFilter
|
||||
/** One repository to read in, or null for every repository the user can read on `host`. */
|
||||
readonly repository: Pick<ForgeRepository, 'owner' | 'name'> | null
|
||||
/** Most change requests returned, a positive integer no greater than {@link ForgeViewerCapability.maxItems}. */
|
||||
readonly limit: number
|
||||
}
|
||||
|
||||
/** The signed-in user's latest submitted review of a change request. */
|
||||
export interface ChangeRequestViewerReview {
|
||||
/** Outcome of the review. */
|
||||
readonly verdict: ReviewVerdict
|
||||
/** Commit the review was on, or null when the host reports none. */
|
||||
readonly reviewedSha: string | null
|
||||
}
|
||||
|
||||
/** Status of one change request as a viewer list reports it, without the checks, reviewers, and merge state of a snapshot. */
|
||||
export interface ChangeRequestSummary {
|
||||
/** The change request. */
|
||||
readonly ref: ChangeRequestRef
|
||||
/** Web page of the change request. */
|
||||
readonly url: string
|
||||
/** Title as the author wrote it. */
|
||||
readonly title: string
|
||||
/** Whether the author marked the change request as a draft. */
|
||||
readonly draft: boolean
|
||||
/** Author, or null when the host hides the account. */
|
||||
readonly author: ForgeCommentAuthor | null
|
||||
/** Commit object name at the head of the change request. */
|
||||
readonly headSha: string
|
||||
/** Combined check outcome on the head commit. */
|
||||
readonly checksRollup: ChecksRollup
|
||||
/** Aggregate review outcome. */
|
||||
readonly reviewDecision: ReviewDecision
|
||||
/** The signed-in user's latest submitted review, or null before the first. */
|
||||
readonly viewerReview: ChangeRequestViewerReview | null
|
||||
/**
|
||||
* The review request that asks the signed-in user, or null when none does: `team` names the team, as
|
||||
* `organization/slug`, when the request asks a team the user belongs to rather than the user.
|
||||
*/
|
||||
readonly viewerRequest: { readonly team: string | null } | null
|
||||
/** Issues the host closes once the change request merges, in host order, at most the provider's limit. */
|
||||
readonly closingIssues: readonly ChangeRequestIssue[]
|
||||
/** Whether the host reported more closing issues than `closingIssues` holds. */
|
||||
readonly closingIssuesTruncated: boolean
|
||||
/** ISO 8601 time of the host's last update to the change request. */
|
||||
readonly updatedAt: string
|
||||
}
|
||||
|
||||
/** One page of a viewer list, most recently updated first. */
|
||||
export interface ForgeViewerList {
|
||||
/** Login of the signed-in user the provider read as. */
|
||||
readonly viewer: string
|
||||
/** Change requests most recently updated first, at most the query's limit. */
|
||||
readonly items: readonly ChangeRequestSummary[]
|
||||
/** Number of change requests the host reports in the whole list; more than `items` holds when the list was cut. */
|
||||
readonly total: number
|
||||
}
|
||||
|
||||
/** The description of a change request as its author wrote it. */
|
||||
export interface ChangeRequestDescription {
|
||||
/** Markdown source; it may contain raw HTML, which readers must not render as HTML. Empty without a description. */
|
||||
readonly body: string
|
||||
/** Labels in host order, at most the provider's limit. */
|
||||
readonly labels: readonly ChangeRequestLabel[]
|
||||
/** Whether the change request has more labels than `labels` holds. */
|
||||
readonly labelsTruncated: boolean
|
||||
/**
|
||||
* Image addresses that a browser cannot load without the user's host session, each mapped to an address the host
|
||||
* issued for loading that image without one. Addresses not listed load as written.
|
||||
*/
|
||||
readonly images: Readonly<Record<string, string>>
|
||||
/** ISO 8601 time after which the addresses in `images` stop loading, or null when there are none or the host names no time. */
|
||||
readonly imagesExpireAt: string | null
|
||||
/** ISO 8601 time the change request was created. */
|
||||
readonly createdAt: string
|
||||
}
|
||||
|
||||
/** One label of a change request. */
|
||||
export interface ChangeRequestLabel {
|
||||
/** Name as the host spells it. */
|
||||
readonly name: string
|
||||
/** Six-digit hexadecimal color without `#`, or null when the host reports none. */
|
||||
readonly color: string | null
|
||||
}
|
||||
|
||||
/** Whether a provider can reach one host with the current credentials. */
|
||||
export interface ForgeReadiness {
|
||||
/** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */
|
||||
@@ -497,6 +612,20 @@ export interface ForgeReadiness {
|
||||
export interface ForgeProvider {
|
||||
/** Forge family name stored in every repository this provider returns. */
|
||||
readonly forge: string
|
||||
/**
|
||||
* Where and which lists of the signed-in user's change requests this provider reads. A provider declares `viewer` and
|
||||
* implements `listForViewer` and `countForViewer` together; omitting any declares that it reads no viewer lists.
|
||||
*/
|
||||
readonly viewer?: ForgeViewerCapability
|
||||
/**
|
||||
* Read one viewer list, most recently updated first. A query outside {@link ForgeProvider.viewer} resolves to an
|
||||
* `unsupported` failure.
|
||||
*/
|
||||
listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>
|
||||
/** Count the change requests in every list of {@link ForgeViewerCapability.filters} on one of its hosts. */
|
||||
countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */
|
||||
readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
|
||||
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ChangeRequestDescription, ForgeViewerList, ForgeViewerQuery } from '../src/types.ts'
|
||||
import { FakeProvider, forgeContext, provide, ref } from './fake-provider.ts'
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx?.fiber.dispose()
|
||||
ctx = undefined
|
||||
})
|
||||
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const query: ForgeViewerQuery = { host: 'fake.test', filter: 'review-requested', repository: null, limit: 20 }
|
||||
|
||||
const list: ForgeViewerList = { viewer: 'octo', items: [], total: 0 }
|
||||
|
||||
/** Give the fake provider viewer lists on `fake.test`: review requests and authored change requests. */
|
||||
function withViewer(provider: FakeProvider): { listForViewer: ReturnType<typeof vi.fn>; countForViewer: ReturnType<typeof vi.fn> } {
|
||||
const listForViewer = vi.fn(async () => list)
|
||||
const countForViewer = vi.fn(async () => new Map([['review-requested', 3], ['authored', 1]]))
|
||||
Object.assign(provider, {
|
||||
viewer: { hosts: ['fake.test'], filters: new Set(['review-requested', 'authored']), maxItems: 40 },
|
||||
listForViewer,
|
||||
countForViewer,
|
||||
})
|
||||
return { listForViewer, countForViewer }
|
||||
}
|
||||
|
||||
describe('forge viewer lists', () => {
|
||||
it('lists the viewer sources of providers that declare and read viewer lists, in registration order', async () => {
|
||||
ctx = await forgeContext()
|
||||
const plain = new FakeProvider('plain')
|
||||
const declaredOnly = new FakeProvider('declared')
|
||||
Object.assign(declaredOnly, { viewer: { hosts: ['declared.test'], filters: new Set(['authored']), maxItems: 5 } })
|
||||
const lister = new FakeProvider()
|
||||
withViewer(lister)
|
||||
await provide(ctx, plain)
|
||||
await provide(ctx, declaredOnly)
|
||||
await provide(ctx, lister)
|
||||
|
||||
expect(ctx.forge.viewerSources()).toEqual([
|
||||
{ forge: 'fake', hosts: ['fake.test'], filters: new Set(['review-requested', 'authored']), maxItems: 40 },
|
||||
])
|
||||
})
|
||||
|
||||
it('delegates a viewer list read and a count to the provider of the forge', async () => {
|
||||
ctx = await forgeContext()
|
||||
const provider = new FakeProvider()
|
||||
const { listForViewer, countForViewer } = withViewer(provider)
|
||||
await provide(ctx, provider)
|
||||
|
||||
await expect(ctx.forge.listForViewer('fake', query, signal)).resolves.toBe(list)
|
||||
expect(listForViewer).toHaveBeenCalledWith(query, expect.any(AbortSignal))
|
||||
await expect(ctx.forge.countForViewer('fake', 'fake.test', signal)).resolves.toEqual(new Map([['review-requested', 3], ['authored', 1]]))
|
||||
expect(countForViewer).toHaveBeenCalledWith('fake.test', expect.any(AbortSignal))
|
||||
})
|
||||
|
||||
it('reports a provider without viewer lists, another host, and another list as unsupported without asking the provider', async () => {
|
||||
ctx = await forgeContext()
|
||||
const bare = new FakeProvider('bare')
|
||||
const provider = new FakeProvider()
|
||||
const { listForViewer, countForViewer } = withViewer(provider)
|
||||
await provide(ctx, bare)
|
||||
await provide(ctx, provider)
|
||||
|
||||
await expect(ctx.forge.listForViewer('bare', query, signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not read viewer lists' })
|
||||
await expect(ctx.forge.countForViewer('bare', 'fake.test', signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not read viewer lists' })
|
||||
await expect(ctx.forge.listForViewer('fake', { ...query, host: 'other.test' }, signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not list change requests on other.test' })
|
||||
await expect(ctx.forge.countForViewer('fake', 'other.test', signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not list change requests on other.test' })
|
||||
await expect(ctx.forge.listForViewer('fake', { ...query, filter: 'involved' }, signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not read the involved list' })
|
||||
expect(listForViewer).not.toHaveBeenCalled()
|
||||
expect(countForViewer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a viewer read for a forge without a provider', async () => {
|
||||
ctx = await forgeContext()
|
||||
await expect(ctx.forge.listForViewer('missing', query, signal)).rejects.toThrow('no provider is registered for "missing"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('forge descriptions', () => {
|
||||
it('delegates a description read and reports a provider without it as unsupported', async () => {
|
||||
ctx = await forgeContext()
|
||||
const provider = new FakeProvider()
|
||||
await provide(ctx, provider)
|
||||
|
||||
await expect(ctx.forge.readDescription(ref(4), signal))
|
||||
.resolves.toEqual({ code: 'unsupported', message: 'This provider does not read descriptions' })
|
||||
const description: ChangeRequestDescription = {
|
||||
body: 'Body', labels: [], labelsTruncated: false, images: {}, imagesExpireAt: null, createdAt: '2026-11-10T00:00:00Z',
|
||||
}
|
||||
const readDescription = vi.fn(async () => description)
|
||||
Object.assign(provider, { readDescription })
|
||||
await expect(ctx.forge.readDescription(ref(4), signal)).resolves.toBe(description)
|
||||
expect(readDescription).toHaveBeenCalledWith(ref(4), expect.any(AbortSignal))
|
||||
})
|
||||
})
|
||||
@@ -1353,6 +1353,33 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'the merge base\'s full object name, or why the host did not provide it; `unsupported` when the provider cannot name merge bases.',
|
||||
throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'],
|
||||
},
|
||||
{
|
||||
signature: 'viewerSources(): ForgeViewerSource[]',
|
||||
description: 'List the viewer lists every registered provider offers; `forge/providers-changed` announces a change.',
|
||||
parameters: [],
|
||||
returns: 'one source per provider that declares viewer lists and reads them, in registration order.',
|
||||
},
|
||||
{
|
||||
signature: 'async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise<ForgeViewerList | ForgeFailure>',
|
||||
description: 'Read one list of open change requests that involve the signed-in user.',
|
||||
parameters: [{ name: 'forge', description: 'forge family of a registered provider.' }, { name: 'query', description: 'host, list, repository, and limit of the read.' }, { name: 'signal', description: 'cancellation of the read.' }],
|
||||
returns: 'the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list.',
|
||||
throws: ['when no provider serves `forge`, or with `signal.reason` when it aborts.'],
|
||||
},
|
||||
{
|
||||
signature: 'async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>',
|
||||
description: 'Count the change requests in each viewer list a provider offers on one host.',
|
||||
parameters: [{ name: 'forge', description: 'forge family of a registered provider.' }, { name: 'host', description: 'lowercase host name the provider lists on.' }, { name: 'signal', description: 'cancellation of the read.' }],
|
||||
returns: 'the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`.',
|
||||
throws: ['when no provider serves `forge`, or with `signal.reason` when it aborts.'],
|
||||
},
|
||||
{
|
||||
signature: 'async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>',
|
||||
description: 'Read the description and labels of a change request.',
|
||||
parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'signal', description: 'cancellation of the read.' }],
|
||||
returns: 'the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions.',
|
||||
throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'],
|
||||
},
|
||||
{
|
||||
signature: 'async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>',
|
||||
description: 'Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced with `forge/review-changed`.',
|
||||
@@ -6172,6 +6199,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
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}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestDescription',
|
||||
declaration: 'export interface ChangeRequestDescription {\n readonly body: string;\n readonly labels: readonly ChangeRequestLabel[];\n readonly labelsTruncated: boolean;\n readonly images: Readonly<Record<string, string>>;\n readonly imagesExpireAt: string | null;\n readonly createdAt: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestIssue',
|
||||
declaration: 'export interface ChangeRequestIssue {\n readonly repository: ForgeRepository;\n readonly number: number;\n readonly title: string;\n readonly state: \'open\' | \'closed\';\n readonly url: string;\n}',
|
||||
@@ -6180,6 +6211,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ChangeRequestKey',
|
||||
declaration: 'export type ChangeRequestKey = Branded<\'ChangeRequestKey\'>;',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestLabel',
|
||||
declaration: 'export interface ChangeRequestLabel {\n readonly name: string;\n readonly color: string | null;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestListener',
|
||||
declaration: 'export type ChangeRequestListener = (update: ChangeRequestUpdate) => void;',
|
||||
@@ -6200,10 +6235,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ChangeRequestState',
|
||||
declaration: 'export type ChangeRequestState = \'open\' | \'closed\' | \'merged\';',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestSummary',
|
||||
declaration: 'export interface ChangeRequestSummary {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly draft: boolean;\n readonly author: ForgeCommentAuthor | null;\n readonly headSha: string;\n readonly checksRollup: ChecksRollup;\n readonly reviewDecision: ReviewDecision;\n readonly viewerReview: ChangeRequestViewerReview | null;\n readonly viewerRequest: {\n readonly team: string | null;\n } | null;\n readonly closingIssues: readonly ChangeRequestIssue[];\n readonly closingIssuesTruncated: boolean;\n readonly updatedAt: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestUpdate',
|
||||
declaration: 'export type ChangeRequestUpdate = {\n readonly key: ChangeRequestKey;\n readonly fetchedAt: number;\n} & ({\n readonly snapshot: ChangeRequestSnapshot;\n} | {\n readonly failure: ForgeFailure;\n});',
|
||||
},
|
||||
{
|
||||
name: 'ChangeRequestViewerReview',
|
||||
declaration: 'export interface ChangeRequestViewerReview {\n readonly verdict: ReviewVerdict;\n readonly reviewedSha: string | null;\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}',
|
||||
@@ -6874,7 +6917,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgeFailure',
|
||||
declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unsupported\' | \'unavailable\';\n readonly message: string;\n}',
|
||||
declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'rate-limited\' | \'unsupported\' | \'unavailable\';\n readonly message: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeFileLayer',
|
||||
@@ -6962,7 +7005,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgeProvider',
|
||||
declaration: 'export interface ForgeProvider {\n readonly forge: string;\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 readiness(host: string, signal: AbortSignal): Promise<ForgeReadiness>;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined>;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>;\n diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise<string | ForgeFailure>;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise<string | /* …truncated — full shape in source */',
|
||||
declaration: 'export interface ForgeProvider {\n readonly forge: string;\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 readiness(host: string, signal: AbortSignal): Promise<ForgeReadiness>;\n markReady(ref: ChangeRequestRef, signal: AbortSig /* …truncated — full shape in source */',
|
||||
},
|
||||
{
|
||||
name: 'ForgeReadiness',
|
||||
@@ -7048,6 +7091,26 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ForgeViewedState',
|
||||
declaration: 'export type ForgeViewedState = \'viewed\' | \'unviewed\' | \'dismissed\';',
|
||||
},
|
||||
{
|
||||
name: 'ForgeViewerCapability',
|
||||
declaration: 'export interface ForgeViewerCapability {\n readonly hosts: readonly string[];\n readonly filters: ReadonlySet<ForgeViewerFilter>;\n readonly maxItems: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeViewerFilter',
|
||||
declaration: 'export type ForgeViewerFilter = \'review-requested\' | \'authored\' | \'involved\';',
|
||||
},
|
||||
{
|
||||
name: 'ForgeViewerList',
|
||||
declaration: 'export interface ForgeViewerList {\n readonly viewer: string;\n readonly items: readonly ChangeRequestSummary[];\n readonly total: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeViewerQuery',
|
||||
declaration: 'export interface ForgeViewerQuery {\n readonly host: string;\n readonly filter: ForgeViewerFilter;\n readonly repository: Pick<ForgeRepository, \'owner\' | \'name\'> | null;\n readonly limit: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeViewerSource',
|
||||
declaration: 'export interface ForgeViewerSource extends ForgeViewerCapability {\n readonly forge: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeBlocker',
|
||||
declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';',
|
||||
|
||||
@@ -440,6 +440,11 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
ForgeReviewersRequest: 'forge.md',
|
||||
ForgeViewedFiles: 'forge.md',
|
||||
ForgeViewedRequest: 'forge.md',
|
||||
ForgeViewerFilter: 'forge.md',
|
||||
ForgeViewerQuery: 'forge.md',
|
||||
ForgeViewerList: 'forge.md',
|
||||
ForgeViewerSource: 'forge.md',
|
||||
ChangeRequestDescription: 'forge.md',
|
||||
ForgeReviewChange: 'forge.md',
|
||||
ForgeLens: 'forge.md',
|
||||
ForgeLensRequest: 'forge.md',
|
||||
|
||||
@@ -2958,6 +2958,51 @@
|
||||
"symbol": "ForgeViewedRequest",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeViewerFilter",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeViewerCapability",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeViewerSource",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeViewerQuery",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestViewerReview",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestSummary",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeViewerList",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestDescription",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ChangeRequestLabel",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeReviewChange",
|
||||
|
||||
Reference in new issue
Block a user