mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(providers): keep stats through merged messages and plugin imports, start Pi first-token timing at the request
A message the timeline merges from several chunks keeps the stats stamped on its last chunk. Plugin session imports carry the stats the plugin replayed, through the same history reader the other providers use. Steers queued together after an unclear turn stay unclear instead of attributing the final reply to the wrong turn. Pi measures time to first token from the request, not the first reply header.
This commit is contained in:
@@ -338,6 +338,20 @@ describe("turn metrics", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the stats on a message whose chunks the projection merges", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("a");
|
||||
store.append("a", { type: "user_message", text: "go" }, { turnId: "turn-1" });
|
||||
store.append("a", { type: "assistant_message", text: "Do" }, { turnId: "turn-1" });
|
||||
store.append("a", { type: "assistant_message", text: "ne" }, { turnId: "turn-1" });
|
||||
store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
|
||||
|
||||
const projected = store.fetch("a").rows;
|
||||
|
||||
expect(projected).toHaveLength(2);
|
||||
expect(projected[1]).toMatchObject({ item: { text: "Done" }, turnMetrics: metrics });
|
||||
});
|
||||
|
||||
it("restores stamped rows when a timeline is seeded from stored rows", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("live");
|
||||
|
||||
@@ -2888,6 +2888,63 @@ test("plugin provider import launches with runtime MCP servers and returns only
|
||||
}
|
||||
});
|
||||
|
||||
test("plugin provider import keeps the stats the plugin reported with its history", async () => {
|
||||
const turnMetrics = [{ label: "Model", value: "plugin-model" }];
|
||||
const sessionMetrics = [{ label: "Cost", value: "$1.23" }];
|
||||
const harness = createProviderHarness({
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.open" || input.history !== "replay") return false;
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: CAPABILITIES,
|
||||
restoration: "core",
|
||||
persistence: input.persistence ?? { version: 1, data: { token: "root" } },
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "user_message", id: "user-1", text: "go" },
|
||||
});
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "assistant_message", id: "answer-1", text: "Done" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "turn-1",
|
||||
state: "completed",
|
||||
metrics: turnMetrics,
|
||||
});
|
||||
emit({ type: "session.metrics", sessionId: input.sessionId, metrics: sessionMetrics });
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([harness.registration]);
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
const storedConfig = { provider: harness.registration.id, cwd: "/project" };
|
||||
try {
|
||||
const imported = await client.importSession!(
|
||||
{ providerHandleId: 'plugin:{"version":1,"data":{"token":"root"}}', cwd: "/project" },
|
||||
{ config: storedConfig, storedConfig },
|
||||
);
|
||||
expect(imported.sessionMetrics).toEqual(sessionMetrics);
|
||||
expect(imported.timeline.map((entry) => entry.turnMetrics ?? null)).toEqual([
|
||||
null,
|
||||
turnMetrics,
|
||||
]);
|
||||
await imported.session.close();
|
||||
} finally {
|
||||
await registry.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
const logger = createTestLogger();
|
||||
const harness = createProviderHarness();
|
||||
|
||||
@@ -72,6 +72,7 @@ import {
|
||||
createProviderEnv,
|
||||
type ProviderRuntimeSettings,
|
||||
} from "./provider-launch-config.js";
|
||||
import { ImportedHistory } from "./provider-session-import.js";
|
||||
import { readPluginOptionState } from "./plugin-provider-options.js";
|
||||
import type { RegisteredProviderDefinition } from "./provider-registry.js";
|
||||
import { runProviderTurn } from "./providers/provider-runner.js";
|
||||
@@ -1149,8 +1150,7 @@ class PluginAgentClient implements AgentClient {
|
||||
session,
|
||||
config: { ...context.storedConfig, provider: this.provider, cwd: input.cwd },
|
||||
persistence,
|
||||
timeline: session.timelineHistory(),
|
||||
providerSubagentEvents: session.subagentHistory(),
|
||||
...session.importedHistory(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1577,13 +1577,10 @@ class PluginAgentSession implements AgentSession {
|
||||
);
|
||||
}
|
||||
|
||||
subagentHistory(): NonNullable<ImportedProviderSession["providerSubagentEvents"]> {
|
||||
return this.history
|
||||
.read(this.provider)
|
||||
.filter(
|
||||
(event): event is Extract<AgentStreamEvent, { type: "provider_subagent" }> =>
|
||||
event.type === "provider_subagent",
|
||||
);
|
||||
importedHistory(): ReturnType<ImportedHistory["result"]> {
|
||||
const history = new ImportedHistory();
|
||||
for (const event of this.history.read(this.provider)) history.add(event);
|
||||
return history.result();
|
||||
}
|
||||
|
||||
attachChild(
|
||||
|
||||
@@ -41,9 +41,7 @@ export async function importSessionFromPersistence(input: {
|
||||
session,
|
||||
config: storedConfig,
|
||||
persistence: canonicalImportPersistence(persistence, session),
|
||||
timeline: history.timeline,
|
||||
...(history.sessionMetrics ? { sessionMetrics: history.sessionMetrics } : {}),
|
||||
providerSubagentEvents: history.providerSubagentEvents,
|
||||
...history,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,36 +82,51 @@ function buildImportPersistenceHandle(
|
||||
};
|
||||
}
|
||||
|
||||
async function collectImportedHistory(events: AsyncGenerator<AgentStreamEvent>): Promise<{
|
||||
timeline: ImportedTimelineEntry[];
|
||||
sessionMetrics?: AgentMetric[];
|
||||
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[];
|
||||
}> {
|
||||
const timeline: ImportedTimelineEntry[] = [];
|
||||
const providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
|
||||
let sessionMetrics: AgentMetric[] | undefined;
|
||||
for await (const event of events) {
|
||||
if (event.type === "provider_subagent") {
|
||||
providerSubagentEvents.push(event);
|
||||
continue;
|
||||
/** What an import keeps of a provider's replayed history, whichever way the events arrive. */
|
||||
export class ImportedHistory {
|
||||
readonly timeline: ImportedTimelineEntry[] = [];
|
||||
readonly providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] = [];
|
||||
sessionMetrics: AgentMetric[] | undefined;
|
||||
|
||||
add(event: AgentStreamEvent): void {
|
||||
switch (event.type) {
|
||||
case "provider_subagent":
|
||||
this.providerSubagentEvents.push(event);
|
||||
return;
|
||||
case "session_metrics_updated":
|
||||
this.sessionMetrics = sanitizeAgentMetrics(event.metrics);
|
||||
return;
|
||||
case "turn_completed": {
|
||||
const metrics = sanitizeAgentMetrics(event.metrics);
|
||||
const last = this.timeline.at(-1);
|
||||
if (last && metrics.length > 0) last.turnMetrics = metrics;
|
||||
return;
|
||||
}
|
||||
case "timeline":
|
||||
this.timeline.push({
|
||||
item: event.item,
|
||||
...(event.timestamp ? { timestamp: event.timestamp } : {}),
|
||||
});
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
if (event.type === "session_metrics_updated") {
|
||||
sessionMetrics = sanitizeAgentMetrics(event.metrics);
|
||||
continue;
|
||||
}
|
||||
if (event.type === "turn_completed") {
|
||||
const metrics = sanitizeAgentMetrics(event.metrics);
|
||||
const last = timeline.at(-1);
|
||||
if (last && metrics.length > 0) last.turnMetrics = metrics;
|
||||
continue;
|
||||
}
|
||||
if (event.type !== "timeline") {
|
||||
continue;
|
||||
}
|
||||
timeline.push({
|
||||
item: event.item,
|
||||
...(event.timestamp ? { timestamp: event.timestamp } : {}),
|
||||
});
|
||||
}
|
||||
return { timeline, sessionMetrics, providerSubagentEvents };
|
||||
|
||||
result(): Pick<
|
||||
ImportedProviderSession,
|
||||
"timeline" | "sessionMetrics" | "providerSubagentEvents"
|
||||
> {
|
||||
return {
|
||||
timeline: this.timeline,
|
||||
...(this.sessionMetrics ? { sessionMetrics: this.sessionMetrics } : {}),
|
||||
providerSubagentEvents: this.providerSubagentEvents,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function collectImportedHistory(events: AsyncGenerator<AgentStreamEvent>) {
|
||||
const history = new ImportedHistory();
|
||||
for await (const event of events) history.add(event);
|
||||
return history.result();
|
||||
}
|
||||
|
||||
@@ -2253,6 +2253,7 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
});
|
||||
return;
|
||||
case "turn_start":
|
||||
this.firstToken.requestSent(Date.now());
|
||||
this.activeTurnStarted = true;
|
||||
this.clearNoTurnBuffers();
|
||||
if (this.activeTurnStartedEmitted) {
|
||||
|
||||
@@ -111,6 +111,12 @@ describe("Pi first token timer", () => {
|
||||
timer.replyUpdated({ type: "thinking_delta", delta: "hmm" }, 2_050);
|
||||
expect(timer.replyEnded()).toBe(50);
|
||||
|
||||
// The request going out starts the clock; the reply's start arrives later, with the headers.
|
||||
timer.requestSent(5_000);
|
||||
timer.replyStarted(8_000);
|
||||
timer.replyUpdated({ type: "text_start" }, 8_050);
|
||||
expect(timer.replyEnded()).toBe(3_050);
|
||||
|
||||
// A reply whose start was not seen, or that never produced content, is not timed.
|
||||
timer.replyUpdated({ type: "text_start" }, 3_000);
|
||||
expect(timer.replyEnded()).toBeNull();
|
||||
@@ -207,7 +213,10 @@ describe("Pi metrics through the session", () => {
|
||||
{ label: "Model time", value: "4.0s" },
|
||||
// Tools ran from 101.5s to 104s.
|
||||
{ label: "Tool time", value: "2.5s" },
|
||||
{ label: "Average TTFT", value: "0.2s" },
|
||||
// The first reply's clock starts when the request went out (turn_start, 100.0s), before its
|
||||
// headers arrived: 0.8s. The second has no turn_start, so it starts at its message_start:
|
||||
// 0.1s.
|
||||
{ label: "Average TTFT", value: "0.5s" },
|
||||
{ label: "Steps", value: "2" },
|
||||
{ label: "Tokens", value: "2.0K ↑ · 1.2K ↓" },
|
||||
{ label: "Cache", value: "75%", tone: "ok" },
|
||||
|
||||
@@ -127,18 +127,23 @@ export function piSessionMetrics(
|
||||
const CONTENT_START_EVENTS = new Set(["text_start", "thinking_start", "toolcall_start"]);
|
||||
|
||||
/**
|
||||
* Times a live reply's first token: from the reply's start to its first content,
|
||||
* on the adapter's clock.
|
||||
* Times a live reply's first token, on the adapter's clock: from when the request went out
|
||||
* (`turn_start`) to the reply's first content. A reply's `message_start` only arrives once
|
||||
* the response headers have, so it stands in for the request only when no `turn_start` came.
|
||||
*/
|
||||
export class PiFirstTokenTimer {
|
||||
private startedAt: number | null = null;
|
||||
private firstTokenAt: number | null = null;
|
||||
|
||||
replyStarted(now: number): void {
|
||||
requestSent(now: number): void {
|
||||
this.startedAt = now;
|
||||
this.firstTokenAt = null;
|
||||
}
|
||||
|
||||
replyStarted(now: number): void {
|
||||
if (this.startedAt === null) this.requestSent(now);
|
||||
}
|
||||
|
||||
replyUpdated(event: { type: string; delta?: unknown }, now: number): void {
|
||||
if (this.startedAt === null || this.firstTokenAt !== null) return;
|
||||
const delta = typeof event.delta === "string" && event.delta.length > 0;
|
||||
|
||||
@@ -230,6 +230,20 @@ describe("replayed turns after a turn that ended on tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("replayed turns after steers queued together", () => {
|
||||
test("every prompt queued behind a turn that ended on tools shares its doubt", () => {
|
||||
const { out } = replay([
|
||||
{ role: "user", at: 0 },
|
||||
{ role: "assistant", step: step({ endedAt: 1_000 }), final: false, endedOnTools: true },
|
||||
{ role: "tool", run: [1_000, 1_500] },
|
||||
{ role: "user", at: 2_000 },
|
||||
{ role: "user", at: 2_100 },
|
||||
{ role: "assistant", step: step({ endedAt: 3_000 }), final: true },
|
||||
]);
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session metrics reporter", () => {
|
||||
test("reports only changes, starting from nothing reported", () => {
|
||||
const reported: unknown[] = [];
|
||||
|
||||
@@ -251,7 +251,10 @@ export class ReplayedTurns<Message> {
|
||||
observe(message: Message): AgentMetric[] {
|
||||
const prompt = this.reader.prompt(message);
|
||||
if (prompt) {
|
||||
const unclear = this.turn?.endedOnTools === true;
|
||||
// Prompts queued behind one another, with no reply between, share the first one's doubt.
|
||||
const unclear =
|
||||
this.turn !== null &&
|
||||
(this.turn.endedOnTools || (this.turn.unclear && this.turn.steps.length === 0));
|
||||
const closed = this.end();
|
||||
this.turn = this.open(prompt.startedAt);
|
||||
this.turn.unclear = unclear;
|
||||
|
||||
@@ -237,6 +237,8 @@ function mergeReasoningChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
seqEnd: entry.seqEnd,
|
||||
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
|
||||
collapsed: Array.from(collapsedKinds),
|
||||
// The turn's stats ride on its last row, which is the later chunk of a merged message.
|
||||
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user