Files
hapi/shared/src/sessionSummary.test.ts
T
e55d29c056 feat(session): opt-in GitHub PR awareness + explicit attach (#1163)
* feat(session): structured externalRefs + list PR chip

Add optional metadata.externalRefs for durable session↔GitHub PR
identity and a clickable primary-PR chip on session list rows, plus
GET /api/sessions/:id/external-refs. Fixes titles-as-identity hacks
without title parsing (tiann/hapi#1160).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(session): validate external PR URL identity

Prevent structured PR chips from linking outside the declared GitHub repository and pull request.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(session): preserve externalRefs on merge + restore row focus group

Carry forward metadata.externalRefs when consolidating into a replacement
session row that omitted them (explicit new values still win). Move
group/session-row back onto the focusable list button so keyboard tooltips
reveal correctly (PR #1161 review).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(session): carry forward externalRefs on bootstrap/metadata write

Preserve metadata.externalRefs when CLI pickExistingSessionMetadata and
hub updateSessionMetadata receive sparse replacements that omit the
field; explicit incoming refs (including []) still win. Closes the
resume/bootstrap data-loss path left after mergeSessions (PR #1161).

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(session): opt-in GitHub PR awareness and explicit attach

Add hub githubPrAwareness (default off), features API, PUT/CLI external-refs
write path, Settings toggle, link dialog, hapi link-pr, and MCP link_pr so
sessions can attach to PRs without title scraping. Depends on #1161 schema.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(session): cache PR status on externalRefs for chip display

Extend GithubPrExternalRef with optional status/statusCheckedAt/statusAction
so Meta can write classifier health onto the attachment. Chip renders emoji
+ #N with status tone. Fixes link_pr tool-list expectations in MCP tests.

Part of tiann/hapi#1162 / #1163 (awareness + state in one PR).

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): mock AppContext for General settings language test

SettingsGeneralPage now reads githubPrAwareness via useAppContext /
useFeatures; wrap the settings page suite with mocks so the language
inline test stops throwing AppContext is not available.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): put PR chip left of session list time

Chip was a trailing sibling outside the row button, so rows with chips
shoved the relative-time column left. Keep time as the stable trailing
meta; optional chip sits immediately before it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): mute PR chip when statusCheckedAt is older than 2h

Cache honesty for Meta-filled externalRefs — never live-query GitHub from
the browser; stale chips show ? and a muted tone.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): use relative ago in PR chip tooltip title

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(web): keep companion baseUrl when mocking AppContext for features

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(session): forge-native PR chip snapshot + estate display profile

Replace Meta babysit status enums with GitHub-shaped openState/checks/merge
plus opaque estateCode. Chip terms (emoji, action prose) come from
$HAPI_HOME/pr-chip-display.json served on GET /api/features.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): use bun:test in prChipDisplay tests

Hub package typechecks include *.test.ts and has no vitest types;
CI failed resolving 'vitest' from the forge chip display suite.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(web): compact PR chip to emoji; details on hover/long-press

Session list chips show status glyph only (estate emoji, or PR/?) so
multi-digit numbers stop crowding the row. Full repo#N + status copy
moves to HoverTooltip (desktop hover/focus) and touch long-press.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): show PR detail in session action menu, not chip long-press

Keep desktop HoverTooltip on the compact emoji chip. Mobile long-press
stays on the session row; linked PR identity/status now tops that menu.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): chip-specific hover tooltip + emoji in PR menu header

Keep HoverTooltip scoped to the PR chip (not row), unclip overflow, and
front the same status glyph in list long-press and session ⋯ menus.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): give claudeRemote first-result test a 15s CI timeout

Same flake as sibling cases under full-suite load; default 5s timed out
twice on #1163 after upstream merge.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): drop duplicate vitest timeout after merge

Upstream #1493 uses it(name, { timeout }, fn); the merge also kept the
legacy third-arg timeout, which Vitest 4 types reject.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,cli): address Codex Majors on PR awareness

Owner-gate PATCH /features, persist githubPrAwareness via updateSettings,
and fail MCP link_pr unless flushMetadata keeps the ref.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli,web,shared): close remaining Codex findings on #1163

Gate MCP link_pr on hub awareness, upsert externalRefs, mark undated
chip snapshots stale, and hide the settings toggle from tenants.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,cli,web): CLI features probe + preserve secondary PR refs

Expose GET /cli/features and /cli/sessions/:id/external-refs for CLI
auth, upsert primary links in hapi link-pr and the web dialog, and tick
chip/menu staleness on a minute clock.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,cli,web): atomic external-ref upsert + create-session gate

Hub merges refs inside the metadata-version retry loop; CLI/web call
upsert/remove-primary instead of snapshot PUT. Strip externalRefs on
CLI create when awareness is off; list chips are display-only in the
row button.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(shared,hub,cli): preserve PR health cache on same-identity upsert

Re-linking an already-linked github_pr was wiping openState/checks/merge
snapshots. Merge identity fields instead of replace-on-upsert.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(shared,cli): case-insensitive PR identity + valid source fixtures

Treat owner/repo as case-insensitive on upsert/re-link so cached health is
not dropped, and keep regression fixtures within agent|user|inferred.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): initializeToken before hapi link-pr hub calls

Match ping-peer/inspect-peer so settings.json auth and apiUrl load
before getAuthToken/axios; keep --help free of prompts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): omit link_pr from standalone hapi mcp defaults

Keep awareness opt-in: internal bridges still pass --tools after hub probe.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(cli): match default MCP tool registration order

list_peers registers after ping/inspect on the stdio bridge.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli,shared): exact link_pr auto-approve + single primary refs

Stop substring/call-id matching for link_pr, and reject multi-primary
externalRefs at the Metadata/PUT schema boundary.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): drop duplicate showSessionSummaryInChat in markdown-a test

Upstream merge left a duplicated mock field that broke tsc.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): cap externalRefs count and disable env-pinned PR toggle

Bound externalRefs at 32 in schema + socket update-metadata ingress;
forward disabled on SettingsSwitch when HAPI_GITHUB_PR_AWARENESS pins the hub.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): validate mutate externalRefs + hapi-scoped link_pr approval

Re-parse upsert transforms with ExternalRefsSchema before persist; only
auto-approve link_pr when MCP server provenance is hapi or the tool name is
a verified HAPI bridge identity.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): trust HAPI link_pr provenance from envelope only

Auto-approve link_pr variants only when trustedHapiMcp is set from MCP
elicitation envelope serverName, not from tool arguments. ACP no longer
reads forged serverName from rawInput; HAPI mcp_tool_call approvals route
through the permission handler instead of blanket bridge auto-accept.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): outer envelope only for trusted HAPI MCP provenance

Do not treat nested elicitation request.serverName as trusted identity;
poll features query so hub-global githubPrAwareness updates reach other tabs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): reject duplicate external ref identities in schema

Case-insensitive github_pr repo+number pairs cannot appear twice in
externalRefs; prevents upsert health merge depending on array order.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): bound repo slugs, hoist PR polling, toggle errors

Cap GitHub repo slugs at 140 chars; share one features query and minute
clock across session list rows; surface githubPrAwareness toggle failures.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): hub upsert link_pr + read-only untrusted gate

MCP link_pr uses atomic hub upsert (no metadata flush retry loop); block
untrusted link_pr auto-approve in read-only mode.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): authoritative hub upsert + merge retry + 400 invalid refs

Stop replaying stale externalRefs through CLI metadata after hub upsert;
recompute merge metadata from the latest target row on version retry;
map ExternalRefsSchema failures to 400 on upsert routes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): fail merge before deleting source on metadata contention

Use METADATA_RETRY_ATTEMPTS for carry-forward metadata during session
merge; throw if externalRefs never commit so the source row is not deleted.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): merge metadata before moving source-owned rows

Run carry-forward metadata merge before messages, scratchlist, and
attachments transfer so a failed merge leaves the source intact.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): validate externalRefs on CLI session create

Share externalRefsInMetadataValid between socket and REST session
ingestion so malformed metadata.externalRefs returns 400 before persist.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): reject non-boolean githubPrAwareness in settings.json

Match serverChanBackgroundOnly: Boolean("false") is true and would
silently enable the opt-in PR-awareness flag from a hand-edited file.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): reveal nested PR chip tooltip on session-row focus

Non-interactive chips sit inside the row button as spans; wire
SESSION_ROW_TOOLTIP_FOCUS_CLASS so keyboard focus shows the tooltip.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): keep raw metadata when linking PR on unparsed rows

mutateSessionExternalRefs reads the on-disk metadata blob instead of
cache-null fallback so link/unlink cannot wipe name/summary/worktree.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): prefer merge conflicts over passing checks on PR chip

Candidate forge keys now rank conflicting/blocked merge ahead of
checks.pass/pending so the chip cannot look healthy when unmergeable.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): localize PR chip detail strings for zh-CN

Map default forge labels and checked/stale/linked through i18n so tooltips
are not mixed-language; pass estate labels through unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): prefer terminal PR openState over clean/pass chip

Merged/closed/draft snapshots must not show "ready to merge" when the last
poll still has clean+pass. Also localize aria-label status via the same
forge-label map as tooltips.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): a11y label and i18n for Link PR invalid input

Give the PR field an aria-label and show localized invalid-input copy
instead of English parseGithubPrInput errors in the dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): gate PR awareness switch; expose nested chip to AT

Disable the settings toggle until features load so owners cannot flip a
placeholder off state. Nested session-row chips use sr-only detail so the
focused row announces PR identity and status.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): refresh MCP link_pr catalog when awareness flips

Re-fetch hub githubPrAwareness for each new HTTP MCP session and invalidate
stale sessions so listTools picks up the toggle without restarting the
Happy server. Stdio --tools remains spawn-scoped.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): gate link_pr at call time without killing MCP sessions

Keep link_pr in the HTTP and stdio catalogs under dynamic awareness, and
re-check the hub flag on each call. Avoids 404ing the stdio bridge session
when Settings toggles awareness mid-run.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): hide MCP link_pr via enable/disable when awareness flips

Keep HTTP/stdio transports alive; toggle RegisteredTool visibility from hub
settings and sync the Codex stdio catalog without killing cached sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): avoid link_pr list_changed loops; poll idle HTTP clients

Only call RegisteredTool enable/disable on actual visibility transitions.
Add a bounded awareness poll so Claude HTTP MCP learns Settings flips
without a client request, and cover idempotent + poll-only transitions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(#1163): accept GHES hosts for GitHub PR external refs

Fold the upstreamable multi-host parser core into PR awareness: validate
github.com and *.ghe.com (plus configureGitHubHosts inject), preserve forge
host in parse/build/upsert, and relax schema URL matching accordingly.
Browser-safe — no operator YAML or Meta tooling in this change.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): keep GHES host through attach + PR identity

Pass parsed.url from UI/CLI/MCP builders, and key identity/dedupe on
host+repo+number so github.com and Enterprise PRs with the same slug
do not collide or share cached health.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): typecheck link-pr GHES attachment test

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): assert GHES link-pr body via toHaveBeenCalledWith

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): do not auto-approve link_pr in read-only mode

Trusted HAPI MCP provenance must not bypass read-only permission mode
when linking a PR; leave the write pending for user approval.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): make list PR chip open its PR and show #N

Render the session-list chip as a sibling link beside the row button
(no nested interactive content) and include the PR number in the
compact glyph so operators can tell which PR is linked at a glance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): drop invalid host from SessionList PR chip test

SessionSummaryMetadata has no host field; CI typecheck failed on the
fixture metadata literal.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): put session-row focus group on the row button

Restore group/session-row on the focusable button so attention and
schedule HoverTooltips still reveal under group-focus-visible.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): align stdio default-tool test with peer/session_job catalog

Standalone MCP defaults now include spawn_peer and session_job; keep
asserting link_pr stays opt-in.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): match merge metadata failure tests to preserve contract

SessionCache throws "Failed to preserve session metadata during merge"
after exhausted retries / store errors; update hub expectations.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): prompt for Codex link_pr instead of native auto-approve

Native approval_mode approve bypassed BasePermissionHandler's read-only
guard; prompt so linking a PR still requires permission in read-only.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): satisfy typecheck on link_pr approval regression

Avoid optional tools property access that failed cli tsc under strict
null checks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): align archive timeout assertion with 503 Cloudflare contract

Upstream #2423 maps ArchiveCleanupError timeout to 503 (not 504) so
Tunnel keeps JSON bodies; update the missed singleflight assertion.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): memoize session-list PR clock between minute ticks

Avoid sampling Date.now() every render so memoized SessionItem rows
do not rerender on unrelated SSE updates when awareness is off.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): preserve machine-spawn stub when attaching a PR

External-ref metadata writes used to clear the preallocation tag, so
adoptPreallocatedSession failed after an early link. Pass
preservePreallocation and cover stub → link → adopt.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): size PR chip padding from quick-action span

Pinned active rows show Unpin + Archive; reserve the CSS action span
so the chip no longer overlaps Unpin and steals clicks.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): align quick-unpin unread focus test with #2434 panels

session-group-unread-peek was removed when collapsed groups kept unread
rows in per-row CollapsiblePanels; update the #2443 focus assertion.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(#1163): unblock passkey browser CI after shared-RP rematch

Playwright route.fulfill drops Location fragments on 3xx, so the
callback never received #state/#code and the opener hung. Apply the
fragment via a document navigation in the harness. Also reuse the
parsed complete form body instead of reading the request twice.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Revert "fix(#1163): unblock passkey browser CI after shared-RP rematch"

This reverts commit 0092ea4b8c69add993fdd2f4b3da411eca641364.

* Revert "Revert "fix(#1163): unblock passkey browser CI after shared-RP rematch""

This reverts commit 1094372855204375a72101c07fa06f70a1aefdd7.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 12:53:26 +08:00

430 lines
15 KiB
TypeScript

import { describe, expect, it } from 'bun:test'
import type { Session } from './schemas'
import {
PENDING_REQUEST_SUMMARY_CAP,
computePendingRequestKinds,
computePendingRequestsCount,
computeTodoProgress,
getPendingRequestKinds,
getPendingRequests,
toSessionSummary,
toSessionSummaryMetadata
} from './sessionSummary'
function makeSession(overrides: Partial<Session> = {}): Session {
return {
id: 'session-1',
namespace: 'default',
active: true,
activeAt: 1000,
updatedAt: 2000,
metadata: { path: '/proj', host: 'local' },
metadataVersion: 1,
agentState: null,
agentStateVersion: 0,
thinking: false,
thinkingAt: 0,
model: null,
modelReasoningEffort: null,
effort: null,
serviceTier: null,
...overrides
}
}
describe('getPendingRequestKinds', () => {
it('classifies ask-user tools as input', () => {
const kinds = getPendingRequestKinds(makeSession({
agentState: {
requests: {
req1: { tool: 'AskUserQuestion', arguments: {} }
}
}
}))
expect(kinds).toEqual(['input'])
})
it('classifies Cursor questions as input', () => {
const kinds = getPendingRequestKinds(makeSession({
agentState: {
requests: {
req1: { tool: 'CursorAskQuestion', arguments: {} }
}
}
}))
expect(kinds).toEqual(['input'])
})
it('classifies other pending tools as permission', () => {
const kinds = getPendingRequestKinds(makeSession({
agentState: {
requests: {
req1: { tool: 'Bash', arguments: {} }
}
}
}))
expect(kinds).toEqual(['permission'])
})
it('returns both kinds when mixed requests are pending', () => {
const kinds = getPendingRequestKinds(makeSession({
agentState: {
requests: {
req1: { tool: 'Bash', arguments: {} },
req2: { tool: 'ask_user_question', arguments: {} }
}
}
}))
expect(kinds).toEqual(['permission', 'input'])
})
})
describe('toSessionSummary', () => {
it('carries createdAt for the fixed-order list sort', () => {
expect(toSessionSummary(makeSession({ createdAt: 1_234 })).createdAt).toBe(1_234)
})
it('includes the pinned state', () => {
expect(toSessionSummary(makeSession({ pinned: true })).pinned).toBe(true)
expect(toSessionSummary(makeSession({ globalPinned: true })).globalPinned).toBe(true)
expect(toSessionSummary(makeSession()).pinned).toBe(false)
expect(toSessionSummary(makeSession()).globalPinned).toBe(false)
})
it('uses grokSessionId as the native resume token', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor: 'grok',
grokSessionId: 'grok-session-1'
}
}))
expect(summary.metadata?.agentSessionId).toBe('grok-session-1')
})
it('uses the native id matching the current flavor instead of a stale id', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor: 'cursor',
codexSessionId: 'stale-codex-id',
cursorSessionId: 'cursor-session-1'
}
}))
expect(summary.metadata?.agentSessionId).toBe('cursor-session-1')
})
it('uses the DSH native session id as the resume token', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor: 'dsh',
codexSessionId: 'stale-codex-id',
dshSessionId: 'dsh-session-1'
}
}))
expect(summary.metadata?.agentSessionId).toBe('dsh-session-1')
})
it('does not fall back to a stale cross-agent id for a known flavor', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor: 'pi',
codexSessionId: 'stale-codex-id'
}
}))
expect(summary.metadata?.agentSessionId).toBeUndefined()
})
it('includes piSessionId as the native resume token', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor: 'pi',
piSessionId: 'pi-session-1'
}
}))
expect(summary.metadata?.agentSessionId).toBe('pi-session-1')
})
it.each([
undefined,
'custom',
' PI '
])('does not infer a Pi identity for an unknown flavor: %s', (flavor) => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
flavor,
piSessionId: 'pi-session-1'
}
}))
expect(summary.metadata?.agentSessionId).toBeUndefined()
})
it('includes pending request kinds and background task count', () => {
const summary = toSessionSummary(makeSession({
backgroundTaskCount: 2,
agentState: {
requests: {
req1: { tool: 'ExitPlanMode', arguments: {} }
}
}
}))
expect(summary.pendingRequestKinds).toEqual(['input'])
expect(summary.pendingRequestsCount).toBe(1)
expect(summary.backgroundTaskCount).toBe(2)
expect(summary.futureScheduledMessageCount).toBe(0)
})
it('includes lifecycleState in summary metadata', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
lifecycleState: 'archived'
}
}))
expect(summary.metadata?.lifecycleState).toBe('archived')
})
it('includes hapiMcpUrl in summary metadata when session bridge is live', () => {
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
hapiMcpUrl: 'http://127.0.0.1:42133/'
}
}))
expect(summary.metadata?.hapiMcpUrl).toBe('http://127.0.0.1:42133/')
})
it('includes externalRefs in summary metadata', () => {
const externalRefs = [{
kind: 'github_pr' as const,
repo: 'tiann/hapi',
number: 1160,
url: 'https://github.com/tiann/hapi/pull/1160',
role: 'primary' as const
}]
const summary = toSessionSummary(makeSession({
metadata: {
path: '/proj',
host: 'local',
externalRefs
}
}))
expect(summary.metadata?.externalRefs).toEqual(externalRefs)
})
it('includes structured pendingRequests for hover-tooltip copy', () => {
const summary = toSessionSummary(makeSession({
updatedAt: 5000,
agentState: {
requests: {
req1: { tool: 'Bash', arguments: {}, createdAt: 100 },
req2: { tool: 'AskUserQuestion', arguments: {}, createdAt: 50 },
req3: { tool: 'Edit', arguments: {} }
}
}
}))
expect(summary.pendingRequestsCount).toBe(3)
expect(summary.pendingRequestKinds).toEqual(['permission', 'input'])
expect(summary.pendingRequests).toHaveLength(3)
expect(summary.pendingRequests[0]).toEqual({
id: 'req2',
kind: 'input',
tool: 'AskUserQuestion',
since: 50
})
expect(summary.pendingRequests[1]).toEqual({
id: 'req1',
kind: 'permission',
tool: 'Bash',
since: 100
})
expect(summary.pendingRequests[2]).toEqual({
id: 'req3',
kind: 'permission',
tool: 'Edit',
since: 5000
})
})
it('returns empty pendingRequests when agentState has no requests', () => {
const summary = toSessionSummary(makeSession({ agentState: null }))
expect(summary.pendingRequests).toEqual([])
})
})
describe('getPendingRequests', () => {
it('caps the array length while leaving pendingRequestsCount untouched', () => {
const requests: Record<string, { tool: string; arguments: unknown; createdAt: number }> = {}
for (let i = 0; i < PENDING_REQUEST_SUMMARY_CAP + 3; i += 1) {
requests[`req-${i.toString().padStart(2, '0')}`] = {
tool: 'Bash',
arguments: {},
createdAt: i
}
}
const session = makeSession({ agentState: { requests } })
const slice = getPendingRequests(session)
expect(slice).toHaveLength(PENDING_REQUEST_SUMMARY_CAP)
// Oldest-first → the first `cap` items by createdAt should win.
expect(slice.map(r => r.id)).toEqual(
Array.from({ length: PENDING_REQUEST_SUMMARY_CAP }, (_, i) => `req-${i.toString().padStart(2, '0')}`)
)
const summary = toSessionSummary(session)
expect(summary.pendingRequestsCount).toBe(PENDING_REQUEST_SUMMARY_CAP + 3)
expect(summary.pendingRequests).toHaveLength(PENDING_REQUEST_SUMMARY_CAP)
})
it('breaks ties on createdAt by id (stable across hub restarts)', () => {
const session = makeSession({
agentState: {
requests: {
'req-b': { tool: 'Bash', arguments: {}, createdAt: 100 },
'req-a': { tool: 'Edit', arguments: {}, createdAt: 100 }
}
}
})
const slice = getPendingRequests(session)
expect(slice.map(r => r.id)).toEqual(['req-a', 'req-b'])
})
})
describe('getPendingRequestKinds', () => {
it('reads from the FULL request set (not the capped pendingRequests slice)', () => {
const requests: Record<string, { tool: string; arguments: unknown; createdAt: number }> = {}
// First CAP requests are all permission, last one is input — must still
// surface 'input' even though it would fall outside the capped slice.
for (let i = 0; i < PENDING_REQUEST_SUMMARY_CAP; i += 1) {
requests[`perm-${i}`] = { tool: 'Bash', arguments: {}, createdAt: i }
}
requests['ask'] = {
tool: 'AskUserQuestion',
arguments: {},
createdAt: PENDING_REQUEST_SUMMARY_CAP + 100
}
const kinds = getPendingRequestKinds(makeSession({ agentState: { requests } }))
expect(kinds).toEqual(['permission', 'input'])
})
})
// The SSE patch path (useSSE.ts patchSessionSummary) calls these directly
// against the patch payload — no full Session needed — to keep the session
// list summary consistent with structured todos/teamState/metadata/agentState
// patches landing for the second half of #884.
describe('summary derivation helpers', () => {
it('computeTodoProgress returns null for empty / undefined todos', () => {
expect(computeTodoProgress(undefined)).toBeNull()
expect(computeTodoProgress([])).toBeNull()
})
it('computeTodoProgress counts completed vs total', () => {
const progress = computeTodoProgress([
{ content: 'a', status: 'pending', priority: 'medium', id: '1' },
{ content: 'b', status: 'completed', priority: 'medium', id: '2' },
{ content: 'c', status: 'completed', priority: 'medium', id: '3' }
])
expect(progress).toEqual({ completed: 2, total: 3 })
})
it('computePendingRequestKinds works on a bare AgentState without a Session', () => {
const kinds = computePendingRequestKinds({
requests: {
req1: { tool: 'Bash', arguments: {} },
req2: { tool: 'AskUserQuestion', arguments: {} }
}
})
expect(kinds).toEqual(['permission', 'input'])
})
it('computePendingRequestsCount handles null agentState', () => {
expect(computePendingRequestsCount(null)).toBe(0)
expect(computePendingRequestsCount(undefined)).toBe(0)
})
it('includes attachedJob when provided via extras', () => {
const job = {
key: 'beets',
label: 'beets import',
status: 'running' as const,
remaining: 120,
unit: 'tracks',
heartbeatAt: 9_000,
startedAt: 1_000,
updatedAt: 9_000
}
const summary = toSessionSummary(makeSession(), { attachedJob: job })
expect(summary.attachedJob).toEqual(job)
expect(summary.attachedJobUpdatedAt).toBe(job.updatedAt)
})
it('defaults attachedJob to null', () => {
expect(toSessionSummary(makeSession()).attachedJob).toBeNull()
expect(toSessionSummary(makeSession()).attachedJobUpdatedAt).toBe(0)
})
it('toSessionSummaryMetadata returns null for null metadata', () => {
expect(toSessionSummaryMetadata(null)).toBeNull()
expect(toSessionSummaryMetadata(undefined)).toBeNull()
})
it('toSessionSummaryMetadata derives agentSessionId from the first non-null source id', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
host: 'h',
cursorSessionId: 'cursor-xyz'
})
expect(summary?.agentSessionId).toBe('cursor-xyz')
})
it('toSessionSummaryMetadata omits lastModelError.lastUserMessage', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
host: 'h',
lastModelError: {
eventId: 'evt-1',
kind: 'transport_closed',
transient: true,
rawSnippet: 'WritableIterable is closed',
atTs: 1,
priorAssistantClaimsDone: false,
lastUserMessage: 'secret prompt text that must not leak into list payloads'
}
})
expect(summary?.lastModelError?.eventId).toBe('evt-1')
expect(summary?.lastModelError).not.toHaveProperty('lastUserMessage')
})
it('carries current-fork capability into list summaries', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
host: 'h',
flavor: 'codex',
capabilities: { conversationHistory: { forkCurrent: true, forkAtMessage: true } }
})
expect(summary?.conversationHistory).toEqual({ forkCurrent: true, forkAtMessage: true })
})
})