fix(forge-session): cancel discovery when Sessions close

This commit is contained in:
Yichen Jiang committed 2026-10-26 17:43:59 +08:00
1 parent fbcfd80e21
commit 3f53fe39fb
5 files changed
+64 -10

No files matched your search

@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-forge-session/use-this-package:
en: 0b75d06236040dd9
zh: ff30c83707003bca
en: 022ab6a18364aa44
zh: adc91aef3f4273e3
/deepseek-ai-dsh-experimental-forge-session/understand-the-implementation:
en: ccc7ad69f5837528
zh: 369c08bf4f7e6e4d
@@ -36,7 +36,7 @@ Mount the service with the forge registry, a provider, and the Session projectio
`ctx.forgeSession.changeRequests(session)` returns the visible bindings in first-recorded order. Each entry carries the URL, its `origin` (`created`, `discovered`, or `tracked`), the provider reference or `null` when no provider serves the URL, and the latest polling result or `null`. `watch(session, listener)` is an effect on the calling fiber: while a Session has a watcher, every visible binding that a provider serves is polled, and listeners receive the complete list after each later binding change or polling result. `track(session, url)` binds a URL under the provider's canonical form, or restores a dismissed binding, and throws when no provider recognizes the URL. `dismiss(session, url)` hides a visible binding; other URLs leave the log unchanged.
A `bash` or `pwsh` call binds evidence only from its first result, and only when the tool execution itself succeeded; the command's exit status does not matter. A command containing `gh pr create` or `gh pr new` binds every `/pull/<number>` URL in its text output. A command containing `git push`, optionally with leading `-C`, `-c`, or long Git options, records each branch listed under a `To <remote>` line as created, updated, forced, or already up to date; rejected and deleted refs, new tags, and explicit refs outside `refs/heads/` are skipped. For each pushed branch whose remote a provider serves, the service runs `ctx.forge.findByHead` within `discoveryTimeoutMs` and appends a `discover` record for every returned change request that is not bound. Dismissed bindings remain bound and are skipped; only `track` restores them. Every push repeats the lookup; failures are logged as warnings. URLs that differ only in scheme, letter case, query, fragment, or trailing slashes name the same binding.
A `bash` or `pwsh` call binds evidence only from its first result, and only when the tool execution itself succeeded; the command's exit status does not matter. A command containing `gh pr create` or `gh pr new` binds every `/pull/<number>` URL in its text output. A command containing `git push`, optionally with leading `-C`, `-c`, or long Git options, records each branch listed under a `To <remote>` line as created, updated, forced, or already up to date; rejected and deleted refs, new tags, and explicit refs outside `refs/heads/` are skipped. For each pushed branch whose remote a provider serves, the service runs `ctx.forge.findByHead` within `discoveryTimeoutMs` and appends a `discover` record for every returned change request that is not bound. Dismissed bindings remain bound and are skipped; only `track` restores them. Every push repeats the lookup; failures are logged as warnings. Closing a Session cancels its unfinished lookups without adding bindings. Reopening it does not repeat those lookups; another push or `track` can bind the change request. URLs that differ only in scheme, letter case, query, fragment, or trailing slashes name the same binding.
Binding actions are `plugin:forge-session/binding` records listed in the [experimental persistence catalog](../../../docs/experimental-persistence-catalog.md); fork and resume carry them with the shell events, so a fork starts with its parent's bindings. `discoveryTimeoutMs` is listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-session).
@@ -36,7 +36,7 @@ kind: "package-reference"
`ctx.forgeSession.changeRequests(session)` 按首次记录的顺序返回可见的绑定。每一项包含 URL、其 `origin`(`created`、`discovered` 或 `tracked`)、提供方引用(没有提供方服务该 URL 时为 `null`)以及最近一次轮询结果(尚无结果时为 `null`)。`watch(session, listener)` 是调用方 fiber 上的 effect:Session 有监听方期间,提供方服务的每个可见绑定都会被轮询;此后每次绑定变化或轮询结果到达时,监听方都会收到完整列表。`track(session, url)` 以提供方的规范形式绑定 URL,或恢复已隐藏的绑定;没有提供方识别该 URL 时抛错。`dismiss(session, url)` 隐藏一个可见绑定;其他 URL 不会改变日志。
`bash` 或 `pwsh` 调用只从其第一个结果中提取证据,且仅当工具执行本身成功时才提取;命令的退出状态不影响结果。包含 `gh pr create` 或 `gh pr new` 的命令会绑定其文本输出中的每个 `/pull/<number>` URL。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To <remote>` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `refs/heads/` 之外的引用会被跳过。对远端由提供方服务的每个被推送分支,服务在 `discoveryTimeoutMs` 内调用 `ctx.forge.findByHead`,并为返回的每个尚未绑定的变更请求追加一条 `discover` 记录。已隐藏的绑定仍视为已绑定而被跳过;只有 `track` 会恢复它们。每次推送都会重新查找;失败记录为警告日志。仅在协议、大小写、查询、片段或末尾斜杠上不同的 URL 指向同一个绑定。
`bash` 或 `pwsh` 调用只从其第一个结果中提取证据,且仅当工具执行本身成功时才提取;命令的退出状态不影响结果。包含 `gh pr create` 或 `gh pr new` 的命令会绑定其文本输出中的每个 `/pull/<number>` URL。包含 `git push` 的命令(可带前置的 `-C`、`-c` 或 Git 长选项)会记录 `To <remote>` 行下列出的每个已创建、已更新、已强制推送或已是最新的分支;被拒绝、已删除的引用、新标签,以及明确位于 `refs/heads/` 之外的引用会被跳过。对远端由提供方服务的每个被推送分支,服务在 `discoveryTimeoutMs` 内调用 `ctx.forge.findByHead`,并为返回的每个尚未绑定的变更请求追加一条 `discover` 记录。已隐藏的绑定仍视为已绑定而被跳过;只有 `track` 会恢复它们。每次推送都会重新查找;失败记录为警告日志。关闭 Session 会取消其未完成的查找,不追加绑定。重新打开不会补做这些查找;可再次推送或用 `track` 绑定变更请求。仅在协议、大小写、查询、片段或末尾斜杠上不同的 URL 指向同一个绑定。
绑定操作是 `plugin:forge-session/binding` 插件记录,列于[实验性持久化目录](../../../docs/experimental-persistence-catalog.zh.md);fork 与恢复会把它们与 shell 事件一同带上,因此 fork 出的 Session 从父 Session 的绑定开始。`discoveryTimeoutMs` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-session)。
@@ -37,7 +37,7 @@ interface SessionWatch {
* requests through `ctx.forge`.
*/
export class ForgeSessionService extends Service {
static inject = ['forge', 'sessionProjections']
static inject = ['forge', 'sessions', 'sessionProjections']
static Config: z<Config> = z.object({
discoveryTimeoutMs: z.number().default(30_000),
@@ -47,6 +47,7 @@ export class ForgeSessionService extends Service {
private readonly discoveryTimeoutMs: number
private readonly watches = new WeakMap<Session, SessionWatch>()
private readonly discoveries = new Set<Promise<void>>()
private readonly sessionLifetimes = new WeakMap<Session, AbortController>()
private readonly lifetime = new AbortController()
private projection!: ProjectionHandle<ForgeChangeRequestsState>
@@ -139,6 +140,10 @@ export class ForgeSessionService extends Service {
this.home.on('session/event', (session: Session, event: SessionEvent) => {
this.react(session, event)
})
this.home.on('session/disposed', (session: Session) => {
this.sessionLifetimes.get(session)?.abort(new Error('forge-session: Session was disposed'))
this.sessionLifetimes.delete(session)
})
}
private state(session: Session): ForgeChangeRequestsState {
@@ -200,19 +205,25 @@ export class ForgeSessionService extends Service {
private discover(session: Session, push: PushedBranch): void {
const repository = this.home.forge.repositoryFromRemote(push.remote)
if (repository === undefined) return
const task = this.lookup(session, repository, push.branch).catch((error: unknown) => {
if (this.lifetime.signal.aborted) return
let lifetime = this.sessionLifetimes.get(session)
if (lifetime === undefined) {
lifetime = new AbortController()
this.sessionLifetimes.set(session, lifetime)
}
const signal = AbortSignal.any([this.lifetime.signal, lifetime.signal])
const task = this.lookup(session, repository, push.branch, signal).catch((error: unknown) => {
if (signal.aborted) return
this.home.logger.warn(`forge-session: change request lookup for ${push.branch} failed: ${error instanceof Error ? error.message : String(error)}`)
})
this.discoveries.add(task)
void task.then(() => this.discoveries.delete(task))
}
private async lookup(session: Session, repository: ForgeRepository, branch: string): Promise<void> {
using timeout = deadline(this.lifetime.signal, this.discoveryTimeoutMs, 'FORGE_DISCOVERY_TIMEOUT')
private async lookup(session: Session, repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<void> {
using timeout = deadline(signal, this.discoveryTimeoutMs, 'FORGE_DISCOVERY_TIMEOUT')
const refs = await this.home.forge.findByHead(repository, branch, timeout.signal)
if (this.lifetime.signal.aborted) return
for (const ref of refs) {
if (signal.aborted || this.home.sessions.get(session.id) !== session) return
const url = this.home.forge.changeRequestUrl(ref)
if (this.state(session).bindings.some(binding => sameChangeRequestUrl(binding.url, url))) continue
appendPluginRecord(session, BINDING_RECORD, { action: 'discover', url })
@@ -66,6 +66,49 @@ describe('forgeSession bindings', () => {
})
describe('forgeSession discovery', () => {
it('cancels a closed Session lookup and never writes its result into a same-id replacement', async () => {
const { ctx, provider } = await open()
const owner = ctx.plugin({ inject: ['sessions'], apply() {} })
await owner
const session = owner.ctx.sessions.create()
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
const result = Promise.withResolvers<readonly ReturnType<typeof pull>[]>()
provider.findImpl = () => result.promise
try {
push(session, 'push', 'feat')
expect(provider.lookups).toHaveLength(1)
await owner.dispose()
expect(provider.lookups[0]?.signal.aborted).toBe(true)
const replacement = ctx.sessions.create(session.id)
result.resolve([pull(7)])
await settle()
expect(records(session)).toEqual([])
expect(records(replacement)).toEqual([])
expect(warn).not.toHaveBeenCalled()
} finally {
result.resolve([])
}
})
it('stops publishing lookup results when the Session closes after the first binding', async () => {
const { ctx, provider } = await open()
const session = ctx.sessions.prepare()
const detach = ctx.sessions.enter(session)
ctx.sessions.announce(session)
ctx.on('session/event', (changed, event) => {
if (changed === session && pluginRecordOf(event)?.type === 'plugin:forge-session/binding') detach()
})
provider.heads.set('feat', [pull(7), pull(8)])
try {
push(session, 'push', 'feat')
await settle()
expect(records(session)).toEqual([{ action: 'discover', url: pullUrl(7) }])
expect(ctx.sessions.get(session.id)).toBeUndefined()
} finally {
detach()
}
})
it('records change requests found for a pushed branch', async () => {
const { ctx, provider, session } = await open()
provider.heads.set('feat', [pull(7)])