From c411eae365e6791c10b0f04f78e670b9cc0201aa Mon Sep 17 00:00:00 2001 From: Ben Davis Date: Wed, 6 May 2026 22:20:43 -0700 Subject: [PATCH] Surface Pi extension runtime state - Add Pi UI state and diagnostic events with JSON-safe payloads - Expose Pi extension resources in provider snapshots and UI panels --- .../Layers/ProviderRuntimeIngestion.ts | 52 ++ apps/server/src/provider/Drivers/PiDriver.ts | 5 +- apps/server/src/provider/Layers/PiAdapter.ts | 117 ++-- apps/server/src/provider/Layers/PiProvider.ts | 202 +++++- .../provider/pi/PiExtensionUiBridge.test.ts | 69 ++ .../src/provider/pi/PiExtensionUiBridge.ts | 433 +++++++++++- apps/server/src/provider/pi/jsonSafe.test.ts | 35 + apps/server/src/provider/pi/jsonSafe.ts | 46 ++ apps/server/src/provider/providerSnapshot.ts | 2 + .../src/provider/providerStatusCache.ts | 1 + apps/web/src/components/chat/ChatComposer.tsx | 199 +++++- .../components/chat/ModelPickerContent.tsx | 16 + .../components/chat/PiRuntimePanel.test.ts | 160 +++++ .../src/components/chat/PiRuntimePanel.tsx | 616 ++++++++++++++++++ .../chat/ProviderModelPicker.browser.tsx | 52 +- apps/web/src/session-logic.test.ts | 40 ++ apps/web/src/session-logic.ts | 20 + docs/providers/pi.md | 85 ++- .../contracts/src/providerRuntime.test.ts | 120 ++++ packages/contracts/src/providerRuntime.ts | 109 +++- packages/contracts/src/server.test.ts | 65 ++ packages/contracts/src/server.ts | 15 + 22 files changed, 2307 insertions(+), 152 deletions(-) create mode 100644 apps/server/src/provider/pi/PiExtensionUiBridge.test.ts create mode 100644 apps/server/src/provider/pi/jsonSafe.test.ts create mode 100644 apps/server/src/provider/pi/jsonSafe.ts create mode 100644 apps/web/src/components/chat/PiRuntimePanel.test.ts create mode 100644 apps/web/src/components/chat/PiRuntimePanel.tsx diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index b0533052c5..2253399f49 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -358,6 +358,13 @@ function runtimeEventToActivities( } case "extension.activity": { + if ( + event.payload.visibility === "pi-panel" || + event.payload.visibility === "debug" || + event.payload.visibility === "hidden" + ) { + return []; + } return [ { id: event.eventId, @@ -372,6 +379,51 @@ function runtimeEventToActivities( ]; } + case "pi.ui.state.updated": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "pi.ui.state.updated", + summary: `Pi ${event.payload.surface} updated`, + payload: event.payload, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "pi.extension.configured": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "info", + kind: "pi.extension.configured", + summary: "Pi extensions configured", + payload: event.payload, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + + case "pi.extension.diagnostic": { + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: event.payload.severity === "error" ? "error" : "info", + kind: "pi.extension.diagnostic", + summary: event.payload.message, + payload: event.payload, + turnId: toTurnId(event.turnId) ?? null, + ...maybeSequence, + }, + ]; + } + case "turn.plan.updated": { return [ { diff --git a/apps/server/src/provider/Drivers/PiDriver.ts b/apps/server/src/provider/Drivers/PiDriver.ts index 9f60c5a99d..43485b5f48 100644 --- a/apps/server/src/provider/Drivers/PiDriver.ts +++ b/apps/server/src/provider/Drivers/PiDriver.ts @@ -61,6 +61,7 @@ export const PiDriver: ProviderDriver = { const adapter = yield* makePiAdapter(effectiveConfig, { instanceId }); const textGeneration = yield* makePiTextGeneration(effectiveConfig); + const serverConfig = yield* ServerConfig; const snapshot = yield* makeManagedServerProvider({ maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ @@ -71,7 +72,9 @@ export const PiDriver: ProviderDriver = { streamSettings: Stream.never, haveSettingsChanged: () => false, initialSnapshot: (settings) => stampIdentity(makePendingPiProvider(settings)), - checkProvider: checkPiProviderStatus(effectiveConfig).pipe(Effect.map(stampIdentity)), + checkProvider: checkPiProviderStatus(effectiveConfig, serverConfig.cwd).pipe( + Effect.map(stampIdentity), + ), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, }).pipe( Effect.mapError( diff --git a/apps/server/src/provider/Layers/PiAdapter.ts b/apps/server/src/provider/Layers/PiAdapter.ts index 091112afee..f3e765ca8b 100644 --- a/apps/server/src/provider/Layers/PiAdapter.ts +++ b/apps/server/src/provider/Layers/PiAdapter.ts @@ -42,7 +42,13 @@ import { import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; import { parsePiSlashCommand, PI_BUILT_IN_SLASH_COMMANDS } from "../pi/PiSlashCommands.ts"; import { makePiExtensionUiBridge, type PiExtensionUiBridge } from "../pi/PiExtensionUiBridge.ts"; -import { resolvePiAgentDir, resolvePiSessionDir } from "./PiProvider.ts"; +import { toPiJsonValue } from "../pi/jsonSafe.ts"; +import { + getPiExtensionInventoryFromRunner, + piModelToServerModel, + resolvePiAgentDir, + resolvePiSessionDir, +} from "./PiProvider.ts"; const PROVIDER = ProviderDriverKind.make("pi"); const PI_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const; @@ -648,34 +654,44 @@ async function publishPiRuntimeWarning(input: { readonly message: string; readonly detail?: unknown; }) { + const detail = toPiJsonValue(input.detail); await input.publishRuntimeEvent({ ...makeContextEventBase(input.context, input.turnId), type: "runtime.warning", payload: { message: input.message, - ...(input.detail !== undefined ? { detail: input.detail } : {}), + ...(detail !== undefined ? { detail } : {}), }, }); } -async function publishPiExtensionActivity(input: { +async function publishPiExtensionDiagnostic(input: { readonly context: PiSessionContext; readonly publishRuntimeEvent: PiRuntimeEventPublisher; readonly message: string; readonly severity?: "info" | "warning" | "error"; + readonly event?: string; + readonly diagnosticKey?: string; + readonly repeatCount?: number; + readonly hiddenCount?: number; readonly detail?: unknown; readonly extensionPath?: string; }) { + const detail = toPiJsonValue(input.detail); await input.publishRuntimeEvent({ ...makeContextEventBase(input.context, input.context.activeTurnId), - type: "extension.activity", + type: "pi.extension.diagnostic", payload: { - source: "pi.extension.ui", - activityType: input.severity === "error" ? "error" : "notify", + source: "pi.extension", message: input.message, - ...(input.severity ? { severity: input.severity } : {}), + severity: input.severity ?? "warning", + visibility: "pi-panel", ...(input.extensionPath ? { extensionPath: input.extensionPath } : {}), - ...(input.detail !== undefined ? { data: input.detail } : {}), + ...(input.event ? { event: input.event } : {}), + ...(input.diagnosticKey ? { diagnosticKey: input.diagnosticKey } : {}), + ...(input.repeatCount ? { repeatCount: input.repeatCount } : {}), + ...(input.hiddenCount !== undefined ? { hiddenCount: input.hiddenCount } : {}), + ...(detail !== undefined ? { detail } : {}), uiOnly: true, }, }); @@ -688,40 +704,25 @@ function extensionErrorMessage(error: ExtensionError): string { return `${source}${event ? ` failed during ${event}` : " failed"}${detail ? `: ${detail}` : "."}`; } -function getPiExtensionConfigSnapshot(session: AgentSession) { - const runner = session.extensionRunner; - if (!runner) { - return { - extensionPaths: [], - slashCommands: [], - tools: [], - flags: [], - }; - } +function extensionDiagnosticKey(error: ExtensionError): string { + return [ + error.extensionPath.trim() || "Pi extension", + error.event.trim(), + error.error.trim(), + ].join(" :: "); +} + +function shouldPublishExtensionDiagnostic(count: number): boolean { + return count === 1 || count === 2 || count === 5 || count === 10 || count % 100 === 0; +} + +function getPiExtensionConfigSnapshot(context: PiSessionContext) { + const runner = context.session.extensionRunner; + const models = context.modelRegistry.getAvailable().map(piModelToServerModel); + const inventory = getPiExtensionInventoryFromRunner(runner); return { - extensionPaths: runner.getExtensionPaths(), - slashCommands: runner.getRegisteredCommands().map((command) => { - const commandRecord = Object(command) as Record; - const input = - commandRecord.input && typeof commandRecord.input === "object" - ? (commandRecord.input as { readonly hint?: unknown }) - : undefined; - const snapshot = { - name: command.name, - description: command.description, - source: "extension", - sourceInfo: command.sourceInfo, - }; - return typeof input?.hint === "string" - ? Object.assign(snapshot, { input: { hint: input.hint } }) - : snapshot; - }), - tools: runner.getAllRegisteredTools().map((tool) => ({ - name: tool.definition.name, - description: tool.definition.description, - sourceInfo: tool.sourceInfo, - })), - flags: [...runner.getFlags().keys()], + ...inventory, + models, }; } @@ -729,13 +730,18 @@ async function publishPiExtensionConfig(input: { readonly context: PiSessionContext; readonly publishRuntimeEvent: PiRuntimeEventPublisher; }) { + const config = getPiExtensionConfigSnapshot(input.context); + const models = toPiJsonValue(config.models); await input.publishRuntimeEvent({ ...makeContextEventBase(input.context, input.context.activeTurnId), - type: "session.configured", + type: "pi.extension.configured", payload: { - config: { - piExtensions: getPiExtensionConfigSnapshot(input.context.session), - }, + source: "pi.extension", + extensionPaths: config.extensionPaths, + slashCommands: config.slashCommands, + tools: config.tools, + flags: config.flags, + ...(Array.isArray(models) ? { models } : {}), }, }); } @@ -745,6 +751,7 @@ async function bindPiExtensions(input: { readonly publishRuntimeEvent: PiRuntimeEventPublisher; readonly uiContext: ExtensionUIContext; }) { + const diagnosticCounts = new Map(); const commandContextActions: ExtensionCommandContextActions = { waitForIdle: () => input.context.session.agent.waitForIdle(), newSession: async () => { @@ -782,7 +789,13 @@ async function bindPiExtensions(input: { }); return { cancelled: true }; }, - reload: () => input.context.session.reload(), + reload: async () => { + await input.context.session.reload(); + await publishPiExtensionConfig({ + context: input.context, + publishRuntimeEvent: input.publishRuntimeEvent, + }); + }, }; await input.context.session.bindExtensions({ @@ -797,12 +810,22 @@ async function bindPiExtensions(input: { }); }, onError: (error) => { - void publishPiExtensionActivity({ + const diagnosticKey = extensionDiagnosticKey(error); + const repeatCount = (diagnosticCounts.get(diagnosticKey) ?? 0) + 1; + diagnosticCounts.set(diagnosticKey, repeatCount); + if (!shouldPublishExtensionDiagnostic(repeatCount)) { + return; + } + void publishPiExtensionDiagnostic({ context: input.context, publishRuntimeEvent: input.publishRuntimeEvent, message: extensionErrorMessage(error), severity: "error", extensionPath: error.extensionPath, + event: error.event, + diagnosticKey, + repeatCount, + hiddenCount: Math.max(0, repeatCount - 1), detail: error, }); }, diff --git a/apps/server/src/provider/Layers/PiProvider.ts b/apps/server/src/provider/Layers/PiProvider.ts index 28c3707862..cec1414dae 100644 --- a/apps/server/src/provider/Layers/PiProvider.ts +++ b/apps/server/src/provider/Layers/PiProvider.ts @@ -1,17 +1,23 @@ import { join } from "node:path"; import { AuthStorage, - loadSkills, + DefaultResourceLoader, + ExtensionRunner, + getAgentDir, ModelRegistry, + SessionManager, VERSION, type Skill, } from "@mariozechner/pi-coding-agent"; import { type ModelCapabilities, + type PiExtensionConfiguredPayload, PiSettings, ProviderDriverKind, + type ServerProvider, type ServerProviderModel, type ServerProviderSkill, + type ServerProviderSlashCommand, } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { Effect } from "effect"; @@ -24,6 +30,7 @@ import { type ServerProviderDraft, } from "../providerSnapshot.ts"; import { PI_BUILT_IN_SLASH_COMMANDS } from "../pi/PiSlashCommands.ts"; +import { toPiJsonValue } from "../pi/jsonSafe.ts"; const DRIVER_KIND = ProviderDriverKind.make("pi"); const PI_PRESENTATION = { @@ -65,6 +72,10 @@ export function resolvePiAgentDir(settings: PiSettings): string | undefined { return configured.length > 0 ? expandHomePath(configured) : undefined; } +function resolveEffectivePiAgentDir(settings: PiSettings): string { + return resolvePiAgentDir(settings) ?? getAgentDir(); +} + export function resolvePiSessionDir(settings: PiSettings): string | undefined { const configured = settings.sessionDir.trim(); return configured.length > 0 ? expandHomePath(configured) : undefined; @@ -119,7 +130,7 @@ function piModelCapabilities(model: PiModel): ModelCapabilities { }); } -function piModelToServerModel(model: PiModel): ServerProviderModel { +export function piModelToServerModel(model: PiModel): ServerProviderModel { const slug = `${model.provider}/${model.id}`; return { slug, @@ -147,19 +158,158 @@ function piSkillToServerSkill(skill: Skill): ServerProviderSkill | undefined { }; } -function getPiSkills(settings: PiSettings): ReadonlyArray { - try { - return loadSkills({ - cwd: process.cwd(), - agentDir: resolvePiAgentDir(settings) ?? "", - skillPaths: [], - includeDefaults: true, - }) - .skills.map(piSkillToServerSkill) - .filter((skill) => skill !== undefined); - } catch { - return []; +type PiResolvedCommand = ReturnType[number]; +type PiRegisteredTool = ReturnType[number]; + +export interface PiExtensionInventory { + readonly extensionPaths: ReadonlyArray; + readonly slashCommands: PiExtensionConfiguredPayload["slashCommands"]; + readonly tools: PiExtensionConfiguredPayload["tools"]; + readonly flags: ReadonlyArray; +} + +interface PiProviderResources { + readonly slashCommands: ReadonlyArray; + readonly skills: ReadonlyArray; + readonly pi: NonNullable; +} + +function optionalTrimmed(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : undefined; +} + +export function piExtensionCommandToSnapshot( + command: PiResolvedCommand, +): PiExtensionInventory["slashCommands"][number] { + const commandRecord = Object(command) as Record; + const input = + commandRecord.input && typeof commandRecord.input === "object" + ? (commandRecord.input as { readonly hint?: unknown }) + : undefined; + const name = + typeof commandRecord.invocationName === "string" ? commandRecord.invocationName : command.name; + const description = optionalTrimmed(command.description); + const sourceInfo = toPiJsonValue(command.sourceInfo); + const snapshot = { + name, + source: "extension", + ...(sourceInfo !== undefined ? { sourceInfo } : {}), + ...(description ? { description } : {}), + }; + return typeof input?.hint === "string" + ? Object.assign(snapshot, { input: { hint: input.hint } }) + : snapshot; +} + +export function piExtensionToolToSnapshot( + tool: PiRegisteredTool, +): PiExtensionInventory["tools"][number] { + const description = optionalTrimmed(tool.definition.description); + const sourceInfo = toPiJsonValue(tool.sourceInfo); + return { + name: tool.definition.name, + ...(description ? { description } : {}), + ...(sourceInfo !== undefined ? { sourceInfo } : {}), + }; +} + +export function getPiExtensionInventoryFromRunner( + runner: ExtensionRunner | undefined, +): PiExtensionInventory { + if (!runner) { + return { + extensionPaths: [], + slashCommands: [], + tools: [], + flags: [], + }; } + + return { + extensionPaths: runner.getExtensionPaths(), + slashCommands: runner.getRegisteredCommands().map(piExtensionCommandToSnapshot), + tools: runner.getAllRegisteredTools().map(piExtensionToolToSnapshot), + flags: [...runner.getFlags().keys()], + }; +} + +function mergePiSlashCommands( + baseCommands: ReadonlyArray, + extensionCommands: ReadonlyArray, +): ReadonlyArray { + const commands = [...baseCommands]; + const seen = new Set(commands.map((command) => command.name)); + for (const command of extensionCommands) { + if (seen.has(command.name)) continue; + commands.push(command); + seen.add(command.name); + } + return commands; +} + +function piSnapshotCommandToServerSlashCommand( + command: PiExtensionInventory["slashCommands"][number], +): ServerProviderSlashCommand { + const description = optionalTrimmed(command.description); + const input = + command.input && typeof command.input === "object" + ? (command.input as { readonly hint?: unknown }) + : undefined; + const hint = typeof input?.hint === "string" ? optionalTrimmed(input.hint) : undefined; + return { + name: command.name, + ...(description ? { description } : {}), + ...(hint ? { input: { hint } } : {}), + }; +} + +async function loadPiProviderResources( + settings: PiSettings, + cwd: string, +): Promise { + const agentDir = resolveEffectivePiAgentDir(settings); + const loader = new DefaultResourceLoader({ + cwd, + agentDir, + }); + await loader.reload(); + + const extensions = loader.getExtensions(); + const runner = new ExtensionRunner( + extensions.extensions, + extensions.runtime, + cwd, + SessionManager.inMemory(cwd), + makePiModelRegistry(settings), + ); + const inventory = getPiExtensionInventoryFromRunner(runner); + const extensionCommands = inventory.slashCommands.map(piSnapshotCommandToServerSlashCommand); + + return { + slashCommands: mergePiSlashCommands(PI_BUILT_IN_SLASH_COMMANDS, extensionCommands), + skills: loader + .getSkills() + .skills.map(piSkillToServerSkill) + .filter((skill) => skill !== undefined), + pi: { + extensionPaths: [...inventory.extensionPaths], + tools: [...inventory.tools], + flags: [...inventory.flags], + }, + }; +} + +function fallbackPiProviderResources(): PiProviderResources { + return { + slashCommands: PI_BUILT_IN_SLASH_COMMANDS, + skills: [], + pi: { + extensionPaths: [], + tools: [], + flags: [], + }, + }; } export function makePendingPiProvider(settings: PiSettings): ServerProviderDraft { @@ -190,14 +340,25 @@ export function makePendingPiProvider(settings: PiSettings): ServerProviderDraft }); } -export const checkPiProviderStatus = (settings: PiSettings) => - Effect.sync(() => { +export const checkPiProviderStatus = (settings: PiSettings, cwd = process.cwd()) => + Effect.promise(async () => { try { const modelRegistry = makePiModelRegistry(settings); const availableModels = modelRegistry.getAvailable(); const authenticated = availableModels.some((model) => modelRegistry.hasConfiguredAuth(model)); const builtInModels = availableModels.map(piModelToServerModel); - const message = authenticated ? undefined : "Pi has no configured authenticated model."; + let resources = fallbackPiProviderResources(); + let resourceMessage: string | undefined; + try { + resources = await loadPiProviderResources(settings, cwd); + } catch (cause) { + resourceMessage = cause instanceof Error ? cause.message : String(cause); + } + const message = authenticated + ? resourceMessage + ? `Failed to read Pi extensions or skills: ${resourceMessage}` + : undefined + : "Pi has no configured authenticated model."; return buildServerProvider({ driver: DRIVER_KIND, @@ -210,12 +371,13 @@ export const checkPiProviderStatus = (settings: PiSettings) => settings.customModels, DEFAULT_PI_MODEL_CAPABILITIES, ), - slashCommands: PI_BUILT_IN_SLASH_COMMANDS, - skills: getPiSkills(settings), + slashCommands: resources.slashCommands, + skills: resources.skills, + pi: resources.pi, probe: { installed: true, version: VERSION, - status: authenticated ? "ready" : "warning", + status: authenticated && !resourceMessage ? "ready" : "warning", auth: { status: authenticated ? "authenticated" : "unauthenticated", type: "pi", diff --git a/apps/server/src/provider/pi/PiExtensionUiBridge.test.ts b/apps/server/src/provider/pi/PiExtensionUiBridge.test.ts new file mode 100644 index 0000000000..b4d4673027 --- /dev/null +++ b/apps/server/src/provider/pi/PiExtensionUiBridge.test.ts @@ -0,0 +1,69 @@ +import { ProviderInstanceId, ThreadId, type ProviderRuntimeEvent } from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; + +import { makePiExtensionUiBridge } from "./PiExtensionUiBridge.ts"; + +describe("makePiExtensionUiBridge", () => { + it("provides a Pi-compatible plain-text theme and routes status to Pi panel state", async () => { + const events: ProviderRuntimeEvent[] = []; + const bridge = makePiExtensionUiBridge({ + getContext: () => ({ + threadId: ThreadId.make("thread-1"), + providerInstanceId: ProviderInstanceId.make("pi"), + activeTurnId: undefined, + }), + publishRuntimeEvent: async (event) => { + events.push(event); + }, + }); + + expect(bridge.uiContext.theme.fg("dim", "generating")).toBe("generating"); + + bridge.uiContext.setStatus("tps", bridge.uiContext.theme.fg("accent", "42 tok/s")); + await Promise.resolve(); + + expect(events[0]?.type).toBe("pi.ui.state.updated"); + const [event] = events; + if (event?.type !== "pi.ui.state.updated") { + throw new Error("expected pi.ui.state.updated"); + } + expect(event.payload.surface).toBe("status"); + expect(event.payload.key).toBe("tps"); + expect(event.payload.text).toBe("42 tok/s"); + }); + + it("publishes only JSON-safe extension activity data", async () => { + const events: ProviderRuntimeEvent[] = []; + const bridge = makePiExtensionUiBridge({ + getContext: () => ({ + threadId: ThreadId.make("thread-1"), + providerInstanceId: ProviderInstanceId.make("pi"), + activeTurnId: undefined, + }), + publishRuntimeEvent: async (event) => { + events.push(event); + }, + }); + + await bridge.publishActivity({ + activityType: "widget", + message: "Widget updated", + data: { + path: "/tmp/pi-extension.ts", + baseDir: undefined, + render: () => undefined, + nested: { ok: true, missing: undefined }, + }, + }); + + expect(events[0]?.type).toBe("extension.activity"); + const [event] = events; + if (event?.type !== "extension.activity") { + throw new Error("expected extension.activity"); + } + expect(event.payload.data).toEqual({ + path: "/tmp/pi-extension.ts", + nested: { ok: true }, + }); + }); +}); diff --git a/apps/server/src/provider/pi/PiExtensionUiBridge.ts b/apps/server/src/provider/pi/PiExtensionUiBridge.ts index 884213dafb..636359d7e1 100644 --- a/apps/server/src/provider/pi/PiExtensionUiBridge.ts +++ b/apps/server/src/provider/pi/PiExtensionUiBridge.ts @@ -1,5 +1,7 @@ import { type ExtensionActivityPayload, + type PiExtensionDiagnosticPayload, + type PiUiStateUpdatedPayload, ApprovalRequestId, RuntimeRequestId, type ProviderRuntimeEvent, @@ -11,11 +13,14 @@ import { ProviderDriverKind, ProviderInstanceId, } from "@t3tools/contracts"; -import type { - ExtensionUIContext, - ExtensionUIDialogOptions, - ExtensionWidgetOptions, +import { + Theme, + type ExtensionUIContext, + type ExtensionUIDialogOptions, + type ExtensionWidgetOptions, + type ThemeColor, } from "@mariozechner/pi-coding-agent"; +import { toPiJsonValue } from "./jsonSafe.ts"; export interface PiExtensionUiBridgeContext { readonly threadId: ThreadId; @@ -37,6 +42,7 @@ export interface PiExtensionUiBridge { answers: ProviderUserInputAnswers, ) => Promise; readonly publishActivity: (activity: PiExtensionActivityInput) => Promise; + readonly publishDiagnostic: (diagnostic: PiExtensionDiagnosticInput) => Promise; readonly dispose: () => void; } @@ -48,6 +54,150 @@ interface PiExtensionActivityInput { readonly data?: unknown; } +interface PiUiStateInput { + readonly surface: PiUiStateUpdatedPayload["surface"]; + readonly key: string; + readonly label?: string; + readonly text?: string; + readonly lines?: readonly string[]; + readonly state?: PiUiStateUpdatedPayload["state"]; + readonly placement?: string; + readonly extensionPath?: string; + readonly data?: unknown; +} + +interface PiExtensionDiagnosticInput { + readonly message: string; + readonly severity?: PiExtensionDiagnosticPayload["severity"]; + readonly visibility?: PiExtensionDiagnosticPayload["visibility"]; + readonly extensionPath?: string; + readonly event?: string; + readonly diagnosticKey?: string; + readonly repeatCount?: number; + readonly hiddenCount?: number; + readonly detail?: unknown; +} + +interface UiStatePublicationState { + lastPublishedAt: number; + lastSignature: string | null; + pending: PiUiStateInput | null; + pendingSignature: string | null; + timeout: ReturnType | null; +} + +const UI_STATE_THROTTLE_MS = 250; +const ANSI_PATTERN = new RegExp(String.raw`\x1B\[[0-?]*[ -/]*[@-~]`, "g"); + +const fallbackFgColors = { + accent: "#7aa2f7", + border: "#6b7280", + borderAccent: "#7aa2f7", + borderMuted: "#4b5563", + success: "#80c990", + error: "#f7768e", + warning: "#e0af68", + muted: "#9ca3af", + dim: "#6b7280", + text: "#d1d5db", + thinkingText: "#9ca3af", + userMessageText: "#d1d5db", + customMessageText: "#d1d5db", + customMessageLabel: "#9ca3af", + toolTitle: "#d1d5db", + toolOutput: "#d1d5db", + mdHeading: "#d1d5db", + mdLink: "#7aa2f7", + mdLinkUrl: "#9ca3af", + mdCode: "#d1d5db", + mdCodeBlock: "#d1d5db", + mdCodeBlockBorder: "#4b5563", + mdQuote: "#9ca3af", + mdQuoteBorder: "#4b5563", + mdHr: "#4b5563", + mdListBullet: "#9ca3af", + toolDiffAdded: "#80c990", + toolDiffRemoved: "#f7768e", + toolDiffContext: "#9ca3af", + syntaxComment: "#6b7280", + syntaxKeyword: "#bb9af7", + syntaxFunction: "#7aa2f7", + syntaxVariable: "#d1d5db", + syntaxString: "#9ece6a", + syntaxNumber: "#ff9e64", + syntaxType: "#2ac3de", + syntaxOperator: "#89ddff", + syntaxPunctuation: "#9ca3af", + thinkingOff: "#6b7280", + thinkingMinimal: "#9ca3af", + thinkingLow: "#7aa2f7", + thinkingMedium: "#e0af68", + thinkingHigh: "#ff9e64", + thinkingXhigh: "#f7768e", + bashMode: "#7aa2f7", +} satisfies Record; + +const fallbackBgColors: ConstructorParameters[1] = { + selectedBg: "#1f2937", + userMessageBg: "#111827", + customMessageBg: "#111827", + toolPendingBg: "#111827", + toolSuccessBg: "#111827", + toolErrorBg: "#111827", +}; + +class PlainTextPiTheme extends Theme { + constructor() { + super(fallbackFgColors, fallbackBgColors, "truecolor", { name: "t3" }); + } + + override fg(_color: ThemeColor, text: string) { + return text; + } + + override bg(_color: Parameters[0], text: string) { + return text; + } + + override bold(text: string) { + return text; + } + + override italic(text: string) { + return text; + } + + override underline(text: string) { + return text; + } + + override inverse(text: string) { + return text; + } + + override strikethrough(text: string) { + return text; + } + + override getFgAnsi(_color: ThemeColor) { + return ""; + } + + override getBgAnsi(_color: Parameters[0]) { + return ""; + } + + override getThinkingBorderColor(_level: Parameters[0]) { + return (text: string) => text; + } + + override getBashModeBorderColor() { + return (text: string) => text; + } +} + +const fallbackTheme = new PlainTextPiTheme(); + function nowIso() { return new Date().toISOString(); } @@ -72,6 +222,30 @@ function trimToMessage(value: string, fallback: string) { return trimmed.length > 0 ? trimmed : fallback; } +function stripAnsi(value: string) { + return value.replace(ANSI_PATTERN, ""); +} + +function sanitizeDisplayText(value: string | undefined): string | undefined { + return value === undefined ? undefined : stripAnsi(value); +} + +function uiStateKey(state: Pick) { + return `${state.surface}:${state.key}`; +} + +function uiStateSignature(state: PiUiStateInput) { + return JSON.stringify({ + surface: state.surface, + key: state.key, + label: state.label, + text: state.text, + lines: state.lines, + state: state.state, + placement: state.placement, + }); +} + function makeQuestion(input: { readonly requestId: ApprovalRequestId; readonly kind: PendingPiExtensionDialog["kind"]; @@ -145,10 +319,12 @@ export function makePiExtensionUiBridge(input: { readonly publishRuntimeEvent: PiRuntimeEventPublisher; }): PiExtensionUiBridge { const pendingDialogs = new Map(); + const uiStatePublications = new Map(); let editorText = ""; let toolsExpanded = false; const publishActivity = async (activity: PiExtensionActivityInput) => { + const data = toPiJsonValue(activity.data); await input.publishRuntimeEvent({ ...baseEvent(input.getContext()), type: "extension.activity", @@ -158,12 +334,122 @@ export function makePiExtensionUiBridge(input: { message: trimToMessage(activity.message, "Pi extension activity"), ...(activity.severity ? { severity: activity.severity } : {}), ...(activity.extensionPath ? { extensionPath: activity.extensionPath } : {}), - ...(activity.data !== undefined ? { data: activity.data } : {}), + ...(data !== undefined ? { data } : {}), uiOnly: true, }, }); }; + const publishDiagnostic = async (diagnostic: PiExtensionDiagnosticInput) => { + const detail = toPiJsonValue(diagnostic.detail); + await input.publishRuntimeEvent({ + ...baseEvent(input.getContext()), + type: "pi.extension.diagnostic", + payload: { + source: "pi.extension", + message: trimToMessage(diagnostic.message, "Pi extension diagnostic"), + severity: diagnostic.severity ?? "warning", + visibility: diagnostic.visibility ?? "pi-panel", + ...(diagnostic.extensionPath ? { extensionPath: diagnostic.extensionPath } : {}), + ...(diagnostic.event ? { event: diagnostic.event } : {}), + ...(diagnostic.diagnosticKey ? { diagnosticKey: diagnostic.diagnosticKey } : {}), + ...(diagnostic.repeatCount ? { repeatCount: diagnostic.repeatCount } : {}), + ...(diagnostic.hiddenCount !== undefined ? { hiddenCount: diagnostic.hiddenCount } : {}), + ...(detail !== undefined ? { detail } : {}), + uiOnly: true, + }, + }); + }; + + const publishUiStateNow = async (state: PiUiStateInput) => { + const publicationKey = uiStateKey(state); + const publicationState = uiStatePublications.get(publicationKey); + const signature = uiStateSignature(state); + if (publicationState) { + publicationState.lastPublishedAt = Date.now(); + publicationState.lastSignature = signature; + publicationState.pendingSignature = null; + } + const data = toPiJsonValue(state.data); + + await input.publishRuntimeEvent({ + ...baseEvent(input.getContext()), + type: "pi.ui.state.updated", + payload: { + source: "pi.extension.ui", + surface: state.surface, + key: trimToMessage(state.key, state.surface), + ...(state.label ? { label: state.label } : {}), + ...(state.text !== undefined ? { text: sanitizeDisplayText(state.text) } : {}), + ...(state.lines ? { lines: state.lines.map(stripAnsi) } : {}), + ...(state.state ? { state: state.state } : {}), + ...(state.placement ? { placement: state.placement } : {}), + ...(state.extensionPath ? { extensionPath: state.extensionPath } : {}), + ...(data !== undefined ? { data } : {}), + uiOnly: true, + }, + }); + }; + + const publishUiState = (state: PiUiStateInput, options?: { readonly throttle?: boolean }) => { + const publicationKey = uiStateKey(state); + const signature = uiStateSignature(state); + const existing = uiStatePublications.get(publicationKey); + const publicationState = + existing ?? + ({ + lastPublishedAt: 0, + lastSignature: null, + pending: null, + pendingSignature: null, + timeout: null, + } satisfies UiStatePublicationState); + if (!existing) { + uiStatePublications.set(publicationKey, publicationState); + } + + if ( + publicationState.lastSignature === signature || + publicationState.pendingSignature === signature + ) { + return; + } + + if (!options?.throttle) { + if (publicationState.timeout) { + clearTimeout(publicationState.timeout); + publicationState.timeout = null; + publicationState.pending = null; + publicationState.pendingSignature = null; + } + void publishUiStateNow(state); + return; + } + + const elapsed = Date.now() - publicationState.lastPublishedAt; + if (elapsed >= UI_STATE_THROTTLE_MS) { + void publishUiStateNow(state); + return; + } + + publicationState.pending = state; + publicationState.pendingSignature = signature; + if (publicationState.timeout) { + return; + } + + publicationState.timeout = setTimeout(() => { + publicationState.timeout = null; + const pending = publicationState.pending; + publicationState.pending = null; + publicationState.pendingSignature = null; + if (pending) { + void publishUiStateNow(pending); + } + }, UI_STATE_THROTTLE_MS - elapsed); + publicationState.timeout.unref?.(); + }; + const openDialog = (dialog: { readonly kind: PendingPiExtensionDialog["kind"]; readonly title: string; @@ -215,11 +501,23 @@ export function makePiExtensionUiBridge(input: { }); }); - const unsupportedComponent = (activityType: "custom-ui" | "widget", data?: unknown) => { - void publishActivity({ - activityType, - message: "custom ui coming soon", - data, + const publishUnsupportedUi = (input: { + readonly surface: PiUiStateInput["surface"]; + readonly key: string; + readonly message: string; + readonly data?: unknown; + }) => { + publishUiState({ + surface: input.surface, + key: input.key, + text: input.message, + state: "unsupported", + data: input.data, + }); + void publishDiagnostic({ + message: input.message, + severity: "warning", + detail: input.data, }); }; @@ -231,18 +529,30 @@ export function makePiExtensionUiBridge(input: { }, input: (title, placeholder, opts) => openDialog({ kind: "input", title, placeholder, opts }), notify: (message, type = "info") => { - void publishActivity({ activityType: "notify", message, severity: type }); + void publishActivity({ activityType: "notify", message: stripAnsi(message), severity: type }); }, onTerminalInput: () => () => {}, setStatus: (key, text) => { - void publishActivity({ - activityType: "status", - message: text ? `${key}: ${text}` : `${key}: cleared`, - data: { key, text }, - }); + publishUiState( + { + surface: "status", + key, + label: key, + ...(text === undefined ? { state: "cleared" } : { text, state: "set" }), + }, + { throttle: true }, + ); }, setWorkingMessage: (message) => { - if (message) void publishActivity({ activityType: "status", message }); + publishUiState( + { + surface: "status", + key: "working", + label: "working", + ...(message === undefined ? { state: "cleared" } : { text: message, state: "set" }), + }, + { throttle: true }, + ); }, setWorkingVisible: () => {}, setWorkingIndicator: () => {}, @@ -253,49 +563,101 @@ export function makePiExtensionUiBridge(input: { options?: ExtensionWidgetOptions, ) => { if (Array.isArray(content)) { - void publishActivity({ - activityType: "widget", - message: content.length > 0 ? `${key}: ${content.join("\n")}` : `${key}: cleared`, - data: { key, content, options }, + publishUiState({ + surface: "widget", + key, + label: key, + lines: content, + state: "set", + ...(options?.placement ? { placement: options.placement } : {}), + data: { options }, }); return; } + if (content === undefined) { + publishUiState({ surface: "widget", key, state: "cleared" }); + return; + } if (typeof content === "function") { - unsupportedComponent("custom-ui", { key, options }); + publishUnsupportedUi({ + surface: "widget", + key, + message: "Custom widget rendering is not available in T3 yet.", + data: { key, options }, + }); } }, setFooter: (factory) => { - if (factory) unsupportedComponent("custom-ui", { surface: "footer" }); + if (factory) { + publishUnsupportedUi({ + surface: "footer", + key: "custom", + message: "Custom footer rendering is not available in T3 yet.", + data: { surface: "footer" }, + }); + return; + } + publishUiState({ surface: "footer", key: "custom", state: "cleared" }); }, setHeader: (factory) => { - if (factory) unsupportedComponent("custom-ui", { surface: "header" }); + if (factory) { + publishUnsupportedUi({ + surface: "header", + key: "custom", + message: "Custom header rendering is not available in T3 yet.", + data: { surface: "header" }, + }); + return; + } + publishUiState({ surface: "header", key: "custom", state: "cleared" }); }, setTitle: (title) => { - void publishActivity({ activityType: "title", message: title }); + publishUiState({ surface: "title", key: "title", label: "title", text: title }); }, custom: async () => { - await publishActivity({ - activityType: "custom-ui", - message: "custom ui coming soon", + await publishDiagnostic({ + message: "Custom Pi UI is not available in T3 yet.", + severity: "warning", }); return undefined as never; }, pasteToEditor: (text) => { editorText = `${editorText}${text}`; - void publishActivity({ activityType: "editor", message: text, data: { action: "paste" } }); + publishUiState({ + surface: "editor", + key: "composer", + text: editorText, + state: "set", + data: { action: "paste" }, + }); }, setEditorText: (text) => { editorText = text; - void publishActivity({ activityType: "editor", message: text, data: { action: "set" } }); + publishUiState({ + surface: "editor", + key: "composer", + text, + state: "set", + data: { action: "set" }, + }); }, getEditorText: () => editorText, editor: (title, prefill) => openDialog({ kind: "editor", title, prefill }), addAutocompleteProvider: () => {}, setEditorComponent: (factory) => { - if (factory) unsupportedComponent("custom-ui", { surface: "editor" }); + if (factory) { + publishUnsupportedUi({ + surface: "editor", + key: "custom", + message: "Custom editor rendering is not available in T3 yet.", + data: { surface: "editor" }, + }); + } else { + publishUiState({ surface: "editor", key: "custom", state: "cleared" }); + } }, getEditorComponent: () => undefined, - theme: {} as ExtensionUIContext["theme"], + theme: fallbackTheme, getAllThemes: () => [], getTheme: () => undefined, setTheme: () => ({ @@ -311,6 +673,7 @@ export function makePiExtensionUiBridge(input: { return { uiContext, publishActivity, + publishDiagnostic, respond: async (requestId, answers) => { const pending = pendingDialogs.get(requestId); if (!pending) { @@ -320,6 +683,12 @@ export function makePiExtensionUiBridge(input: { pending.resolve(resolveDialogAnswer(pending.kind, answers)); }, dispose: () => { + for (const publication of uiStatePublications.values()) { + if (publication.timeout) { + clearTimeout(publication.timeout); + } + } + uiStatePublications.clear(); for (const pending of pendingDialogs.values()) { pending.resolve(undefined); } diff --git a/apps/server/src/provider/pi/jsonSafe.test.ts b/apps/server/src/provider/pi/jsonSafe.test.ts new file mode 100644 index 0000000000..5f31caa33f --- /dev/null +++ b/apps/server/src/provider/pi/jsonSafe.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; + +import { toPiJsonValue } from "./jsonSafe.ts"; + +describe("toPiJsonValue", () => { + it("removes non-JSON object fields before Pi metadata crosses RPC", () => { + const cyclic: Record = { label: "cycle" }; + cyclic.self = cyclic; + + expect( + toPiJsonValue({ + path: "/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts", + source: "local", + baseDir: undefined, + nested: { + enabled: true, + missing: undefined, + callback: () => undefined, + }, + list: [undefined, Number.NaN, "tool"], + cyclic, + }), + ).toEqual({ + path: "/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts", + source: "local", + nested: { + enabled: true, + }, + list: [null, null, "tool"], + cyclic: { + label: "cycle", + }, + }); + }); +}); diff --git a/apps/server/src/provider/pi/jsonSafe.ts b/apps/server/src/provider/pi/jsonSafe.ts new file mode 100644 index 0000000000..369ef12115 --- /dev/null +++ b/apps/server/src/provider/pi/jsonSafe.ts @@ -0,0 +1,46 @@ +import type { Schema } from "effect"; + +export type PiJsonValue = Schema.Json; + +function toPiJsonValueInternal(value: unknown, seen: WeakSet): PiJsonValue | undefined { + if (value === null || typeof value === "string" || typeof value === "boolean") { + return value; + } + + if (typeof value === "number") { + return Number.isFinite(value) ? value : undefined; + } + + if (Array.isArray(value)) { + if (seen.has(value)) return undefined; + seen.add(value); + try { + return value.map((item) => toPiJsonValueInternal(item, seen) ?? null); + } finally { + seen.delete(value); + } + } + + if (typeof value === "object" && value !== null) { + if (seen.has(value)) return undefined; + seen.add(value); + try { + const out: Record = {}; + for (const [key, nested] of Object.entries(value)) { + const jsonValue = toPiJsonValueInternal(nested, seen); + if (jsonValue !== undefined) { + out[key] = jsonValue; + } + } + return out; + } finally { + seen.delete(value); + } + } + + return undefined; +} + +export function toPiJsonValue(value: unknown): PiJsonValue | undefined { + return toPiJsonValueInternal(value, new WeakSet()); +} diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index ce9eb950f1..30842441ee 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -191,6 +191,7 @@ export function buildServerProvider(input: { models: ReadonlyArray; slashCommands?: ReadonlyArray; skills?: ReadonlyArray; + pi?: ServerProvider["pi"]; probe: ProviderProbeResult; }): ServerProviderDraft { const versionAdvisory = input.driver @@ -216,6 +217,7 @@ export function buildServerProvider(input: { models: input.models, slashCommands: [...(input.slashCommands ?? [])], skills: [...(input.skills ?? [])], + ...(input.pi ? { pi: input.pi } : {}), ...(versionAdvisory ? { versionAdvisory } : {}), }; } diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts index db6c358c99..ad7e12a680 100644 --- a/apps/server/src/provider/providerStatusCache.ts +++ b/apps/server/src/provider/providerStatusCache.ts @@ -63,6 +63,7 @@ export const hydrateCachedProvider = (input: { checkedAt: input.cachedProvider.checkedAt, slashCommands: input.cachedProvider.slashCommands, skills: input.cachedProvider.skills, + ...(input.cachedProvider.pi ? { pi: input.cachedProvider.pi } : {}), }; return input.cachedProvider.message diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index ecba6fcd5f..c9ec1fb14b 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -70,6 +70,12 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; +import { + PiRuntimePanel, + PiRuntimePanelTrigger, + type PiRuntimePanelTab, + usePiRuntimePanelState, +} from "./PiRuntimePanel"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { searchSlashCommandItems } from "./composerSlashCommandSearch"; import { @@ -115,6 +121,7 @@ import { searchProviderSkills } from "../../providerSkillSearch"; import { useMediaQuery } from "../../hooks/useMediaQuery"; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; +const PI_PROVIDER = ProviderDriverKind.make("pi"); const runtimeModeConfig: Record< RuntimeMode, @@ -723,19 +730,59 @@ export const ChatComposer = memo( () => selectedProviderEntry?.models ?? [], [selectedProviderEntry], ); + const isPiProviderSelected = selectedProvider === PI_PROVIDER; const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false); const [isModelPickerOptionsHydrated, setIsModelPickerOptionsHydrated] = useState(false); + const [piPanelOpen, setPiPanelOpen] = useState(false); + const [piPanelTab, setPiPanelTab] = useState("home"); + const piPanelState = usePiRuntimePanelState({ + activities: activeThreadActivities, + provider: selectedProviderStatus, + skills: selectedProviderStatus?.skills, + thread: activeThread, + gitCwd, + model: selectedModel, + }); + const selectedProviderSlashCommands = useMemo(() => { + const commands = [...(selectedProviderStatus?.slashCommands ?? [])]; + if (!isPiProviderSelected) { + return commands; + } + const seen = new Set(commands.map((command) => command.name)); + for (const command of piPanelState.slashCommands) { + if (seen.has(command.name)) continue; + commands.push(command); + seen.add(command.name); + } + return commands; + }, [isPiProviderSelected, piPanelState.slashCommands, selectedProviderStatus?.slashCommands]); + const selectedProviderModelsForComposer = useMemo(() => { + if (!isPiProviderSelected || piPanelState.models.length === 0) { + return selectedProviderModels; + } + const modelsBySlug = new Map(selectedProviderModels.map((model) => [model.slug, model])); + for (const model of piPanelState.models) { + modelsBySlug.set(model.slug, model); + } + return [...modelsBySlug.values()]; + }, [isPiProviderSelected, piPanelState.models, selectedProviderModels]); const composerProviderState = useMemo( () => getComposerProviderState({ provider: selectedProvider, model: selectedModel, - models: selectedProviderModels, + models: selectedProviderModelsForComposer, prompt, modelOptions: composerModelOptions?.[selectedProvider], }), - [composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels], + [ + composerModelOptions, + prompt, + selectedModel, + selectedProvider, + selectedProviderModelsForComposer, + ], ); const selectedPromptEffort = composerProviderState.promptEffort; @@ -767,14 +814,47 @@ export const ChatComposer = memo( const out = new Map>(); const entries = isModelPickerOptionsHydrated ? providerInstanceEntries - : selectedProviderEntry - ? [selectedProviderEntry] - : []; + : (() => { + const initialEntries = new Map(); + if (selectedProviderEntry) { + initialEntries.set(selectedProviderEntry.instanceId, selectedProviderEntry); + } + for (const favorite of settings.favorites ?? []) { + const favoriteEntry = providerInstanceEntries.find( + (entry) => entry.instanceId === favorite.provider, + ); + if (favoriteEntry) { + initialEntries.set(favoriteEntry.instanceId, favoriteEntry); + } + } + return [...initialEntries.values()]; + })(); for (const entry of entries) { - out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry)); + const entryForOptions = + isPiProviderSelected && + entry.instanceId === selectedInstanceId && + selectedProviderModelsForComposer.length > 0 + ? ({ + ...entry, + models: selectedProviderModelsForComposer, + snapshot: { + ...entry.snapshot, + models: selectedProviderModelsForComposer, + }, + } satisfies ProviderInstanceEntry) + : entry; + out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entryForOptions)); } return out; - }, [isModelPickerOptionsHydrated, providerInstanceEntries, selectedProviderEntry, settings]); + }, [ + isModelPickerOptionsHydrated, + isPiProviderSelected, + providerInstanceEntries, + selectedInstanceId, + selectedProviderEntry, + selectedProviderModelsForComposer, + settings, + ]); const selectedModelForPickerWithCustomFallback = useMemo(() => { const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? []; return currentOptions.some((option) => option.slug === selectedModelForPicker) @@ -796,6 +876,12 @@ export const ChatComposer = memo( }; }, [isComposerModelPickerOpen]); + useEffect(() => { + if (!isPiProviderSelected) { + setPiPanelOpen(false); + } + }, [isPiProviderSelected]); + useEffect(() => { if (!isComposerModelPickerOpen) { return; @@ -926,16 +1012,14 @@ export const ChatComposer = memo( description: "Switch this thread back to normal build mode", }, ] satisfies ReadonlyArray>; - const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map( - (command) => ({ - id: `provider-slash-command:${selectedProvider}:${command.name}`, - type: "provider-slash-command" as const, - provider: selectedProvider, - command, - label: `/${command.name}`, - description: command.description ?? command.input?.hint ?? "Run provider command", - }), - ); + const providerSlashCommandItems = selectedProviderSlashCommands.map((command) => ({ + id: `provider-slash-command:${selectedProvider}:${command.name}`, + type: "provider-slash-command" as const, + provider: selectedProvider, + command, + label: `/${command.name}`, + description: command.description ?? command.input?.hint ?? "Run provider command", + })); const query = composerTrigger.query.trim().toLowerCase(); const slashCommandItems = [...builtInSlashCommandItems, ...providerSlashCommandItems]; if (!query) { @@ -960,7 +1044,13 @@ export const ChatComposer = memo( })); } return []; - }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries]); + }, [ + composerTrigger, + selectedProvider, + selectedProviderSlashCommands, + selectedProviderStatus, + workspaceEntries, + ]); const composerMenuOpen = Boolean(composerTrigger); const composerMenuSearchKey = composerTrigger @@ -995,7 +1085,8 @@ export const ChatComposer = memo( const hasComposerHeader = isComposerApprovalState || pendingUserInputs.length > 0 || - (showPlanFollowUpPrompt && activeProposedPlan !== null); + (showPlanFollowUpPrompt && activeProposedPlan !== null) || + (isPiProviderSelected && piPanelOpen); const showCollapsedMobilePromptRow = isComposerCollapsedMobile && !isComposerApprovalState && pendingUserInputs.length === 0; @@ -1062,7 +1153,7 @@ export const ChatComposer = memo( ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), ...(routeKind === "draft" && draftId ? { draftId } : {}), model: selectedModel, - models: selectedProviderModels, + models: selectedProviderModelsForComposer, modelOptions: composerModelOptions?.[selectedProvider], prompt, onPromptChange: setPromptFromTraits, @@ -1072,7 +1163,7 @@ export const ChatComposer = memo( ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), ...(routeKind === "draft" && draftId ? { draftId } : {}), model: selectedModel, - models: selectedProviderModels, + models: selectedProviderModelsForComposer, modelOptions: composerModelOptions?.[selectedProvider], prompt, onPromptChange: setPromptFromTraits, @@ -1512,7 +1603,7 @@ export const ChatComposer = memo( }, [readComposerSnapshot]); const onSelectComposerItem = useCallback( - (item: ComposerCommandItem) => { + (item: ComposerCommandItem, action: "insert" | "run" = "run") => { if (composerSelectLockRef.current) return; composerSelectLockRef.current = true; window.requestAnimationFrame(() => { @@ -1560,21 +1651,42 @@ export const ChatComposer = memo( return; } if (item.type === "provider-slash-command") { - const replacement = `/${item.command.name} `; + const replacement = action === "run" ? `/${item.command.name}` : `/${item.command.name} `; const replacementRangeEnd = extendReplacementRangeForTrailingSpace( snapshot.value, trigger.rangeEnd, replacement, ); + const expectedText = snapshot.value.slice(trigger.rangeStart, replacementRangeEnd); + if (action === "run") { + const next = replaceTextRange( + snapshot.value, + trigger.rangeStart, + replacementRangeEnd, + replacement, + ); + if (expectedText !== snapshot.value.slice(trigger.rangeStart, replacementRangeEnd)) { + return; + } + promptRef.current = next.text; + setPrompt(next.text); + setComposerCursor(collapseExpandedComposerCursor(next.text, next.cursor)); + setComposerTrigger(null); + setComposerHighlightedItemId(null); + window.requestAnimationFrame(() => { + onSend(); + }); + return; + } const applied = applyPromptReplacement( trigger.rangeStart, replacementRangeEnd, replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + { + expectedText, + }, ); - if (applied) { - setComposerHighlightedItemId(null); - } + if (applied) setComposerHighlightedItemId(null); return; } if (item.type === "skill") { @@ -1596,7 +1708,14 @@ export const ChatComposer = memo( return; } }, - [applyPromptReplacement, handleInteractionModeChange, resolveActiveComposerTrigger], + [ + applyPromptReplacement, + handleInteractionModeChange, + onSend, + promptRef, + resolveActiveComposerTrigger, + setPrompt, + ], ); const onComposerMenuItemHighlighted = useCallback( @@ -1712,7 +1831,7 @@ export const ChatComposer = memo( return true; } if ((key === "Enter" || key === "Tab") && selectedItem) { - onSelectComposerItem(selectedItem); + onSelectComposerItem(selectedItem, key === "Tab" ? "insert" : "run"); return true; } } @@ -1956,7 +2075,7 @@ export const ChatComposer = memo( selectedModelSelection, selectedProvider, selectedModel, - selectedProviderModels, + selectedProviderModels: selectedProviderModelsForComposer, }), }), [ @@ -1975,7 +2094,7 @@ export const ChatComposer = memo( selectedModelSelection, selectedPromptEffort, selectedProvider, - selectedProviderModels, + selectedProviderModelsForComposer, ], ); @@ -2132,6 +2251,15 @@ export const ChatComposer = memo( ) : null} + {!isComposerCollapsedMobile && isPiProviderSelected && piPanelOpen ? ( + setPiPanelOpen(false)} + /> + ) : null} + {showCollapsedMobilePromptRow ? (
+ ); +} + +export function PiRuntimePanel(props: PiRuntimePanelProps) { + return ( +
+
+
+ Pi + {props.state.summaryStatus ? ( + + {props.state.summaryStatus} + + ) : null} + {props.state.issueCount > 0 ? ( + + {props.state.issueCount} + + ) : null} +
+ +
+
+ {PANEL_TABS.map((tab) => ( + + ))} +
+ +
{renderPanelTab(props.state, props.tab)}
+
+
+ ); +} + +function renderPanelTab(state: PiRuntimePanelState, tab: PiRuntimePanelTab) { + switch (tab) { + case "home": + return ; + case "extensions": + return ; + case "logs": + return ; + } +} + +function PiPanelHome({ state }: { readonly state: PiRuntimePanelState }) { + return ( +
+ {state.title || state.headers.length > 0 ? ( +
+ Header + {state.title ? : null} + {state.headers.map((row) => ( + + ))} +
+ ) : null} + +
+ Status + {state.statuses.length > 0 ? ( + state.statuses.map((row) => ( + + )) + ) : ( + No active status + )} +
+ +
+ Widgets + {state.widgets.length > 0 ? ( + state.widgets.map((widget) => ( +
+
{widget.label}
+
+                {widget.lines.length > 0 ? widget.lines.join("\n") : widget.text}
+              
+
+ )) + ) : ( + No active widgets + )} +
+ +
+ Footer + {state.cwd ? : null} + {state.branch ? : null} + {state.model ? : null} + {state.footers.map((row) => ( + + ))} +
+
+ ); +} + +function PiPanelExtensions({ state }: { readonly state: PiRuntimePanelState }) { + return ( +
+
+ Extensions + {state.extensions.length > 0 ? ( + state.extensions.map((extension) => ( +
+
+
{extension.name}
+
{extension.path}
+
+ active +
+ )) + ) : ( + No extension snapshot yet + )} +
+ +
+ Skills + {state.skills.length > 0 ? ( + state.skills.map((skill) => { + const source = formatProviderSkillInstallSource(skill); + return ( +
+ + {formatProviderSkillDisplayName(skill)} + + {source ? {source} : null} +
+ ); + }) + ) : ( + No Pi skills loaded + )} +
+
+ ); +} + +function PiPanelLogs({ logs }: { readonly logs: readonly PiPanelLog[] }) { + if (logs.length === 0) { + return No Pi logs yet; + } + return ( +
+ {logs.slice(0, 12).map((log) => ( +
+ + {log.severity === "info" ? null : } + +
+
+ {log.severity} + {log.source} +
+
{log.message}
+ {log.hiddenCount > 0 ? ( +
+ {log.hiddenCount} repeats hidden +
+ ) : null} +
+
+ ))} +
+ ); +} + +function PiPanelSectionLabel({ children }: { readonly children: string }) { + return ( +
+ {children} +
+ ); +} + +function PiKeyValue(props: { + readonly label: string; + readonly value: string; + readonly muted?: boolean; +}) { + return ( +
+ {props.label} + + {props.value} + +
+ ); +} + +function PiEmptyLine({ children }: { readonly children: string }) { + return
{children}
; +} diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index d3b168876a..b6352db5de 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -254,6 +254,7 @@ async function mountPicker(props: { lockedContinuationGroupKey?: string | null; providers?: ReadonlyArray; settings?: UnifiedSettings; + modelOptionsByInstance?: ReadonlyMap>; triggerVariant?: "ghost" | "outline"; }) { const host = document.createElement("div"); @@ -262,12 +263,14 @@ async function mountPicker(props: { const providers = props.providers ?? TEST_PROVIDERS; const instanceEntries = sortProviderInstanceEntries(deriveProviderInstanceEntries(providers)); const activeInstanceId = props.activeInstanceId ?? CODEX_INSTANCE_ID; - const modelOptionsByInstance = getCustomModelOptionsByInstance( - props.settings ?? DEFAULT_UNIFIED_SETTINGS, - providers, - activeInstanceId, - props.model, - ); + const modelOptionsByInstance = + props.modelOptionsByInstance ?? + getCustomModelOptionsByInstance( + props.settings ?? DEFAULT_UNIFIED_SETTINGS, + providers, + activeInstanceId, + props.model, + ); const screen = await render( { } }); + it("falls back to the active instance when favorites are not in the loaded option slice", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + favorites: [{ provider: "codex", model: "gpt-5-codex" }], + }), + ); + const allOptions = getCustomModelOptionsByInstance( + DEFAULT_UNIFIED_SETTINGS, + TEST_PROVIDERS, + CLAUDE_INSTANCE_ID, + "claude-opus-4-6", + ); + const mounted = await mountPicker({ + activeInstanceId: CLAUDE_INSTANCE_ID, + model: "claude-opus-4-6", + lockedProvider: null, + modelOptionsByInstance: new Map([ + [CLAUDE_INSTANCE_ID, allOptions.get(CLAUDE_INSTANCE_ID) ?? []], + ]), + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).not.toContain("No models found"); + expect(text).toContain("Claude Opus 4.6"); + }); + } finally { + localStorage.removeItem("t3code:client-settings:v1"); + await mounted.cleanup(); + } + }); + it("filters models by selected provider in sidebar", async () => { const mounted = await mountPicker({ activeInstanceId: CLAUDE_INSTANCE_ID, diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index baf384d6af..f9f63eb408 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -249,6 +249,7 @@ describe("derivePendingUserInputs", () => { id: "sandbox_mode", header: "Sandbox", question: "Which mode should be used?", + inputKind: "select", options: [ { label: "workspace-write", @@ -620,6 +621,45 @@ describe("deriveWorkLogEntries", () => { expect(entries.map((entry) => entry.id)).toEqual(["task-progress", "task-complete"]); }); + it("omits Pi panel state and diagnostics from the normal work log", () => { + const activities: OrchestrationThreadActivity[] = [ + makeActivity({ + id: "pi-status", + createdAt: "2026-02-23T00:00:01.000Z", + kind: "pi.ui.state.updated", + summary: "Pi status updated", + tone: "info", + payload: { + source: "pi.extension.ui", + surface: "status", + key: "tps", + text: "42 tok/s", + }, + }), + makeActivity({ + id: "pi-diagnostic", + createdAt: "2026-02-23T00:00:02.000Z", + kind: "pi.extension.diagnostic", + summary: "message_update failed", + tone: "error", + payload: { + source: "pi.extension", + message: "message_update failed", + severity: "error", + }, + }), + makeActivity({ + id: "tool-complete", + createdAt: "2026-02-23T00:00:03.000Z", + summary: "Tool call complete", + kind: "tool.completed", + }), + ]; + + const entries = deriveWorkLogEntries(activities, undefined); + expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]); + }); + it("uses payload summary as label for task entries when available", () => { const activities: OrchestrationThreadActivity[] = [ makeActivity({ diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 84c55665eb..dd376b46b7 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -512,6 +512,7 @@ export function deriveWorkLogEntries( .filter((activity) => activity.kind !== "tool.started") .filter((activity) => activity.kind !== "task.started") .filter((activity) => activity.kind !== "context-window.updated") + .filter((activity) => !isPiPanelOnlyActivity(activity)) .filter((activity) => activity.summary !== "Checkpoint captured") .filter((activity) => !isPlanBoundaryToolActivity(activity)) .map(toDerivedWorkLogEntry); @@ -520,6 +521,25 @@ export function deriveWorkLogEntries( ); } +function isPiPanelOnlyActivity(activity: OrchestrationThreadActivity): boolean { + if ( + activity.kind === "pi.ui.state.updated" || + activity.kind === "pi.extension.configured" || + activity.kind === "pi.extension.diagnostic" + ) { + return true; + } + if (activity.kind !== "extension.activity") { + return false; + } + const payload = + activity.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : null; + const visibility = payload?.visibility; + return visibility === "pi-panel" || visibility === "debug" || visibility === "hidden"; +} + function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean { if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") { return false; diff --git a/docs/providers/pi.md b/docs/providers/pi.md index 456bb7490b..d23e93b863 100644 --- a/docs/providers/pi.md +++ b/docs/providers/pi.md @@ -39,7 +39,60 @@ The tables below use these status labels: - `future`: intentionally not handled in v1. - `internal`: available to extensions, but no T3-facing behavior is needed. -Persisted extension activity is UI-only history. It must not be included in future model context. +Persisted extension activity and Pi panel state are UI-only history. They must not be included in +future model context. + +## Pi Runtime Panel + +When the selected provider is Pi, T3 renders a small Pi panel from the composer. The panel is not a +second chat interface and does not replace T3's composer. It is the home for Pi's TUI-adjacent +surfaces: header, footer, status, widgets, extension inventory, and diagnostics. + +The panel has three tabs: + +- `Home`: the Pi TUI projection. It contains header state, keyed status rows, working message, + string widgets, title metadata, and footer state. +- `Extensions`: loaded extension paths, registered extension tools/commands/providers when known, + and Pi skills. Slash commands still belong in `/` autocomplete, not in a separate commands tab. +- `Logs`: Pi diagnostics and extension lifecycle messages. High-frequency hook failures are deduped + here and hidden from the normal Work Log. + +The open panel has a fixed maximum height inside the composer. Its tab body owns scrolling, so long +extension or skill lists never resize the composer surface after the panel is opened. + +Closed state: + +- The closed Pi button may show one compact status summary, for example + `Pi ยท tps 42 tok/s`, sourced from `ctx.ui.setStatus(...)`. +- Warning/error counts are T3 diagnostics and should appear as a quiet badge, not inline status copy. + +Pi TUI surface mapping: + +| Pi TUI surface | T3 panel section | Pi function source | +| -------------- | ---------------- | ----------------------------------------------------------------------------------- | +| Header | `Home` header | `ctx.ui.setHeader(...)`; fallback from title/session/git metadata when available. | +| Input | T3 composer | T3 keeps its own composer. Pi input prompts render above the composer when pending. | +| Body widgets | `Home` widgets | `ctx.ui.setWidget(...)`; string widgets render, component widgets degrade in v1. | +| Status/footer | `Home` status | `ctx.ui.setStatus(...)` and `ctx.ui.setWorkingMessage(...)`. | +| Footer | `Home` footer | `ctx.ui.setFooter(...)`; fallback from cwd, branch, model, usage, and context. | +| Logs | `Logs` | extension load/reload messages, `bindExtensions({ onError })`, degraded UI calls. | + +Implementation rules: + +- `ctx.ui.setStatus(...)`, `ctx.ui.setWorkingMessage(...)`, `ctx.ui.setTitle(...)`, and + `ctx.ui.setWidget(...)` update keyed Pi panel state. They do not append normal Work Log rows. +- Before a Pi session emits per-thread activity, T3 should seed the panel from the provider snapshot: + static extension paths, extension tools, extension slash commands, Pi skills, and available Pi + models. Live `pi.extension.configured` activity replaces this once the session is bound. +- `ctx.ui.notify(...)` remains user-visible activity when appropriate, and may also be mirrored in + Pi logs. +- Extension hook errors are non-fatal diagnostics. They are deduped by extension path, hook event, + and error message, then displayed in the Pi `Logs` tab instead of the normal Work Log. +- Repeated diagnostics should publish the first occurrence and occasional count updates, not one row + per failure. +- Unsupported custom TUI components should create a restrained placeholder in the relevant Pi panel + surface and a diagnostic log entry. They should not throw or hang the extension. +- T3 should strip terminal ANSI sequences before rendering Pi panel text in the browser. ## `ctx.ui` Mapping @@ -50,21 +103,21 @@ Persisted extension activity is UI-only history. It must not be included in futu | `ctx.ui.input(title, placeholder, opts)` | `v1` | Emit `user-input.requested` with `inputKind: "text"`. Resolve with submitted text or `undefined`. | | `ctx.ui.editor(title, prefill)` | `v1` | Emit `user-input.requested` with `inputKind: "textarea"`. Resolve with submitted text or `undefined`. | | `ctx.ui.notify(message, type)` | `v1` | Persist `extension.activity` with `activityType: "notify"` and severity from `type`. No toast-only behavior. | -| `ctx.ui.setStatus(key, text)` | `v1` | Persist every call as an individual `extension.activity` with `activityType: "status"`. If `text` is omitted, persist a clear-status entry. | -| `ctx.ui.setWorkingMessage(message)` | `v1` | Persist as `extension.activity` status. If omitted, persist or ignore as a clear/default status event. | -| `ctx.ui.setWidget(key, stringLines, options)` | `v1` | Persist string-array widgets as UI-only `extension.activity` with placement metadata. | -| `ctx.ui.setWidget(key, componentFactory, options)` | `degrade` | Persist `custom ui coming soon`, then do not render the component. | -| `ctx.ui.setTitle(title)` | `v1` | Persist UI-only `extension.activity` with `activityType: "title"`. Do not change browser title in v1. | -| `ctx.ui.custom(factory, options)` | `degrade` | Persist exact message `custom ui coming soon`, then resolve as unsupported/cancelled so the extension does not hang. | -| `ctx.ui.pasteToEditor(text)` | `degrade` | Persist UI-only editor activity in v1. Future work can mutate the composer. | -| `ctx.ui.setEditorText(text)` | `degrade` | Persist UI-only editor activity in v1. Future work can mutate the composer. | +| `ctx.ui.setStatus(key, text)` | `v1` | Update keyed Pi panel status state. If `text` is omitted, clear that status key. High-frequency updates should be throttled/deduped. | +| `ctx.ui.setWorkingMessage(message)` | `v1` | Update the Pi panel working/status row. If omitted, clear the custom working message. | +| `ctx.ui.setWidget(key, stringLines, options)` | `v1` | Update keyed Pi panel widget state with string lines and placement metadata. | +| `ctx.ui.setWidget(key, componentFactory, options)` | `degrade` | Update a Pi panel widget placeholder and emit a diagnostic. Do not render the component in v1. | +| `ctx.ui.setTitle(title)` | `v1` | Update Pi panel title/header metadata. Do not change browser title in v1. | +| `ctx.ui.custom(factory, options)` | `degrade` | Emit a Pi panel diagnostic and resolve as unsupported/cancelled so the extension does not hang. | +| `ctx.ui.pasteToEditor(text)` | `degrade` | Update internal editor text state and emit a Pi panel diagnostic in v1. Future work can mutate the composer. | +| `ctx.ui.setEditorText(text)` | `degrade` | Update internal editor text state and emit a Pi panel diagnostic in v1. Future work can mutate the composer. | | `ctx.ui.getEditorText()` | `degrade` | Return `""` in v1. Future work can request current composer text from the client. | | `ctx.ui.onTerminalInput(handler)` | `future` | Return an unsubscribe no-op. Optional one-time activity warning if an extension registers this. | | `ctx.ui.setWorkingVisible(visible)` | `future` | No-op in v1. Optional UI-only activity for visibility changes. | | `ctx.ui.setWorkingIndicator(options)` | `future` | No-op in v1. | | `ctx.ui.setHiddenThinkingLabel(label)` | `future` | No-op in v1. Future mapping can alter reasoning block labels. | -| `ctx.ui.setFooter(factory)` | `future` | No-op or persist unsupported UI activity when a factory is provided. | -| `ctx.ui.setHeader(factory)` | `future` | No-op or persist unsupported UI activity when a factory is provided. | +| `ctx.ui.setFooter(factory)` | `degrade` | Update Pi panel footer placeholder state and emit a diagnostic when a custom factory is provided. | +| `ctx.ui.setHeader(factory)` | `degrade` | Update Pi panel header placeholder state and emit a diagnostic when a custom factory is provided. | | `ctx.ui.addAutocompleteProvider(factory)` | `future` | No-op in v1. Future mapping can compose into T3 composer autocomplete. | | `ctx.ui.setEditorComponent(factory)` | `future` | No-op in v1. | | `ctx.ui.getEditorComponent()` | `future` | Return `undefined` in v1. | @@ -300,9 +353,13 @@ If the extension uses the answer in TypeScript only, no user message is added. I Extension errors are non-fatal by default. -T3 should persist an `extension.activity` row with `activityType: "error"` and severity `error`, -then continue the session. Do not map extension hook/command errors to `runtime.error` unless the Pi -session itself crashes. +T3 should persist Pi diagnostics for extension hook/command errors, then continue the session. Do +not map extension hook/command errors to `runtime.error` unless the Pi session itself crashes. + +Diagnostics belong in the Pi panel `Logs` tab by default. The normal Work Log should only show +extension errors when they are directly user-actionable and intentionally marked for the main +surface. High-frequency hooks such as `message_update` must be deduped and suppressed after the +first visible diagnostic. ## Current Local Extension Coverage diff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.ts index 5476c43306..534bd17c26 100644 --- a/packages/contracts/src/providerRuntime.test.ts +++ b/packages/contracts/src/providerRuntime.test.ts @@ -168,6 +168,126 @@ describe("ProviderRuntimeEvent", () => { expect(parsed.payload.uiOnly).toBe(true); }); + it("decodes Pi panel state updates", () => { + const parsed = decodeRuntimeEvent({ + type: "pi.ui.state.updated", + eventId: "event-pi-ui-1", + provider: "pi", + createdAt: "2026-02-28T00:00:01.000Z", + threadId: "thread-2", + payload: { + source: "pi.extension.ui", + surface: "status", + key: "tps", + label: "tps", + text: "42 tok/s", + state: "set", + uiOnly: true, + }, + }); + + expect(parsed.type).toBe("pi.ui.state.updated"); + if (parsed.type !== "pi.ui.state.updated") { + throw new Error("expected pi.ui.state.updated"); + } + expect(parsed.payload.state).toBe("set"); + expect(parsed.payload.uiOnly).toBe(true); + }); + + it("decodes Pi extension configured snapshots", () => { + const parsed = decodeRuntimeEvent({ + type: "pi.extension.configured", + eventId: "event-pi-config-1", + provider: "pi", + createdAt: "2026-02-28T00:00:01.000Z", + threadId: "thread-2", + payload: { + source: "pi.extension", + extensionPaths: ["/Users/davis/.pi/agent/extensions/tps-tracker.ts"], + slashCommands: [ + { + name: "usage", + description: "Show usage", + source: "extension", + sourceInfo: { path: "/Users/davis/.pi/agent/extensions/tps-tracker.ts" }, + }, + ], + tools: [ + { + name: "search", + description: "Search", + sourceInfo: { path: "/Users/davis/.pi/agent/extensions/tps-tracker.ts" }, + }, + ], + flags: ["verbose"], + models: [{ slug: "extension/model", name: "Extension Model" }], + }, + }); + + expect(parsed.type).toBe("pi.extension.configured"); + if (parsed.type !== "pi.extension.configured") { + throw new Error("expected pi.extension.configured"); + } + expect(parsed.payload.slashCommands[0]?.name).toBe("usage"); + expect(parsed.payload.tools[0]?.sourceInfo).toEqual({ + path: "/Users/davis/.pi/agent/extensions/tps-tracker.ts", + }); + }); + + it("rejects non-JSON Pi extension configured metadata", () => { + expect(() => + decodeRuntimeEvent({ + type: "pi.extension.configured", + eventId: "event-pi-config-unsafe-1", + provider: "pi", + createdAt: "2026-02-28T00:00:01.000Z", + threadId: "thread-2", + payload: { + source: "pi.extension", + extensionPaths: ["/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts"], + slashCommands: [], + tools: [ + { + name: "search", + sourceInfo: { + path: "/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts", + baseDir: undefined, + }, + }, + ], + flags: [], + }, + }), + ).toThrow(); + }); + + it("decodes Pi extension diagnostics with repeat counts", () => { + const parsed = decodeRuntimeEvent({ + type: "pi.extension.diagnostic", + eventId: "event-pi-diagnostic-1", + provider: "pi", + createdAt: "2026-02-28T00:00:01.000Z", + threadId: "thread-2", + payload: { + source: "pi.extension", + message: "tps-tracker.ts failed during message_update", + severity: "error", + visibility: "pi-panel", + event: "message_update", + diagnosticKey: "tps-tracker :: message_update :: theme.fg is not a function", + repeatCount: 100, + hiddenCount: 99, + }, + }); + + expect(parsed.type).toBe("pi.extension.diagnostic"); + if (parsed.type !== "pi.extension.diagnostic") { + throw new Error("expected pi.extension.diagnostic"); + } + expect(parsed.payload.visibility).toBe("pi-panel"); + expect(parsed.payload.hiddenCount).toBe(99); + }); + it("decodes user-input.resolved with answer map", () => { const parsed = decodeRuntimeEvent({ type: "user-input.resolved", diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index 79ef7a432b..5626d5a112 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -192,6 +192,9 @@ const ProviderRuntimeEventType = Schema.Literals([ "deprecation.notice", "files.persisted", "extension.activity", + "pi.ui.state.updated", + "pi.extension.configured", + "pi.extension.diagnostic", "runtime.warning", "runtime.error", ]); @@ -243,6 +246,9 @@ const ConfigWarningType = Schema.Literal("config.warning"); const DeprecationNoticeType = Schema.Literal("deprecation.notice"); const FilesPersistedType = Schema.Literal("files.persisted"); const ExtensionActivityType = Schema.Literal("extension.activity"); +const PiUiStateUpdatedType = Schema.Literal("pi.ui.state.updated"); +const PiExtensionConfiguredType = Schema.Literal("pi.extension.configured"); +const PiExtensionDiagnosticType = Schema.Literal("pi.extension.diagnostic"); const RuntimeWarningType = Schema.Literal("runtime.warning"); const RuntimeErrorType = Schema.Literal("runtime.error"); @@ -611,12 +617,87 @@ export const ExtensionActivityPayload = Schema.Struct({ ]), message: TrimmedNonEmptyStringSchema, severity: Schema.optional(Schema.Literals(["info", "warning", "error"])), + visibility: Schema.optional(Schema.Literals(["main", "pi-panel", "debug", "hidden"])), extensionPath: Schema.optional(TrimmedNonEmptyStringSchema), - data: Schema.optional(Schema.Unknown), + data: Schema.optional(Schema.Json), uiOnly: Schema.optional(Schema.Boolean).pipe(Schema.withConstructorDefault(Effect.succeed(true))), }); export type ExtensionActivityPayload = typeof ExtensionActivityPayload.Type; +export const PiUiPanelSurface = Schema.Literals([ + "header", + "footer", + "status", + "widget", + "title", + "editor", + "custom", +]); +export type PiUiPanelSurface = typeof PiUiPanelSurface.Type; + +export const PiUiStateUpdatedPayload = Schema.Struct({ + source: TrimmedNonEmptyStringSchema, + surface: PiUiPanelSurface, + key: TrimmedNonEmptyStringSchema, + label: Schema.optional(TrimmedNonEmptyStringSchema), + text: Schema.optional(Schema.String), + lines: Schema.optional(Schema.Array(Schema.String)), + state: Schema.optional(Schema.Literals(["set", "cleared", "unsupported"])).pipe( + Schema.withConstructorDefault(Effect.succeed("set")), + ), + placement: Schema.optional(TrimmedNonEmptyStringSchema), + extensionPath: Schema.optional(TrimmedNonEmptyStringSchema), + data: Schema.optional(Schema.Json), + uiOnly: Schema.optional(Schema.Boolean).pipe(Schema.withConstructorDefault(Effect.succeed(true))), +}); +export type PiUiStateUpdatedPayload = typeof PiUiStateUpdatedPayload.Type; + +const PiExtensionSlashCommandSnapshot = Schema.Struct({ + name: TrimmedNonEmptyStringSchema, + description: Schema.optional(Schema.String), + source: Schema.optional(TrimmedNonEmptyStringSchema), + sourceInfo: Schema.optional(Schema.Json), + input: Schema.optional(Schema.Json), +}); +export type PiExtensionSlashCommandSnapshot = typeof PiExtensionSlashCommandSnapshot.Type; + +const PiExtensionToolSnapshot = Schema.Struct({ + name: TrimmedNonEmptyStringSchema, + description: Schema.optional(Schema.String), + sourceInfo: Schema.optional(Schema.Json), +}); +export type PiExtensionToolSnapshot = typeof PiExtensionToolSnapshot.Type; + +export const PiExtensionConfiguredPayload = Schema.Struct({ + source: TrimmedNonEmptyStringSchema, + extensionPaths: Schema.Array(Schema.String), + slashCommands: Schema.Array(PiExtensionSlashCommandSnapshot), + tools: Schema.Array(PiExtensionToolSnapshot), + flags: Schema.Array(Schema.String), + models: Schema.optional(Schema.Array(Schema.Json)), + skills: Schema.optional(Schema.Array(Schema.Json)), +}); +export type PiExtensionConfiguredPayload = typeof PiExtensionConfiguredPayload.Type; + +export const PiExtensionDiagnosticPayload = Schema.Struct({ + source: TrimmedNonEmptyStringSchema, + message: TrimmedNonEmptyStringSchema, + severity: Schema.Literals(["info", "warning", "error"]), + visibility: Schema.optional(Schema.Literals(["main", "pi-panel", "debug", "hidden"])).pipe( + Schema.withConstructorDefault(Effect.succeed("pi-panel")), + ), + extensionPath: Schema.optional(TrimmedNonEmptyStringSchema), + event: Schema.optional(TrimmedNonEmptyStringSchema), + diagnosticKey: Schema.optional(TrimmedNonEmptyStringSchema), + repeatCount: Schema.optional(PositiveInt).pipe(Schema.withConstructorDefault(Effect.succeed(1))), + hiddenCount: Schema.optional(NonNegativeInt).pipe( + Schema.withConstructorDefault(Effect.succeed(0)), + ), + detail: Schema.optional(Schema.Json), + uiOnly: Schema.optional(Schema.Boolean).pipe(Schema.withConstructorDefault(Effect.succeed(true))), +}); +export type PiExtensionDiagnosticPayload = typeof PiExtensionDiagnosticPayload.Type; + const RuntimeWarningPayload = Schema.Struct({ message: TrimmedNonEmptyStringSchema, detail: Schema.optional(Schema.Unknown), @@ -970,6 +1051,29 @@ const ProviderRuntimeExtensionActivityEvent = Schema.Struct({ export type ProviderRuntimeExtensionActivityEvent = typeof ProviderRuntimeExtensionActivityEvent.Type; +const ProviderRuntimePiUiStateUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: PiUiStateUpdatedType, + payload: PiUiStateUpdatedPayload, +}); +export type ProviderRuntimePiUiStateUpdatedEvent = typeof ProviderRuntimePiUiStateUpdatedEvent.Type; + +const ProviderRuntimePiExtensionConfiguredEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: PiExtensionConfiguredType, + payload: PiExtensionConfiguredPayload, +}); +export type ProviderRuntimePiExtensionConfiguredEvent = + typeof ProviderRuntimePiExtensionConfiguredEvent.Type; + +const ProviderRuntimePiExtensionDiagnosticEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: PiExtensionDiagnosticType, + payload: PiExtensionDiagnosticPayload, +}); +export type ProviderRuntimePiExtensionDiagnosticEvent = + typeof ProviderRuntimePiExtensionDiagnosticEvent.Type; + const ProviderRuntimeWarningEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: RuntimeWarningType, @@ -1031,6 +1135,9 @@ export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeDeprecationNoticeEvent, ProviderRuntimeFilesPersistedEvent, ProviderRuntimeExtensionActivityEvent, + ProviderRuntimePiUiStateUpdatedEvent, + ProviderRuntimePiExtensionConfiguredEvent, + ProviderRuntimePiExtensionDiagnosticEvent, ProviderRuntimeWarningEvent, ProviderRuntimeErrorEvent, ]); diff --git a/packages/contracts/src/server.test.ts b/packages/contracts/src/server.test.ts index cae68e1f64..3ecc3bf765 100644 --- a/packages/contracts/src/server.test.ts +++ b/packages/contracts/src/server.test.ts @@ -71,4 +71,69 @@ describe("ServerProvider", () => { expect(parsed.continuation?.groupKey).toBe("codex:home:/Users/julius/.codex"); }); + + it("decodes Pi provider inventory metadata", () => { + const parsed = decodeServerProvider({ + instanceId: "pi", + driver: "pi", + enabled: true, + installed: true, + version: "0.73.0", + status: "ready", + auth: { + status: "authenticated", + }, + checkedAt: "2026-04-10T00:00:00.000Z", + models: [], + pi: { + extensionPaths: ["/Users/davis/.pi/agent/extensions/tps-tracker.ts"], + tools: [ + { + name: "search", + description: "Search docs", + sourceInfo: { path: "/Users/davis/.pi/agent/extensions/tps-tracker.ts" }, + }, + ], + flags: ["verbose"], + }, + }); + + expect(parsed.pi?.extensionPaths).toEqual(["/Users/davis/.pi/agent/extensions/tps-tracker.ts"]); + expect(parsed.pi?.tools[0]?.name).toBe("search"); + expect(parsed.pi?.tools[0]?.sourceInfo).toEqual({ + path: "/Users/davis/.pi/agent/extensions/tps-tracker.ts", + }); + expect(parsed.pi?.flags).toEqual(["verbose"]); + }); + + it("rejects non-JSON Pi provider inventory metadata", () => { + expect(() => + decodeServerProvider({ + instanceId: "pi", + driver: "pi", + enabled: true, + installed: true, + version: "0.73.0", + status: "ready", + auth: { + status: "authenticated", + }, + checkedAt: "2026-04-10T00:00:00.000Z", + models: [], + pi: { + extensionPaths: ["/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts"], + tools: [ + { + name: "search", + sourceInfo: { + path: "/Users/davis/.pi/agent/extensions/pi-mcp/src/index.ts", + baseDir: undefined, + }, + }, + ], + flags: [], + }, + }), + ).toThrow(); + }); }); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 15afea93ad..0b1812cdfd 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -79,6 +79,20 @@ export const ServerProviderSlashCommand = Schema.Struct({ }); export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type; +export const ServerProviderPiToolSnapshot = Schema.Struct({ + name: TrimmedNonEmptyString, + description: Schema.optional(Schema.String), + sourceInfo: Schema.optional(Schema.Json), +}); +export type ServerProviderPiToolSnapshot = typeof ServerProviderPiToolSnapshot.Type; + +export const ServerProviderPiMetadata = Schema.Struct({ + extensionPaths: Schema.Array(Schema.String), + tools: Schema.Array(ServerProviderPiToolSnapshot), + flags: Schema.Array(Schema.String), +}); +export type ServerProviderPiMetadata = typeof ServerProviderPiMetadata.Type; + export const ServerProviderSkill = Schema.Struct({ name: TrimmedNonEmptyString, description: Schema.optional(TrimmedNonEmptyString), @@ -185,6 +199,7 @@ export const ServerProvider = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed([])), ), skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + pi: Schema.optionalKey(ServerProviderPiMetadata), versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory), updateState: Schema.optionalKey(ServerProviderUpdateState), });