mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-03 06:47:03 +00:00
feat: rich composer session @-mentions + inspect_peer (#1228)
* feat(web): feature-flagged rich composer for inline session @ mentions Custom segmented contenteditable (not TipTap) inserts caret-local session atoms from the existing @ picker and serializes to markdown links on send. Textarea path remains default until flag parity dogfood. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): rich composer mention boundary + #1215 refs Treat U+FFFC mirror atoms as word boundaries so @ after a session token still opens autocomplete. Point comments at Fixes #1215. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): peer-stack e2e for rich composer session @ mentions (#1215) Smoke: flag on, @ picker inserts inline session atom chip (not prose dump). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): preserve newlines in rich composer Enter-newline mode Chromium splits contenteditable on Enter into block divs; serialize those as \\n and insert <br> when parent leaves Enter unhandled (Shift+Enter / enter-inserts-newline). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): show @ badge when rich composer mentions flag is on Dogfood was invisible: flag-off looks like a normal textarea, and flag-on had no chrome. Surface a small @ badge when enabled. * fix(web): rich session composer on by default (not a user setting) The plan dual-path was an engineering kill-switch, not an opt-in. Default to the segmented composer; only richMentions=0 disables. Drop the flag badge and record a peer-stack motion proof covering chips + baseline UX. * fix(web): make rich composer Shift+Enter create a visible newline Trailing <br>+empty text node was a silent no-op at EOL. Use insertLineBreak (ZWSP pad fallback), assert real \\n in peer e2e. * feat(web): hover tooltips on rich composer session chips Show full title, status, short id, and path on chip hover via a portal bubble fed by live useSessions lookup (drafts fall back to title + id). * fix(web): dismiss rich composer chip tooltips on mouse leave contenteditable pointerout/relatedTarget was flaky so tips stuck after leaving the chip. Hit-test on pointermove, clear on prose/input/leave. * fix(web): address cold-review Blocker/Majors on rich composer Exclude peer e2e from default Playwright; force plain-text paste; restore newline hard-stop in findActiveWord; fix root-anchored selection mapping and nested-block serialize; cover with unit tests. * chore: drop accidental .cursor files from rich-composer tip * fix(web): close remaining cold-review gaps on rich composer Drop absolute peer e2e tooling imports, prove chip→markdown send, and harden paste/EOL/focus/tooltip/Enter edges before Meta rematerialize. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: absorb soup playwright.config union for clean remat Keep fork peer-stack timeouts/annotated-video wiring and add testIgnore for e2e/peer so the next driver rematerialize does not conflict. Co-authored-by: Cursor <cursoragent@cursor.com> * revert: drop fork playwright tooling from upstreamable tip Peer-stack annotated-video + HAPI_PEER wiring stay on fork main / soup. Product tip only needs testIgnore for e2e/peer (see docs/tooling/peer-stack.md). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): fix rich composer Shift+Enter double newline and paste space Prefer manual newline+pad over execCommand insertLineBreak, and stop applying autocomplete trailing-space on paste/drop paths. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): pad EOL Shift+Enter after Range.insertNode split insertNode always leaves an empty text sibling, so !nextSibling never saw EOL; detect meaningful trailing content and cover with jsdom tests. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop custom onDrop from rich composer Intercepting drop without caretRangeFromPoint landed text at EOF or no-oped in-editor moves. Native CE drop is enough for #1215; paste still forces plain text. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): sidebar-parity tooltips on rich composer session chips Reuse SessionRowSummary (flavor, thinking/attention, schedule, todos, relative ago, path) for chip hover so the tip matches the session list. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: keep peer-stack e2e off the upstreamable tip Peer specs and playwright.peer.config stay on fork main per docs/tooling/peer-stack.md; default config still testIgnore's e2e/peer. Co-authored-by: Cursor <cursoragent@cursor.com> * feat: cite sessions with UUID wire + inspect_peer for agent/overseer Rich composer chips already serialize to [title](/sessions/<id>); flush before send so the agent prompt never gets title-only chip text. Add inspect_peer (MCP + hapi inspect-peer) as the read twin of ping_peer so that same id is immediately usable for overseer/agent peer lookup, with system-prompt glue from citations to inspect/ping. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): gate inspect_peer behind permission approval Cross-session history reads need the same prompt path as ping_peer: keep inspect_peer off Claude --allowedTools and treat it as sensitive in ACP/OpenCode read-only mode so prompt injection cannot silently enumerate peer transcripts. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: clarify playwright peer testIgnore is upstream-safe Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): keep session UUIDs on rich composer copy/cut/paste Copy/cut write wire markdown so chips do not collapse to @title-only clipboard text; paste reparses session links back into atoms. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
/**
|
||||
* Resume-if-inactive + wait-active + POST /api/sessions/:id/messages.
|
||||
* Resume-if-inactive + wait-active + POST /api/sessions/:id/messages,
|
||||
* plus read-only inspectPeer (GET session + messages, never resume).
|
||||
*
|
||||
* Shared by `hapi ping-peer` and MCP `ping_peer`. Uses the same hub JWT flow
|
||||
* as the web app (`POST /api/auth` with CLI_API_TOKEN), scoped to the token's
|
||||
* namespace. Callers must not invent parallel auth or arbitrary hosts.
|
||||
* Shared by `hapi ping-peer` / `hapi inspect-peer` and MCP `ping_peer` /
|
||||
* `inspect_peer`. Uses the same hub JWT flow as the web app
|
||||
* (`POST /api/auth` with CLI_API_TOKEN), scoped to the token's namespace.
|
||||
* Callers must not invent parallel auth or arbitrary hosts.
|
||||
*/
|
||||
|
||||
import axios, { type AxiosInstance } from 'axios'
|
||||
import { extractAssistantPlainText, isObject } from '@hapi/protocol'
|
||||
import { configuration } from '@/configuration'
|
||||
import { getAuthToken } from '@/api/auth'
|
||||
import { buildHubRequestHeaders } from '@/api/hubExtraHeaders'
|
||||
@@ -33,10 +36,13 @@ export class PingPeerError extends Error {
|
||||
export type PingPeerSessionSummary = {
|
||||
id: string
|
||||
active: boolean
|
||||
thinking?: boolean
|
||||
updatedAt?: number
|
||||
metadata?: {
|
||||
name?: string
|
||||
flavor?: string | null
|
||||
path?: string | null
|
||||
lifecycleState?: string | null
|
||||
piSessionId?: string
|
||||
} | null
|
||||
}
|
||||
@@ -422,3 +428,181 @@ export function exitCodeForPingPeerError(error: PingPeerError): number {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
// ── inspect_peer (read twin; no resume) ─────────────────────────────────────
|
||||
|
||||
export type InspectPeerOptions = {
|
||||
sessionIdPrefix: string
|
||||
/** Recent message page size (default 30, clamped 1..100). */
|
||||
messageLimit?: number
|
||||
apiUrl?: string
|
||||
accessToken?: string
|
||||
http?: AxiosInstance
|
||||
}
|
||||
|
||||
export type InspectPeerMessage = {
|
||||
id: string
|
||||
role: string
|
||||
text: string
|
||||
createdAt: number | null
|
||||
}
|
||||
|
||||
export type InspectPeerResult = {
|
||||
sessionId: string
|
||||
name: string
|
||||
active: boolean
|
||||
thinking: boolean
|
||||
flavor: string | null
|
||||
path: string | null
|
||||
lifecycleState: string | null
|
||||
updatedAt: number | null
|
||||
messages: InspectPeerMessage[]
|
||||
}
|
||||
|
||||
const DEFAULT_INSPECT_MESSAGE_LIMIT = 30
|
||||
const MAX_INSPECT_MESSAGE_LIMIT = 100
|
||||
const MAX_SNIPPET_CHARS = 1_200
|
||||
|
||||
function clampInspectMessageLimit(raw: number | undefined): number {
|
||||
const n = raw ?? DEFAULT_INSPECT_MESSAGE_LIMIT
|
||||
if (!Number.isFinite(n)) {
|
||||
throw new PingPeerError('bad_args', 'messageLimit must be a number')
|
||||
}
|
||||
return Math.min(MAX_INSPECT_MESSAGE_LIMIT, Math.max(1, Math.floor(n)))
|
||||
}
|
||||
|
||||
function extractUserPlainText(inner: unknown): string | null {
|
||||
if (typeof inner === 'string' && inner.trim()) return inner
|
||||
if (!isObject(inner)) return null
|
||||
if (typeof inner.text === 'string' && inner.text.trim()) return inner.text
|
||||
if (isObject(inner.content) && typeof inner.content.text === 'string' && inner.content.text.trim()) {
|
||||
return inner.content.text
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Best-effort text from a hub message row; skip tool-call / empty noise. */
|
||||
export function extractInspectMessageSnippet(content: unknown): InspectPeerMessage | null {
|
||||
if (!isObject(content)) return null
|
||||
const role = typeof content.role === 'string' ? content.role : 'unknown'
|
||||
const inner = content.content
|
||||
let text: string | null = null
|
||||
if (role === 'user') {
|
||||
text = extractUserPlainText(inner)
|
||||
} else {
|
||||
text = extractAssistantPlainText(inner)
|
||||
if (!text) text = extractUserPlainText(inner)
|
||||
}
|
||||
if (!text) return null
|
||||
const trimmed = text.replace(/\s+/g, ' ').trim()
|
||||
if (!trimmed) return null
|
||||
const snippet = trimmed.length > MAX_SNIPPET_CHARS
|
||||
? `${trimmed.slice(0, MAX_SNIPPET_CHARS)}…`
|
||||
: trimmed
|
||||
return {
|
||||
id: typeof content.id === 'string' ? content.id : '',
|
||||
role,
|
||||
text: snippet,
|
||||
createdAt: null
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSessionMessages(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
sessionId: string,
|
||||
limit: number,
|
||||
http: AxiosInstance
|
||||
): Promise<InspectPeerMessage[]> {
|
||||
const response = await http.get(
|
||||
`${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages`,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
params: { limit },
|
||||
timeout: 20_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
const detail = typeof response.data?.error === 'string'
|
||||
? response.data.error
|
||||
: `HTTP ${response.status}`
|
||||
throw new PingPeerError('not_found', `failed to load messages for ${sessionId} (${detail})`)
|
||||
}
|
||||
const rows = Array.isArray(response.data?.messages) ? response.data.messages : []
|
||||
const out: InspectPeerMessage[] = []
|
||||
for (const row of rows) {
|
||||
if (!isObject(row)) continue
|
||||
const snippet = extractInspectMessageSnippet(row.content)
|
||||
if (!snippet) continue
|
||||
out.push({
|
||||
...snippet,
|
||||
id: typeof row.id === 'string' ? row.id : snippet.id,
|
||||
createdAt: typeof row.createdAt === 'number' ? row.createdAt : null
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a peer by id/prefix and return metadata + recent text messages.
|
||||
* Read-only: never resumes inactive sessions (unlike `pingPeer`).
|
||||
*/
|
||||
export async function inspectPeer(options: InspectPeerOptions): Promise<InspectPeerResult> {
|
||||
const prefix = options.sessionIdPrefix?.trim() ?? ''
|
||||
if (!prefix) {
|
||||
throw new PingPeerError('bad_args', 'session id prefix is required')
|
||||
}
|
||||
const messageLimit = clampInspectMessageLimit(options.messageLimit)
|
||||
|
||||
const apiUrl = resolveApiUrl(options.apiUrl)
|
||||
const accessToken = resolveAccessToken(options.accessToken)
|
||||
const http = options.http ?? axios
|
||||
|
||||
const jwt = await exchangeJwt(apiUrl, accessToken, http)
|
||||
const sessions = await listSessions(apiUrl, jwt, http)
|
||||
const matched = resolveSessionByPrefix(sessions, prefix)
|
||||
const live = await getSession(apiUrl, jwt, matched.id, http)
|
||||
const meta = live.metadata ?? matched.metadata ?? null
|
||||
const messages = await fetchSessionMessages(apiUrl, jwt, matched.id, messageLimit, http)
|
||||
|
||||
return {
|
||||
sessionId: matched.id,
|
||||
name: meta?.name ?? '(unnamed)',
|
||||
active: live.active,
|
||||
thinking: Boolean(live.thinking),
|
||||
flavor: typeof meta?.flavor === 'string' ? meta.flavor : null,
|
||||
path: typeof meta?.path === 'string' ? meta.path : null,
|
||||
lifecycleState: typeof meta?.lifecycleState === 'string' ? meta.lifecycleState : null,
|
||||
updatedAt: typeof live.updatedAt === 'number'
|
||||
? live.updatedAt
|
||||
: typeof matched.updatedAt === 'number'
|
||||
? matched.updatedAt
|
||||
: null,
|
||||
messages
|
||||
}
|
||||
}
|
||||
|
||||
/** Human/agent-readable report for MCP tool results and CLI stdout. */
|
||||
export function formatInspectPeerReport(result: InspectPeerResult): string {
|
||||
const lines: string[] = [
|
||||
`sessionId: ${result.sessionId}`,
|
||||
`path: /sessions/${result.sessionId}`,
|
||||
`name: ${result.name}`,
|
||||
`flavor: ${result.flavor ?? '(unknown)'}`,
|
||||
`active: ${result.active}`,
|
||||
`thinking: ${result.thinking}`,
|
||||
`lifecycle: ${result.lifecycleState ?? '(none)'}`,
|
||||
`cwd: ${result.path ?? '(unknown)'}`,
|
||||
`updatedAt: ${result.updatedAt ?? '(unknown)'}`,
|
||||
`messages (text snippets, newest page): ${result.messages.length}`
|
||||
]
|
||||
if (result.messages.length === 0) {
|
||||
lines.push('(no extractable user/assistant text in this page)')
|
||||
} else {
|
||||
for (const message of result.messages) {
|
||||
lines.push(`[${message.role}] ${message.text}`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user