Files
hapi/shared/src/sessionCitation.test.ts
T
Junmo KimandGitHub 5ce30b20c9 feat(cli): auto-steer ping-peer messages into active peer turns (#2298)
* refactor(shared): describe steering support with a per-flavor capability table

Replace the flavor comparison chains in isSteeringSupportedForFlavor and
isSteeringSupportedForSession with a table keyed by flavor, so a protocol
restriction such as legacy Cursor sessions sits next to the flavor it applies
to. Results are unchanged for every flavor and Cursor session shape.

* feat(cli): auto-steer ping-peer messages into active peer turns

Peer messages in auto mode only steered Codex turns. Record each flavor's
active-turn signal in the steering capability table, expose it as
hasActiveSteeringTurn(), and use it in both the peer sender and the waiting
queue's Steer gate, so remote Claude, Pi, OpenCode and Cursor ACP targets with
an active, steerable turn also get the queued message steered into it.

Auto still stores one ordinary queued message first and attempts the existing
steer action at most once. A steer that the hub rejects or that stays
unconfirmed keeps the accepted message without resending, and the receipt now
says which of "not attempted", "rejected by hub" or "not confirmed" applied.
Inactive targets, --wake, explicit steer and explicit queue are unchanged.

* fix(cli): keep ping-peer steer notes accurate when delivery is unresolved

Auto receipts reported every unsuccessful steer response as "rejected by hub"
and promised the message stays queued. Only a refusal before any native steer
is dispatched (an HTTP 4xx, or a Hub failure without a localId) is definitive.
A failure that carries a localId, such as an RPC timeout or an OpenCode steer
that is still being reconciled, now reads "steer not confirmed; delivery
unresolved" without promising queued delivery.

Auto notes for a skipped steer used the explicit-steer refusal text, so an
accepted receipt could say "no message sent". They now use separate reasons
(for example "target is idle"); explicit steer wording is unchanged.
2026-11-07 08:13:48 +08:00

187 lines
8.4 KiB
TypeScript

import { describe, expect, it } from 'bun:test'
import {
SESSION_REFERENCE_STEER_SUFFIX,
SPAWN_PEER_TOOL_DESCRIPTION,
PEER_DELIVERY_MODE_DESCRIPTION,
PING_PEER_TOOL_DESCRIPTION,
buildSessionCitationSteerInstruction,
extractSessionCitationIds,
normalizeSessionIdPrefix,
} from './sessionCitation'
const UUID = '7ee03698-0fe7-4f76-b8a8-d84f4eddbf5c'
describe('extractSessionCitationIds', () => {
it('extracts id from Copy-reference prose (tiann/hapi#1144)', () => {
const text = `See session "Coding" (/sessions/${UUID}) for context`
expect(extractSessionCitationIds(text)).toEqual([UUID])
})
it('extracts id from Copy-reference prose with steer suffix', () => {
const text =
`See session "Coding" (/sessions/${UUID}) for context.${SESSION_REFERENCE_STEER_SUFFIX}`
expect(extractSessionCitationIds(text)).toEqual([UUID])
})
it('extracts id from empty-title Copy-reference form', () => {
expect(extractSessionCitationIds(`See HAPI session /sessions/${UUID} for context`)).toEqual([
UUID,
])
})
it('extracts id from markdown composer chip form', () => {
expect(extractSessionCitationIds(`[Coding](/sessions/${UUID})`)).toEqual([UUID])
})
it('extracts id from bare /sessions/<id>', () => {
expect(extractSessionCitationIds(`please read /sessions/${UUID}`)).toEqual([UUID])
})
it('strips trailing prose punctuation from bare citations', () => {
expect(extractSessionCitationIds(`see /sessions/${UUID}.`)).toEqual([UUID])
expect(extractSessionCitationIds(`see /sessions/${UUID}, then continue`)).toEqual([UUID])
})
it('rejects dotted tails that look like source paths', () => {
expect(extractSessionCitationIds('see web/src/routes/sessions/chat.tsx')).toEqual([])
expect(extractSessionCitationIds('/sessions/chat.tsx')).toEqual([])
})
it('dedupes while preserving first-seen order', () => {
const other = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
const text = `[A](/sessions/${UUID}) and See session "B" (/sessions/${other}) then /sessions/${UUID}`
expect(extractSessionCitationIds(text)).toEqual([UUID, other])
})
it('accepts BASE_URL-prefixed session paths', () => {
expect(extractSessionCitationIds(`(/hapi/sessions/${UUID})`)).toEqual([UUID])
})
})
describe('normalizeSessionIdPrefix', () => {
it('returns a bare prefix unchanged', () => {
expect(normalizeSessionIdPrefix('7ee03698')).toBe('7ee03698')
expect(normalizeSessionIdPrefix(` ${UUID} `)).toBe(UUID)
})
it('pulls the id out of a pasted Copy-reference blob', () => {
expect(
normalizeSessionIdPrefix(`See session "Coding" (/sessions/${UUID}) for context`)
).toBe(UUID)
})
it('prefers the parenthesized Copy-reference path over /sessions/ inside the title', () => {
const other = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
const text =
`See session ${JSON.stringify(`Review /sessions/${other}`)} (/sessions/${UUID}) for context.${SESSION_REFERENCE_STEER_SUFFIX}`
expect(normalizeSessionIdPrefix(text)).toBe(UUID)
})
it('pulls the id out of a markdown citation', () => {
expect(normalizeSessionIdPrefix(`[Coding](/sessions/${UUID})`)).toBe(UUID)
})
it('fails closed on ambiguous multi-citation blobs', () => {
const other = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
expect(
normalizeSessionIdPrefix(
`[A](/sessions/${UUID}) and See session "B" (/sessions/${other}) for context`
)
).toBe('')
})
it('fails closed when a Copy-reference is followed by a second citation', () => {
const other = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
expect(
normalizeSessionIdPrefix(
`See session "A" (/sessions/${UUID}) for context and [B](/sessions/${other})`
)
).toBe('')
})
})
describe('buildSessionCitationSteerInstruction', () => {
it('guides collaboration toward auto and preserves explicit modes and retry safety', () => {
const text = buildSessionCitationSteerInstruction({ inspectTool: 'inspect_peer', pingTool: 'ping_peer' })
expect(text).toContain(PEER_DELIVERY_MODE_DESCRIPTION)
expect(PING_PEER_TOOL_DESCRIPTION).toContain(PEER_DELIVERY_MODE_DESCRIPTION)
expect(text).toContain('auto (default)')
expect(text).toContain('active turn when the target supports steering and is ready')
expect(text).toContain('auto retains the same single accepted message without resending')
expect(text).not.toContain('Auto currently queues for other agent flavors')
expect(text).toContain('Prefer auto for routine collaboration when queueing is an acceptable fallback')
expect(text).toContain('queue: explicitly defer non-urgent updates')
expect(text).toContain('steer: use for important, time-sensitive findings the peer needs to know now')
expect(text).toContain('not after finishing its current turn')
expect(text).toContain('State why the finding matters now and what the peer should adjust')
expect(text).toContain('Steer requires insertion')
expect(text).toContain('does not abort the current turn or guarantee an immediate response')
expect(text).toContain('do not resend automatically')
expect(text).toContain('hapi ping-peer <id> <message> --delivery-mode auto')
})
it('mentions both citation forms and forbids local FS search', () => {
const text = buildSessionCitationSteerInstruction({
inspectTool: 'mcp__hapi__inspect_peer',
pingTool: 'mcp__hapi__ping_peer',
listPeersTool: 'mcp__hapi__list_peers',
})
expect(text).toContain('[title](/sessions/<id>)')
expect(text).toContain('See session')
expect(text).toContain('/sessions/<id>')
expect(text).toContain('mcp__hapi__inspect_peer')
expect(text).toContain('mcp__hapi__ping_peer')
expect(text).toContain('mcp__hapi__list_peers')
expect(text.toLowerCase()).toMatch(/not.*(grep|glob|filesystem|local file)/i)
})
it('teaches spawn_peer for new peers with work and forbids stuffing remit into machine spawn', () => {
const text = buildSessionCitationSteerInstruction({
inspectTool: 'mcp__hapi__inspect_peer',
pingTool: 'mcp__hapi__ping_peer',
listPeersTool: 'mcp__hapi__list_peers',
spawnTool: 'mcp__hapi__spawn_peer',
})
expect(text).toContain('mcp__hapi__spawn_peer')
expect(text).toMatch(/spawn-peer|spawn_peer/)
expect(text.toLowerCase()).toMatch(/400|reject/)
expect(text.toLowerCase()).not.toMatch(/strip/)
})
})
describe('SPAWN_PEER_TOOL_DESCRIPTION', () => {
it('tells agents the hub rejects a spawn-body remit instead of stripping it', () => {
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/reject/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).not.toMatch(/strip/)
})
it('teaches omit permissionMode = yolo default, not approval-gated default', () => {
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/yolo/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/omit/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).not.toMatch(
/pass permissionmode only when the operator asked/
)
})
it('forbids inventing peer titles and teaches Parent UUID stamp', () => {
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/never invent/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/parent/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/uuid/)
})
it('documents optional machine targeting beyond this host only', () => {
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/machine/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/hostname|uuid/)
expect(SPAWN_PEER_TOOL_DESCRIPTION.toLowerCase()).not.toMatch(
/spawn a new hapi session on this machine and/
)
})
})
describe('PING_PEER_TOOL_DESCRIPTION identity rule', () => {
it('forbids inventing peer titles', async () => {
const { PING_PEER_TOOL_DESCRIPTION } = await import('./sessionCitation')
expect(PING_PEER_TOOL_DESCRIPTION.toLowerCase()).toMatch(/never invent/)
})
})