Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions apps/server/src/chat/invoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ test("streams a fragmented Chat question, then repairs it within the same Planne
});

test.each(["new", "existing", "unanchored", "replayed", "changed", "discarded", "discarded-new"])(
"a rejected reply reports only durable captures the turn made or repeated (%s)",
"a flagged reply reports only durable captures the turn made or repeated (%s)",
async kind => {
let { context } = await setup();
let options = {
Expand Down Expand Up @@ -287,14 +287,14 @@ test.each(["new", "existing", "unanchored", "replayed", "changed", "discarded",
expect(turns).toBe(2);
let entries = context.chat.entries.map(entry => entry.text);
expect(entries).not.toContain("Decisions await Save.");
// A repair still flagged is the Planner's answer: the turn ends without a failure either way.
expect(context.chat.entries.some(entry => entry.turnFailure)).toBe(false);
if (kind === "new") {
expect(entries).toContain("Added 1 inline decision to the document.");
expect(entries.some(text => text?.includes("could not move"))).toBe(false);
} else if (kind === "replayed") {
expect(entries).toContain("1 inline decision is already in the document.");
expect(entries.some(text => text?.includes("could not move"))).toBe(false);
expect(context.plan.records.size).toBe(1);
} else expect(entries.some(text => text?.includes("could not move"))).toBe(true);
} else expect(entries.some(text => text?.includes("inline decision"))).toBe(false);
if (kind === "changed") {
expect(entries.some(text => text?.includes("already in the document"))).toBe(false);
expect(context.plan.records.size).toBe(1);
Expand Down Expand Up @@ -734,7 +734,7 @@ test("a failed foreground turn aborts late work and keeps a Planner that waits o
expect(planner.calls).toEqual(["destroy"]);
});

test("a reply that cannot move its questions into decisions fails the turn but keeps the session and its open question past 30 minutes", async () => {
test("a reply still asking after its repair ends the turn and keeps the session and its open question past 30 minutes", async () => {
let { context, user, backend } = await setup(configured(ATOMIC));
let planner = plannerSession();
let withdrawn = new AbortController();
Expand Down Expand Up @@ -779,8 +779,8 @@ test("a reply that cannot move its questions into decisions fails the turn but k
await context.chat.running;
await tick();
let said = () => context.chat.entries.map(entry => entry.text);
expect(said().some(text => text.includes("could not move its questions"))).toBe(true);
// Both replies were shown as they streamed; the turn says it could not move the question.
expect(context.chat.entries.some(entry => entry.turnFailure)).toBe(false);
// Both replies were shown as they streamed, and the second ends the turn.
expect(said().filter(text => text === "Which scope should the plan cover?")).toHaveLength(2);
expect(planner.calls).not.toContain("destroy");
expect(context.chat.retained).toBeDefined();
Expand All @@ -804,7 +804,7 @@ test("a reply that cannot move its questions into decisions fails the turn but k
* A Planner whose only open work is a question it asked: the session's own signal ends with the
* session, as a host tool's does under Atomic.
*/
async function askingPlanner(kind: "refused" | "settled" = "refused") {
async function askingPlanner(kind: "flagged" | "settled" = "flagged") {
let fixture = await setup(configured(ATOMIC));
let { context } = fixture;
let inputs = new PendingInputs();
Expand Down Expand Up @@ -850,15 +850,15 @@ async function askingPlanner(kind: "refused" | "settled" = "refused") {
};
}

test("a refused reply keeps a Planner that only waits on a question it asked, however long nobody answers, and lets it go once that ends", async () => {
test("a reply still asking after its repair keeps a Planner that only waits on a question it asked, however long nobody answers, and lets it go once that ends", async () => {
let { context, user, backend, planner, withdrawn, asked, status } = await askingPlanner();
try {
await Chat.invoke(context, user, "Plan it");
await context.chat.running;
await tick();
let said = () => context.chat.entries.map(entry => entry.text);
expect(said().some(text => text.includes("could not move its questions"))).toBe(true);
// Both replies were shown as they streamed; the turn says it could not move the question.
expect(context.chat.entries.some(entry => entry.turnFailure)).toBe(false);
// Both replies were shown as they streamed, and the second ends the turn.
expect(said().filter(text => text === "Which scope should the plan cover?")).toHaveLength(2);
expect(planner.calls).not.toContain("destroy");
expect(withdrawn.signal.aborted).toBe(false);
Expand All @@ -882,7 +882,7 @@ test("a refused reply keeps a Planner that only waits on a question it asked, ho
}
});

test("a Planner that ended its turn with a question still open is kept, not only after a refused reply", async () => {
test("a Planner that ended its turn with a question still open is kept, not only after a flagged reply", async () => {
let { context, user, planner, withdrawn, status } = await askingPlanner("settled");
await Chat.invoke(context, user, "Plan it");
await context.chat.running;
Expand Down
52 changes: 42 additions & 10 deletions apps/server/src/chat/reply-policy.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import { expectPlain } from "../testing/plain-words";
import { ToolBoundaryError } from "../harness/remote/link";
import { checkPlannerReply, PlannerReplyError, publishPlannerReplies } from "./reply-policy";
import { checkPlannerReply, publishPlannerReplies } from "./reply-policy";

import type { Decide } from "../conversation-plan/decisions";
import type { TextStreamPart, ToolSet } from "ai";
Expand Down Expand Up @@ -172,9 +172,7 @@ test.each([0.11, 0.5, 1])(
"a reply that asks for input (%s) stays shown and gets one repair step that moves its questions into decisions",
async p => {
let f = fixture([text("Tell me your preferred scope."), text("Which scope?")], verdict(p));
expect(await rejection(f.run())).toContain(
"could not move its questions into inline decisions",
);
expect(await warned(f.run())).toHaveLength(1);
expect(f.published).toEqual([
...text("Tell me your preferred scope."),
...text("Which scope?"),
Expand All @@ -193,6 +191,19 @@ async function rejection(run: Promise<unknown>): Promise<string> {
return message;
}

/** What a turn that ends normally logged, which no person reads. */
async function warned(run: Promise<unknown>): Promise<unknown[][]> {
let warnings: unknown[][] = [];
let warn = console.warn;
console.warn = (...args: unknown[]) => warnings.push(args);
try {
await run;
} finally {
console.warn = warn;
}
return warnings;
}

function said(f: ReturnType<typeof fixture>): string[] {
return f.published.filter(part => part.type === "text-delta").map(part => part.text);
}
Expand Down Expand Up @@ -232,21 +243,42 @@ test("a repair that answers without asking ends the turn with its own words", as
expect(said(f)).toEqual(["Which scope?", "I put the scope question beside the goal."]);
});

test("a repair still read as asking, with no card added or kept, ends the turn normally with the Planner's own words and a logged warning", async () => {
let saved: Part = {
type: "tool-result",
toolCallId: "edit-1",
toolName: "edit_plan",
input: {},
output: { ok: true, revision: 7 },
};
let first = "I saved the plan and its build graph. Want me to walk you through why it is split?";
let repaired =
"The plan and its build graph are saved. Happy to walk through the split if useful.";
let f = fixture([[saved, ...text(first)], text(repaired)], verdict(1));
f.options.capturedDecisions = () => 0;
f.options.keptDecisions = () => 0;
let warnings = await warned(f.run());
expect(f.prompts).toHaveLength(2);
expect(said(f)).toEqual([first, repaired]);
expect(warnings).toHaveLength(1);
expect(String(warnings[0]![0])).toContain("still asked for input in Chat after its repair");
});

test.each([0, -1, NaN, 1.5])(
"a repeated-decision count of %s cannot mask a rejected turn, and the failure keeps the session",
"a repeated-decision count of %s claims no decisions, so the Planner's reply ends the turn without a summary",
async count => {
let f = fixture([text("Which scope?"), text("Tell me the scope.")], verdict(1));
f.options.keptDecisions = () => count;
let failure = await f.run().catch(error => error);
expect(failure).toBeInstanceOf(PlannerReplyError);
expect(failure.message).toContain("could not move its questions");
expect(await warned(f.run())).toHaveLength(1);
expect(said(f)).toEqual(["Which scope?", "Tell me the scope."]);
},
);

test.each([0, -1, NaN, 1.5])("a capture count of %s cannot mask a rejected turn", async count => {
test.each([0, -1, NaN, 1.5])("a capture count of %s claims no decisions", async count => {
let f = fixture([text("Which scope?"), text("Tell me the scope.")], verdict(1));
f.options.capturedDecisions = () => count;
expect(await rejection(f.run())).toContain("could not move its questions");
expect(await warned(f.run())).toHaveLength(1);
expect(said(f)).toEqual(["Which scope?", "Tell me the scope."]);
});

test("a check that fails leaves the streamed reply standing, says nothing to the person, and only logs", async () => {
Expand Down
8 changes: 5 additions & 3 deletions apps/server/src/chat/reply-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ export async function checkPlannerReply(
* A text message reaches Chat as the model writes it, like any other part. Each finished message is checked
* meanwhile, without holding back what follows; a check that fails or runs out of time leaves the reply standing and
* is only logged. A reply the check finds asking for input in Chat is followed by one repair step, in which the Planner
* moves those questions into inline decision cards and ends with a factual summary.
* moves those questions into inline decision cards and ends with a factual summary. A repair the check still flags,
* with no card to show for it, stands as the Planner's answer and is only logged: its words are already in Chat, and
* failing the turn over their phrasing would report saved work as lost.
*/
export async function publishPlannerReplies(options: {
session: Pick<PlannerSession, "stream">;
Expand Down Expand Up @@ -237,7 +239,7 @@ export async function publishPlannerReplies(options: {
publish({ type: "text-end", id });
return;
}
throw new PlannerReplyError(
`${PLANNER_NAME} could not move its questions into inline decisions. Try again.`,
console.warn(
"[chat] a Planner reply still asked for input in Chat after its repair, and no decision card was added or kept; the reply stands.",
);
}
15 changes: 5 additions & 10 deletions apps/server/src/chat/threads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async function buildWorld(config: Record<string, string> = {}, extra: Partial<Ch
let emitExtra:
| ((emit: (part: Record<string, unknown>) => void) => Promise<void> | void)
| undefined;
/** Whether the session waits on a question it asked, which keeps it past a reply refused. */
/** Whether the session waits on a question it asked, which keeps it past a failed turn. */
let asking = false;

let fakeOpen: typeof openPlannerSession = async (_binding, options) => {
Expand Down Expand Up @@ -1009,16 +1009,13 @@ describe("Chat threads server", () => {
for (
let failure of [
{ name: "an unreachable agent", keepsSession: false },
{ name: "a refused reply that keeps its session", keepsSession: true },
{ name: "a failure while its session waits on a question", keepsSession: true },
]
) {
test(`a Retry after ${failure.name} keeps the unread notes under their cap, and gives every attempt the replayed notes before the unread ones`, async () => {
let unreadSaved: number[] = [];
let w: Awaited<ReturnType<typeof buildWorld>>;
w = await buildWorld(ATOMIC, {
...(failure.keepsSession
? { decide: decideReplying({ input: { type: "noul", noul: 1 } }) }
: {}),
modelChoice: async () => {
await w.context.onSessionMetaChanged!();
let saved = await w.storage.chatThreads.getSessionState(w.channel.id);
Expand All @@ -1034,11 +1031,9 @@ describe("Chat threads server", () => {

let failing = crypto.randomUUID();
if (failure.keepsSession) w.setAsking(true);
else {
w.setEmitExtra(() => {
throw new Error("503 Service Unavailable");
});
}
w.setEmitExtra(() => {
throw new Error("503 Service Unavailable");
});
let opened = w.forks.length;
await Threads.sendMessage(w.context, alice.ws, {
kind: "chat:send",
Expand Down
4 changes: 2 additions & 2 deletions docs/agent-connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -737,8 +737,8 @@ With `retry-turn`, every `turn` that a person's Chat message began names it:

- **`message`** is the id of the Chat message the turn answers, the same id the room sees. It is
absent from a turn no person's message began (a background job, a decision follow-up, an
instruction Chopin wrote). When Chopin asks the same session to repair a reply it withheld, that
second `turn` carries the same `message`, without `retry`.
instruction Chopin wrote). When Chopin asks the same session to repair a reply that asked for
input in Chat, that second `turn` carries the same `message`, without `retry`.
- **`retry: true`** says this turn runs `message` again after an earlier turn for it failed. Its
`prompt` is the message as it was first given, and its `attachments` the same files. Before
running it, the client drops from whatever it keeps across sessions or turns everything the
Expand Down
26 changes: 13 additions & 13 deletions docs/hosted-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,23 +180,23 @@ can appear in one batch. Cards stay open after the Planner finishes its turn,
and people can answer in any order. Only Save settles an answer. Repository facts need answers, not votes. Optional
exploration can remain provisional without becoming a Build blocker.

On every harness, Chat buffers each complete Planner text message and checks it
with the deployment's decisions classifier before publication. Requests for input
are withheld and the same session gets one continuation to create inline cards.
On every harness, Chat streams each Planner text message as it is written, then checks
it with the deployment's decisions classifier. A reply that asks for input in Chat
gets one continuation in the same session to move those questions into inline cards.
A continuation that repeats cards an earlier turn already created, by their stable
keys, counts as having created them only while those cards still hold their question:
open, reopened or answered. A key repeated for a different question or passage is
refused, and a card a person discarded, or that was cancelled or expired, counts for
nothing and is never recreated, so the turn still reports that it could not move its
questions.
Completed tools and the original request are not replayed. Failed, missing,
malformed or interrupted checks never publish unchecked prose; uncertain judgments
also withhold it. Chat prose therefore arrives after validation rather than token
by token. This is a semantic check and can misclassify language.
If both generated replies are withheld after the turn durably captured new inline
decisions, Chat reports their count in a fixed server-authored summary. It never
publishes the withheld text or claims the whole request succeeded. Without new
captured decisions, the turn still reports failure.
nothing and is never recreated.
Completed tools and the original request are not replayed. A check that fails or runs
out of time leaves the reply standing and is only logged. This is a semantic check and
can misclassify language.
If the check still flags the continuation, Chat adds a fixed server-authored count of
the inline decisions the turn durably captured, or repeated while they still hold their
question. With no card to show for it, the continuation stands as the Planner's answer
and the server logs a warning: its words are already in Chat, and failing the turn over
their phrasing would report work it saved as lost. A stream error or a tool boundary
stop still fails the turn.

An answer, correction, or contradictory finding should change the affected
prose and its anchors, followed by the next useful authorized action. Disagreement
Expand Down
Loading