* ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu <[email protected]> Co-authored-by: imccyu <[email protected]>
216 lines
9.7 KiB
TypeScript
216 lines
9.7 KiB
TypeScript
/** Keyless assembled-Web evidence for GitHub ready-for-review Session creation. */
|
|
|
|
import { createHmac } from 'node:crypto'
|
|
import { createServer } from 'node:http'
|
|
import type { AddressInfo } from 'node:net'
|
|
import { fileURLToPath } from 'node:url'
|
|
import type { Browser, Page } from 'playwright'
|
|
import { chromium } from 'playwright'
|
|
import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest'
|
|
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
|
|
import { LlmAdapter } from '@deepseek-ai/dsh-llm'
|
|
import type {} from '@deepseek-ai/dsh-webhook'
|
|
import {
|
|
captureExpandedTurnProcessAria,
|
|
captureStableAria,
|
|
compareOrRefreshGolden,
|
|
launchWebScaffold,
|
|
watchConsole,
|
|
webSnapshotMode,
|
|
type WebScaffold,
|
|
} from './scaffold.ts'
|
|
import { saveFailureShot } from './support.ts'
|
|
|
|
const MODE = webSnapshotMode()
|
|
const OVERLAY = fileURLToPath(new URL('../../../packages/experimental/webhook-github/examples/github-review/cordis.yml', import.meta.url))
|
|
const EXPECTED = fileURLToPath(new URL('./expected/github-ready-review/conversation.expected.md', import.meta.url))
|
|
const EXPANDED_EXPECTED = fileURLToPath(
|
|
new URL('./expected/github-ready-review/conversation-expanded.expected.md', import.meta.url),
|
|
)
|
|
const PROVIDER = 'github-webhook-review-test'
|
|
const MODEL = 'reply'
|
|
const SECRET = 'github-webhook-review-secret'
|
|
const TITLE = 'Review deepseek-ai/deepseek-harness#314'
|
|
const REPLY = 'Review complete: no actionable findings.'
|
|
|
|
/** Deterministic model response for the webhook-created Session. */
|
|
class ReviewAdapter extends LlmAdapter {
|
|
override async listModels(provider: string) { return [{ provider, id: MODEL, name: `${provider}/${MODEL}` }] }
|
|
readonly requests: GenerateOptions[] = []
|
|
|
|
override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
|
this.requests.push(options)
|
|
yield { type: 'block-start', index: 0, blockType: 'text' }
|
|
yield { type: 'block-end', index: 0, block: { type: 'text', text: REPLY } }
|
|
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
}
|
|
}
|
|
|
|
/** Reserve one currently free loopback port for the isolated WebServer. */
|
|
async function freePort(): Promise<number> {
|
|
const server = createServer()
|
|
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
|
|
const port = (server.address() as AddressInfo).port
|
|
await new Promise<void>(resolve => server.close(() => { resolve() }))
|
|
return port
|
|
}
|
|
|
|
/** Sign one exact GitHub JSON body. */
|
|
function signature(body: string): string {
|
|
return `sha256=${createHmac('sha256', SECRET).update(body).digest('hex')}`
|
|
}
|
|
|
|
/** Send one signed GitHub delivery to a selected origin. */
|
|
async function send(origin: string, delivery: string, body: object, event = 'pull_request'): Promise<Response> {
|
|
const text = JSON.stringify(body)
|
|
return await fetch(`${origin}/github`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
'x-hub-signature-256': signature(text),
|
|
'x-github-event': event,
|
|
'x-github-delivery': delivery,
|
|
},
|
|
body: text,
|
|
})
|
|
}
|
|
|
|
describe.skipIf(MODE === 'record')('web e2e: GitHub ready-for-review', () => {
|
|
let scaffold: WebScaffold
|
|
let browser: Browser
|
|
let page: Page
|
|
let webhookOrigin: string
|
|
let tripwire: ReturnType<typeof watchConsole>
|
|
let previousPort: string | undefined
|
|
let previousSecret: string | undefined
|
|
const adapter = new ReviewAdapter()
|
|
|
|
beforeAll(async () => {
|
|
previousPort = process.env.DSH_GITHUB_WEBHOOK_PORT
|
|
previousSecret = process.env.DSH_GITHUB_WEBHOOK_SECRET
|
|
const port = await freePort()
|
|
process.env.DSH_GITHUB_WEBHOOK_PORT = String(port)
|
|
process.env.DSH_GITHUB_WEBHOOK_SECRET = SECRET
|
|
webhookOrigin = `http://127.0.0.1:${String(port)}`
|
|
scaffold = await launchWebScaffold({
|
|
extraOverlayPath: OVERLAY,
|
|
profile: { packages: [
|
|
{ dir: fileURLToPath(new URL('../../../packages/experimental/webhook', import.meta.url)) },
|
|
{ dir: fileURLToPath(new URL('../../../packages/experimental/webhook-github', import.meta.url)) },
|
|
] },
|
|
})
|
|
scaffold.ctx.effect(
|
|
() => scaffold.ctx.llm.registerAdapter([PROVIDER], adapter),
|
|
'GitHub webhook review adapter',
|
|
)
|
|
await scaffold.ctx.agentDefaultModel.saveSelection({ provider: PROVIDER, model: MODEL })
|
|
|
|
browser = await chromium.launch()
|
|
page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'en-US' })
|
|
await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'en') })
|
|
tripwire = watchConsole(page)
|
|
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
|
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
|
}, 60_000)
|
|
|
|
afterAll(async () => {
|
|
await browser?.close()
|
|
await scaffold?.close()
|
|
if (previousPort === undefined) Reflect.deleteProperty(process.env, 'DSH_GITHUB_WEBHOOK_PORT')
|
|
else process.env.DSH_GITHUB_WEBHOOK_PORT = previousPort
|
|
if (previousSecret === undefined) Reflect.deleteProperty(process.env, 'DSH_GITHUB_WEBHOOK_SECRET')
|
|
else process.env.DSH_GITHUB_WEBHOOK_SECRET = previousSecret
|
|
})
|
|
|
|
it('isolates ingress and creates a browsable Workspace Session', async () => {
|
|
onTestFailed(async () => { await saveFailureShot(page, 'github-ready-review') })
|
|
const before = scaffold.ctx.agents.list().length
|
|
|
|
expect((await fetch(`${webhookOrigin}/api`)).status).toBe(404)
|
|
expect((await send(scaffold.baseUrl, 'wrong-port', { zen: 'ping' }, 'ping')).status).not.toBe(202)
|
|
expect(scaffold.ctx.agents.list()).toHaveLength(before)
|
|
|
|
expect((await send(webhookOrigin, 'ping', { zen: 'keep it logically awesome' }, 'ping')).status).toBe(202)
|
|
await vi.waitFor(() => { expect(scaffold.ctx.agents.list()).toHaveLength(before) })
|
|
|
|
const payload = {
|
|
action: 'ready_for_review',
|
|
number: 314,
|
|
repository: { full_name: 'deepseek-ai/deepseek-harness' },
|
|
pull_request: {
|
|
title: 'Fix session replay',
|
|
html_url: 'https://github.com/deepseek-ai/deepseek-harness/pull/314',
|
|
draft: false,
|
|
user: { login: 'octocat' },
|
|
base: { ref: 'master', sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' },
|
|
head: { ref: 'fix-session-replay', sha: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' },
|
|
},
|
|
}
|
|
const completed = Promise.withResolvers<undefined>()
|
|
let reviewSession: string | undefined
|
|
const off = scaffold.ctx.on('session/event', (session, event) => {
|
|
if (event.type === 'user/message' && event.data.source.kind === 'webhook'
|
|
&& event.data.source.provider === 'github' && event.data.source.source === 'primary-github'
|
|
&& event.data.source.deliveryId === 'ready' && event.data.source.ruleId === 'review-pr-when-ready') reviewSession = session.id
|
|
if (event.type === 'turn/end' && session.id === reviewSession) completed.resolve(undefined)
|
|
})
|
|
const entered = Promise.withResolvers<undefined>()
|
|
const release = Promise.withResolvers<undefined>()
|
|
const createWorkspace = scaffold.ctx.workspaceRegistry.create.bind(scaffold.ctx.workspaceRegistry)
|
|
const create = vi.spyOn(scaffold.ctx.workspaceRegistry, 'create').mockImplementationOnce(async (...args) => {
|
|
entered.resolve(undefined)
|
|
await release.promise
|
|
return await createWorkspace(...args)
|
|
})
|
|
onTestFinished(() => {
|
|
off()
|
|
release.resolve(undefined)
|
|
create.mockRestore()
|
|
})
|
|
try {
|
|
expect((await send(webhookOrigin, 'ready', payload)).status).toBe(202)
|
|
await entered.promise
|
|
expect(scaffold.ctx.agents.list()).toHaveLength(before)
|
|
expect(adapter.requests).toHaveLength(0)
|
|
release.resolve(undefined)
|
|
await completed.promise
|
|
} finally {
|
|
release.resolve(undefined)
|
|
create.mockRestore()
|
|
off()
|
|
}
|
|
expect(scaffold.ctx.agents.list()).toHaveLength(before + 1)
|
|
expect(adapter.requests).toHaveLength(1)
|
|
|
|
const agent = scaffold.ctx.agents.list().find(candidate => candidate.session.header.cwd === scaffold.workspaceCwd)
|
|
expect(agent).toBeDefined()
|
|
const workspace = await scaffold.ctx.workspaceRegistry.resolveByPath(scaffold.workspaceCwd)
|
|
expect(workspace?.sessionIds).toContain(agent?.id)
|
|
const webhookMessage = adapter.requests[0]?.messages.find(message => message.role === 'user' && message.source?.kind === 'webhook')
|
|
expect(webhookMessage?.content).toHaveLength(1)
|
|
const [content] = webhookMessage?.content ?? []
|
|
expect(content?.type).toBe('text')
|
|
if (content?.type !== 'text') throw new Error('webhook prompt was not text')
|
|
expect(content.text).toContain('exact head SHA bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
|
|
|
|
const workspaceRow = page.locator('[role="treeitem"]').first()
|
|
if (await workspaceRow.getAttribute('aria-expanded') !== 'true') await workspaceRow.click()
|
|
await page.bringToFront()
|
|
await page.getByText(TITLE, { exact: true }).click()
|
|
await page.getByText(REPLY, { exact: true }).waitFor({ state: 'visible', timeout: 30_000 })
|
|
const reviewRow = page.locator('[role="treeitem"]').filter({ has: page.getByText(TITLE, { exact: true }) })
|
|
await expect.poll(() => reviewRow.getByText('Unread', { exact: true }).count()).toBe(0)
|
|
const tree = await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd)
|
|
const conversation = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
|
|
await compareOrRefreshGolden(EXPECTED, `${tree}\n\n---\n\n${conversation}`, MODE)
|
|
const expanded = await captureExpandedTurnProcessAria(
|
|
page,
|
|
'[class*="centerCol"]',
|
|
scaffold.workspaceCwd,
|
|
)
|
|
await compareOrRefreshGolden(EXPANDED_EXPECTED, `${tree}\n\n---\n\n${expanded}`, MODE)
|
|
expect(tripwire.pageErrors).toEqual([])
|
|
expect(tripwire.warnings).toEqual([])
|
|
}, 60_000)
|
|
})
|