Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let users cancel a goal (#2271)

Regan Bell795a33a4ce2a
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 62710ad65..8a1f6892a 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1925,6 +1925,19 @@ const apiRoutes: readonly WebRoute[] = [
);
},
},
+ {
+ method: "POST",
+ path: "/api/sessions/:id/goal/cancel",
+ handle: async (c) => {
+ const { res, user } = c;
+ return relayCore(
+ res,
+ "POST",
+ `/v1/sessions/${encodeURIComponent(c.params.id!)}/goal/cancel`,
+ JSON.stringify({ principalId: user }),
+ );
+ },
+ },
{
method: "POST",
path: "/api/sessions/:id/fork",
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 3128516cf..59955b916 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -90,6 +90,7 @@ import {
forkOriginDetails,
forkCutSeq,
forkSession,
+ cancelSessionGoal,
inheritedRefreshEntries,
inheritedTranscript,
loadInheritedTranscript,
@@ -187,7 +188,7 @@ import {
watchActivityLabel,
} from "./session-list";
import { liveTurnThreadRef } from "./working-dot";
-import { goalElapsedLabel, goalObjectiveLabel, goalWorkedLabel, latestGoal } from "./goal-strip";
+import { goalElapsedLabel, goalObjectiveLabel, goalWorkedLabel, latestGoal, type GoalStripState } from "./goal-strip";
import {
ackKey,
peekLines,
@@ -277,6 +278,7 @@ export function createChatSurface(
const transcriptFetcher = dependencies.fetchTranscript ?? fetchTranscript;
const sessionOpener = dependencies.openSession ?? openSession;
+ const goalCancels = new Map<string, "pending" | "done">();
const chatState = {
agent: null as Agent | null,
host: null as HTMLElement | null,
@@ -1856,22 +1858,23 @@ export function createChatSurface(
}
if (role === "system-note") {
const note = message as unknown as HistorySystemNote;
- const who = note.speaker ?? "The user";
- return html`
+ const row = (body: TemplateResult) => html`
<article
class="message-row system-note-row"
data-index=${index}
data-entry-seqs=${messageEntrySeqs(message).join(" ")}
>
- <div class="system-note">
- ${
- note.action === "deleted"
- ? html`${who} deleted their message`
- : html`${who} edited their message: <span class="system-note-text">${note.content}</span>`
- }
- </div>
+ <div class="system-note">${body}</div>
</article>
`;
+ if (note.note === "goal_cancelled")
+ return row(html`Goal cancelled: <span class="system-note-text">${goalObjectiveLabel(note.content)}</span>`);
+ const who = note.speaker ?? "The user";
+ return row(
+ note.action === "deleted"
+ ? html`${who} deleted their message`
+ : html`${who} edited their message: <span class="system-note-text">${note.content}</span>`,
+ );
}
if (role === "assistant") {
const msg = message as AssistantMessage;
@@ -2666,10 +2669,30 @@ export function createChatSurface(
`;
}
+ async function cancelGoal(agent: Agent, goal: GoalStripState): Promise<void> {
+ const sessionId = chatState.sessionId;
+ const key = `${sessionId}:${goal.createdAt}`;
+ if (!sessionId || goalCancels.has(key)) return;
+ goalCancels.set(key, "pending");
+ drawActiveChat(agent);
+ try {
+ await cancelSessionGoal(sessionId);
+ goalCancels.set(key, "done");
+ if (agent === chatState.agent) await refreshTranscriptFromEntries(agent);
+ } catch (err) {
+ goalCancels.delete(key);
+ ctx.composer.state.error = errMessage(err, "Could not cancel the goal.");
+ } finally {
+ if (agent === chatState.agent) drawActiveChat(agent);
+ }
+ }
+
function goalStrip(agent: Agent): TemplateResult | typeof nothing {
const messages = visibleMessages(agent);
const goal = latestGoal(messages);
if (!goal) return nothing;
+ const cancel = goalCancels.get(`${chatState.sessionId}:${goal.createdAt}`);
+ if (cancel === "done") return nothing;
const { workedMs, paused: stopped } = goalWorked(messages, goal);
const paused = goal.status === "paused" || (goal.status === "active" && stopped);
if (goal.status !== "active" && !paused) return nothing;
@@ -2682,6 +2705,16 @@ export function createChatSurface(
<span class="goal-strip-title">${title}</span>
<span class="goal-strip-objective" dir="auto">${goalObjectiveLabel(goal.objective)}</span>
<span class="goal-strip-meta">${goalWorkedLabel(workedMs, goal.floor)}</span>
+ <button
+ type="button"
+ class="chip-x"
+ aria-label="Cancel goal"
+ ${tip("Cancel goal")}
+ ?disabled=${cancel === "pending"}
+ @click=${() => void cancelGoal(agent, goal)}
+ >
+ ${icon(X, 13)}
+ </button>
</section>
`;
}
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index ebd9bf52d..1a81c1d17 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -392,6 +392,10 @@ export async function regenerateTitle(id: string): Promise<{ title: string | nul
export async function detachSession(id: string): Promise<{ detached: true }> {
return api<{ detached: true }>(`/api/sessions/${encodeURIComponent(id)}/detach`, { method: "POST" });
}
+
+export async function cancelSessionGoal(id: string): Promise<{ cancelled: true }> {
+ return api<{ cancelled: true }>(`/api/sessions/${encodeURIComponent(id)}/goal/cancel`, { method: "POST" });
+}
export interface SessionEntry {
type:
| "user"
@@ -1740,7 +1744,7 @@ function subagentMailOf(payload: unknown): SubagentMailRef | undefined {
return { title: xmlAttrUnescape(m[1]!), sessionId: m[2]!, kind: m[3]! };
}
-export interface HistorySystemNote {
+interface MessageRevisionNote {
role: "system-note";
note: "message_revision";
action: "edited" | "deleted";
@@ -1750,6 +1754,15 @@ export interface HistorySystemNote {
timestamp?: number;
}
+interface GoalCancelledNote {
+ role: "system-note";
+ note: "goal_cancelled";
+ content: string;
+ timestamp?: number;
+}
+
+export type HistorySystemNote = MessageRevisionNote | GoalCancelledNote;
+
export interface HistoryApprovalDecision {
role: "approval-decision";
requestId?: string;
@@ -1821,7 +1834,13 @@ export function messagesWithStreaming(messages: AgentMessage[], streaming?: Agen
});
}
-function messageRevisionPayload(payload: unknown): HistorySystemNote | null {
+function goalCancelledPayload(payload: unknown): GoalCancelledNote | null {
+ const p = payload as { kind?: unknown; cancelledBy?: unknown; goal?: { objective?: unknown } | null } | null;
+ if (p?.kind !== "goal" || typeof p.cancelledBy !== "string" || typeof p.goal?.objective !== "string") return null;
+ return { role: "system-note", note: "goal_cancelled", content: p.goal.objective };
+}
+
+function messageRevisionPayload(payload: unknown): MessageRevisionNote | null {
const p = payload as { kind?: unknown; action?: unknown; ts?: unknown; text?: unknown; name?: unknown } | null;
if (p?.kind !== "message_revision") return null;
if (p.action !== "edited" && p.action !== "deleted") return null;
@@ -2109,6 +2128,13 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
} else if (e.type === "delivery") {
appendDeliveryFiles(deliveredFilesFromAttachments(payload?.files));
} else if (e.type === "system") {
+ const goalNote = goalCancelledPayload(e.payload);
+ if (goalNote) {
+ spillHeldPosts();
+ flushWork("", e.createdAt);
+ out.push({ ...goalNote, timestamp: e.createdAt } as unknown as AgentMessage);
+ continue;
+ }
const revision = messageRevisionPayload(e.payload);
if (revision) {
spillHeldPosts();
diff --git a/plugins/web-ui/src/goal-strip.ts b/plugins/web-ui/src/goal-strip.ts
index 804bb0c3e..d43109e0f 100644
--- a/plugins/web-ui/src/goal-strip.ts
+++ b/plugins/web-ui/src/goal-strip.ts
@@ -1,6 +1,6 @@
export interface GoalStripState {
objective: string;
- status: "active" | "paused" | "complete";
+ status: "active" | "paused" | "complete" | "cancelled";
floor?: string;
createdAt: number;
}
@@ -11,6 +11,8 @@ interface ActivityLike {
}
interface MessageLike {
+ role?: string;
+ note?: string;
work?: { activity?: ActivityLike[] };
}
@@ -27,7 +29,7 @@ function snapshotFrom(payload: unknown): GoalStripState | null | undefined {
};
if (typeof goal !== "object" || typeof goal.objective !== "string" || !goal.objective.trim()) return undefined;
const status = goal.status;
- if (status !== "active" && status !== "paused" && status !== "complete") return undefined;
+ if (status !== "active" && status !== "paused" && status !== "complete" && status !== "cancelled") return undefined;
const floor = goalFloorLabel(goal.floor ?? null);
const createdAt = typeof goal.createdAt === "number" ? goal.createdAt : Date.now();
return {
@@ -41,6 +43,10 @@ function snapshotFrom(payload: unknown): GoalStripState | null | undefined {
export function latestGoal(messages: readonly unknown[]): GoalStripState | null {
let latest: GoalStripState | null = null;
for (const message of messages) {
+ if ((message as MessageLike).role === "system-note" && (message as MessageLike).note === "goal_cancelled") {
+ latest = null;
+ continue;
+ }
const activity = (message as MessageLike).work?.activity;
if (!activity) continue;
for (const item of activity) {
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index eba2eb400..8a0606c28 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -10074,6 +10074,10 @@ h3.ambient-field-label {
flex: none;
opacity: 0.75;
}
+.goal-strip .chip-x {
+ flex: none;
+ margin-left: auto;
+}
.file-chip-group {
display: inline-flex;
diff --git a/plugins/web-ui/test/goal-strip.test.ts b/plugins/web-ui/test/goal-strip.test.ts
index 965ca86c8..f81ebc148 100644
--- a/plugins/web-ui/test/goal-strip.test.ts
+++ b/plugins/web-ui/test/goal-strip.test.ts
@@ -7,6 +7,11 @@ import {
goalObjectiveLabel,
latestGoal,
} from "../src/goal-strip.ts";
+import { entriesToMessages, type SessionEntry } from "../src/core-bridge.ts";
+
+const MODEL = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Parameters<
+ typeof entriesToMessages
+>[1];
function msg(activity: Array<{ type: string; payload: unknown }>): unknown {
return { role: "assistant", work: { status: "working", activity } };
@@ -70,3 +75,35 @@ test("worked time leads the label, the floor follows", () => {
assert.equal(goalWorkedLabel(720_000, "20m"), "12m worked · 20m floor");
assert.equal(goalWorkedLabel(45_000), "45s worked");
});
+
+test("a goal cancelled from the goal bar closes the strip and leaves one note in the transcript", () => {
+ const goal = record("active");
+ const entries: SessionEntry[] = [
+ { type: "user", payload: { text: "work for 20 minutes" }, createdAt: 900 },
+ { type: "tool_call", payload: { tool: "goal", action: "create", callId: "c1" }, createdAt: 1000 },
+ { type: "tool_result", payload: { tool: "goal", action: "create", goal, callId: "c1" }, createdAt: 1001 },
+ { type: "system", payload: { kind: "goal", goal: record("paused") }, createdAt: 1002 },
+ { type: "assistant", payload: { text: "(stopped)", stopped: true }, createdAt: 1003 },
+ { type: "system", payload: { kind: "goal", goal: record("cancelled"), cancelledBy: "U1" }, createdAt: 1004 },
+ ];
+ const messages = entriesToMessages(entries, MODEL);
+ assert.equal(latestGoal(messages), null);
+ const notes = messages.filter((m) => (m as { role?: string }).role === "system-note");
+ assert.deepEqual(
+ notes.map((n) => ({ ...(n as object) })),
+ [{ role: "system-note", note: "goal_cancelled", content: "work for 20 minutes", timestamp: 1004 }],
+ );
+});
+
+test("a goal the agent cancelled at the user's request closes the strip without a note", () => {
+ const entries: SessionEntry[] = [
+ { type: "user", payload: { text: "cancel the goal" }, createdAt: 900 },
+ { type: "tool_result", payload: { tool: "goal", action: "create", goal: record("active") }, createdAt: 1000 },
+ { type: "tool_result", payload: { tool: "goal", action: "update", goal: record("cancelled") }, createdAt: 1001 },
+ { type: "system", payload: { kind: "goal", goal: record("cancelled") }, createdAt: 1002 },
+ { type: "assistant", payload: { text: "Cancelled the goal." }, createdAt: 1003 },
+ ];
+ const messages = entriesToMessages(entries, MODEL);
+ assert.equal(latestGoal(messages)?.status, "cancelled");
+ assert.ok(!messages.some((m) => (m as { role?: string }).role === "system-note"));
+});
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index 5dbb9a654..3f05ab753 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -8,11 +8,23 @@ import type { PendingApprovalRecord } from "../types.ts";
import { orgId as orgIdOf } from "../config.ts";
import { parseScopeId, scopeId, type ScopeId } from "../types.ts";
import { fileArtifactId, artifactPath } from "../files/file-artifact-store.ts";
-import { entryWithinTenure, transcriptEntries, windowedTranscript } from "../sessions/session-store.ts";
+import {
+ acquireLeaseWithin,
+ appendEntryOutsideTurn,
+ entryWithinTenure,
+ transcriptEntries,
+ windowedTranscript,
+} from "../sessions/session-store.ts";
import { createTranscriptSource } from "../harness/tape-projection.ts";
import { appendCoverageImport } from "../harness/replay.ts";
import { swallowAs } from "../util/errors.ts";
-import { latestGoalRecord } from "../harness/goal.ts";
+import {
+ cancelGoal,
+ goalCancelledNote,
+ goalSnapshotPayload,
+ latestGoalRecord,
+ rehydrateOpenGoal,
+} from "../harness/goal.ts";
import { SEARCH_HIT_LIMIT, entrySearchText, searchSnippet, searchTerms } from "../sessions/entry-search.ts";
import { supportsProcessSessions } from "../sandbox/sandbox.ts";
import { processIsGone } from "../sandbox/process-poll.ts";
@@ -52,6 +64,7 @@ function coversTailWindow(entries: readonly { type: string }[], tailTurns: numbe
}
const GOAL_LOOKBACK_ENTRIES = 2000;
+const GOAL_CANCEL_LEASE_WAIT_MS = 30_000;
export function createSessionMethods(
deps: AppDeps,
@@ -88,6 +101,7 @@ export function createSessionMethods(
| "authorizesCapabilityScope"
| "updateSession"
| "detachSession"
+ | "cancelSessionGoal"
| "regenerateTitle"
| "spawnSession"
| "discardSession"
@@ -106,6 +120,7 @@ export function createSessionMethods(
const {
sessionsForViewer,
sessionForViewer,
+ mayWriteSession,
managedProjectMembership,
filesForViewer,
canUseContext,
@@ -873,6 +888,43 @@ export function createSessionMethods(
: detach();
},
+ async cancelSessionGoal(sessionId, principalId) {
+ const session = await sessionForViewer(sessionId, principalId);
+ if (!session || !(await mayWriteSession(principalId, session))) return null;
+ const openGoal = async () =>
+ rehydrateOpenGoal(
+ (await deps.sessions.getRecentEntries([session.id], GOAL_LOOKBACK_ENTRIES)).get(session.id) ?? [],
+ );
+ const before = await openGoal();
+ if (!before) return { cancelled: false as const, reason: "no_open_goal" as const };
+ let { lease } = await deps.sessions.acquireLease(session.id, "backfill");
+ if (!lease) {
+ if (before.status === "active")
+ for (const run of await deps.runs.inFlightForThread(session.threadRef))
+ if (run.status === "running") await deps.signals?.send(run.id, { kind: "abort" });
+ ({ lease } = await acquireLeaseWithin(deps.sessions, session.id, "backfill", GOAL_CANCEL_LEASE_WAIT_MS));
+ }
+ if (!lease) return { cancelled: false as const, reason: "busy" as const };
+ try {
+ const goal = await openGoal();
+ if (!goal) return { cancelled: false as const, reason: "no_open_goal" as const };
+ cancelGoal(goal, "Cancelled from the goal bar.");
+ await appendEntryOutsideTurn(
+ deps.sessions,
+ lease,
+ {
+ type: "system",
+ payload: { ...goalSnapshotPayload(goal), cancelledBy: principalId },
+ scopeLabel: session.scopeId,
+ },
+ () => goalCancelledNote(goal),
+ );
+ return { cancelled: true as const };
+ } finally {
+ await deps.sessions.releaseLease(lease);
+ }
+ },
+
async regenerateTitle(sessionId, principalId) {
const session = await sessionForViewer(sessionId, principalId);
if (!session) return null;
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 0945e2008..bacabe411 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -396,6 +396,10 @@ export interface App {
): Promise<Session | null>;
regenerateTitle(sessionId: string, principalId: string): Promise<{ title: string | null } | null>;
detachSession(sessionId: string, principalId: string): Promise<{ detached: true } | null>;
+ cancelSessionGoal(
+ sessionId: string,
+ principalId: string,
+ ): Promise<{ cancelled: true } | { cancelled: false; reason: "no_open_goal" | "busy" } | null>;
spawnSession(principalId: string, opts: { scopeId: ScopeId; title?: string }): Promise<{ session: Session } | null>;
discardSession(sessionId: string, principalId: string): Promise<boolean>;
forkSession(
diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.ts
index d02ba6165..637ce18ca 100644
--- a/src/api/routes/surface.ts
+++ b/src/api/routes/surface.ts
@@ -86,6 +86,25 @@ async function detachSession(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, out);
}
+async function cancelSessionGoal(ctx: ApiCtx): Promise<void> {
+ const { res, app, body } = ctx;
+ const principalId = (body as { principalId?: unknown }).principalId;
+ if (typeof principalId !== "string" || !principalId) {
+ return sendJson(res, 400, { error: "bad_request", message: "principalId required" });
+ }
+ const out = await app.cancelSessionGoal(ctx.params.id!, principalId);
+ if (!out) return sendJson(res, 404, { error: "not_found" });
+ if (!out.cancelled)
+ return sendJson(res, 409, {
+ error: out.reason,
+ message:
+ out.reason === "busy"
+ ? "The conversation is still finishing a reply. Try again in a moment."
+ : "This conversation has no active or paused goal to cancel.",
+ });
+ return sendJson(res, 200, out);
+}
+
async function forkSession(ctx: ApiCtx): Promise<void> {
const { res, app, body } = ctx;
const id = ctx.params.id!;
@@ -1308,6 +1327,7 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/sessions/:id/title", auth: "source", handle: regenerateSessionTitle },
{ method: "POST", path: "/v1/sessions/:id/fork", auth: "source", handle: forkSession },
{ method: "POST", path: "/v1/sessions/:id/detach", auth: "source", handle: detachSession },
+ { method: "POST", path: "/v1/sessions/:id/goal/cancel", auth: "source", handle: cancelSessionGoal },
{ method: "GET", path: "/v1/sessions/:id/approvals", auth: "source", handle: listSessionApprovals },
{ method: "GET", path: "/v1/sessions/:id/background", auth: "source", handle: getSessionBackground },
{
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index cb3bacf75..76b008116 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -58,6 +58,7 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/sessions/:id/title", { in: "body", name: "principalId" }),
pat("POST", "/v1/sessions/:id/fork", { in: "body", name: "principalId" }),
pat("POST", "/v1/sessions/:id/detach", { in: "body", name: "principalId" }),
+ pat("POST", "/v1/sessions/:id/goal/cancel", { in: "body", name: "principalId" }),
pat("GET", "/v1/sessions", { in: "query", name: "principalId" }),
pat("GET", "/v1/resources/search", { in: "query", name: "principalId" }),
pat("GET", "/v1/contexts", { in: "query", name: "principalId" }),
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index b3f23883f..0e1b0431f 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -27,8 +27,10 @@ import { BOT_MODES } from "../surface-cache/channel-policy-store.ts";
import { headSlice, tailSlice } from "../util/text.ts";
import {
applyGovernorVerdict,
+ cancelGoal,
createGoalRecord,
goalFloorMeter,
+ goalIsOpen,
goalReport,
GOAL_STEP_BACK_PROMPT,
type GoalGovernor,
@@ -109,6 +111,7 @@ export interface ToolContextRef {
silentRequested?: boolean;
goal?: GoalRecord | null;
+ goalOpenedThisTurn?: boolean;
goalRound?: number;
@@ -3907,11 +3910,13 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
async execute(callId, params) {
const p = params as { objective: string; floor?: Record<string, number>; token_cap?: number };
await recordCall(callId, { tool: "goal", action: "create", objective: p.objective });
- if (ref.goal && (ref.goal.status === "active" || ref.goal.status === "paused")) {
+ if (goalIsOpen(ref.goal)) {
return recordCoreAuthoredResult(
callId,
{ tool: "goal", action: "create", error: "goal_exists" },
- text("A goal is already registered (active or paused) — goal action get shows it."),
+ text(
+ 'A goal is already registered (active or paused) — goal action get shows it. If the user asked to replace it, cancel it first (goal action update "cancel").',
+ ),
true,
);
}
@@ -3931,6 +3936,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
);
}
ref.goal = record;
+ ref.goalOpenedThisTurn = true;
return recordCoreAuthoredResult(
callId,
{ tool: "goal", action: "create", goal: record },
@@ -3968,12 +3974,14 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"workspace files you name in `files` (the harness reads them for it — name deliverables, never paste them into the note), and " +
"decides; if it rejects, the goal stays active and its reasons come back to you. You cannot block or pause a goal; " +
'only the user stops it. A paused goal resumes (status "resume") only when the person in this turn explicitly asks ' +
- "to resume it; never resume one on your own initiative. Resume keeps the objective, floor and cap.",
+ "to resume it; never resume one on your own initiative. Resume keeps the objective, floor and cap. " +
+ 'Cancel (status "cancel") ends an active or paused goal without completing it, only when the person in this turn ' +
+ "explicitly asks to cancel, drop or replace it; never to escape unfinished work.",
parameters: Type.Object({
- status: Type.Union([Type.Literal("complete"), Type.Literal("resume")]),
+ status: Type.Union([Type.Literal("complete"), Type.Literal("resume"), Type.Literal("cancel")]),
note: Type.String({
description:
- "complete: the concrete evidence (commands, output, results, links) that proves the objective is achieved. resume: quote the user's request to resume.",
+ "complete: the concrete evidence (commands, output, results, links) that proves the objective is achieved. resume or cancel: quote the user's request.",
}),
files: Type.Optional(
Type.Array(Type.String(), {
@@ -3984,8 +3992,13 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
sandbox_id: sandboxSelector("Sandbox holding `files`; omit for the default."),
}),
async execute(callId, params) {
- const p = params as { status?: "complete" | "resume"; note: string; files?: string[]; sandbox_id?: string };
- const status = p.status === "resume" ? "resume" : "complete";
+ const p = params as {
+ status?: "complete" | "resume" | "cancel";
+ note: string;
+ files?: string[];
+ sandbox_id?: string;
+ };
+ const status = p.status === "resume" || p.status === "cancel" ? p.status : "complete";
await recordCall(callId, {
tool: "goal",
action: "update",
@@ -3993,6 +4006,34 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(p.note ? { note: p.note } : {}),
});
const goal = ref.goal;
+ if (status === "cancel") {
+ if (!goalIsOpen(goal)) {
+ return recordCoreAuthoredResult(
+ callId,
+ { tool: "goal", action: "update", error: "no_open_goal" },
+ text("No active or paused goal to cancel."),
+ true,
+ );
+ }
+ if (ref.current?.humanTurn !== true || (ref.goalRound ?? 0) > 0 || ref.goalOpenedThisTurn) {
+ return recordCoreAuthoredResult(
+ callId,
+ { tool: "goal", action: "update", error: "human_required" },
+ text(
+ "Only the user's own message can cancel a goal, and the message you are answering is not one that came after this goal started (it is a keep-going prompt, an automated run, or the goal was started or resumed this turn). The goal is unchanged. If the user asked to cancel, tell them to use the cancel button on the goal bar, or to stop this reply and ask again.",
+ ),
+ true,
+ );
+ }
+ cancelGoal(goal, p.note);
+ return recordCoreAuthoredResult(
+ callId,
+ { tool: "goal", action: "update", goal },
+ text(
+ "The goal is cancelled at the user's request: it is no longer enforced and was not completed. A new goal can be registered now if the user asked for one.",
+ ),
+ );
+ }
if (status === "resume") {
if (goal?.status !== "paused") {
return recordCoreAuthoredResult(
@@ -4016,6 +4057,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
}
goal.status = "active";
goal.updatedAt = goal.activeSince = Date.now();
+ ref.goalOpenedThisTurn = true;
delete goal.pauseReason;
delete goal.governor;
return recordCoreAuthoredResult(
@@ -4222,7 +4264,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
async execute(callId, params) {
const request = params as RuntimeRequest;
await recordCall(callId, { tool: "runtime", ...request });
- if (request.action !== "get" && ref.goal && (ref.goal.status === "active" || ref.goal.status === "paused")) {
+ if (request.action !== "get" && goalIsOpen(ref.goal)) {
return recordCoreAuthoredResult(
callId,
{ tool: "runtime", error: "goal_in_progress" },
diff --git a/src/harness/goal.ts b/src/harness/goal.ts
index aa61ec009..3e07e40c5 100644
--- a/src/harness/goal.ts
+++ b/src/harness/goal.ts
@@ -31,7 +31,7 @@
import type { LlmCallUsage } from "../sessions/session-store.ts";
import { type GrindBudget, type GrindMeter, grindState } from "./grind.ts";
-type GoalStatus = "active" | "paused" | "complete";
+type GoalStatus = "active" | "paused" | "complete" | "cancelled";
export interface GoalRecord {
objective: string;
@@ -48,6 +48,7 @@ export interface GoalRecord {
/** When the user last resumed the goal; time before it (while paused) never counts. */
activeSince?: number;
completionNote?: string;
+ cancelNote?: string;
/** The governor's last verdict; a pause is only honored right after a step back. */
governor?: GovernorVerdict;
/** Why the governor paused the goal: the question waiting on the user. */
@@ -148,7 +149,7 @@ export function goalContinuationPrompt(goal: GoalRecord, meter: GrindMeter): str
`- Derive the concrete requirements from the objective; verify each against authoritative current state (files, command output, test results), not memory or intent.`,
`- Do not redefine success around a smaller, easier, or merely test-passing subset. A narrow check never supports a broad claim.`,
`- Uncertain or indirect evidence means NOT done: gather stronger evidence or keep working.`,
- `There is no other way out: you cannot pause, block or abandon this goal, and going quiet does not end it — only the user can stop it. If you feel stuck, that is the signal to change approach: re-read the objective, question your assumptions, try a different method or tool, or break the problem down differently. An independent governor reviews your recent work periodically and decides whether a blocker genuinely needs the user. Keep working.`,
+ `There is no other way out: you cannot pause, block or abandon this goal, and going quiet does not end it — only the user can stop or cancel it. If you feel stuck, that is the signal to change approach: re-read the objective, question your assumptions, try a different method or tool, or break the problem down differently. An independent governor reviews your recent work periodically and decides whether a blocker genuinely needs the user. Keep working.`,
`If the objective is verifiably achieved, request completion with goal action update "complete" and a note carrying the concrete evidence; a fresh verifier decides from that note alone. Otherwise go deeper on the least-examined requirement now.`,
]
.filter(Boolean)
@@ -206,7 +207,8 @@ export function goalPausedNote(goal: GoalRecord): string {
`[goal] This session has a PAUSED goal (paused when a turn was stopped or by request):\n` +
`<objective>\n${escapeTags(goal.objective)}\n</objective>\n` +
`Do not pursue it and do not treat it as enforced. If the user's message explicitly asks to resume it, ` +
- `call goal action update with status "resume"; never resume it on your own initiative.`
+ `call goal action update with status "resume"; if it explicitly asks to cancel, drop or replace it, call goal action update with status "cancel". ` +
+ `Never do either on your own initiative.`
);
}
@@ -216,7 +218,7 @@ export function goalSteeringNote(goal: GoalRecord): string {
`[goal] This session has an active goal registered earlier (status: active` +
(goal.capTokens ? `, tokens ${goal.tokensUsed}/${goal.capTokens}` : "") +
`):\n<objective>\n${escapeTags(goal.objective)}\n</objective>\n` +
- `Unless this message changes or drops the goal, weigh it in everything you do this turn; use goal action get / goal action update to inspect or close it. Only the user stopping it, or goal action update "complete" once it is achieved, ends it.`
+ `Unless this message changes or drops the goal, weigh it in everything you do this turn; use goal action get / goal action update to inspect or close it. Only the user stopping or cancelling it, or goal action update "complete" once it is achieved, ends it.`
);
}
@@ -349,6 +351,10 @@ export function reviveGoalRecord(goal: GoalRecord): GoalRecord {
};
}
+export function goalIsOpen(goal: GoalRecord | null | undefined): goal is GoalRecord {
+ return goal?.status === "active" || goal?.status === "paused";
+}
+
/**
* Recover the session's open goal from persisted history, newest snapshot
* first. Only an open (active/paused) goal survives turns: a terminal
@@ -358,7 +364,19 @@ export function reviveGoalRecord(goal: GoalRecord): GoalRecord {
*/
export function rehydrateOpenGoal(history: ReadonlyArray<{ type: string; payload?: unknown }>): GoalRecord | null {
const goal = latestGoalRecord(history);
- return goal && (goal.status === "active" || goal.status === "paused") ? reviveGoalRecord(goal) : null;
+ return goalIsOpen(goal) ? goal : null;
+}
+
+export function cancelGoal(goal: GoalRecord, note: string, now = Date.now()): void {
+ goal.status = "cancelled";
+ goal.updatedAt = now;
+ goal.cancelNote = note;
+ delete goal.pauseReason;
+ delete goal.governor;
+}
+
+export function goalCancelledNote(goal: GoalRecord): string {
+ return `[goal] The user cancelled this goal; it is no longer enforced and must not be pursued:\n<objective>\n${escapeTags(goal.objective)}\n</objective>`;
}
export function latestGoalEntry<T extends { type: string; payload?: unknown }>(entries: ReadonlyArray<T>): T | null {
diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.ts
index 0c79c1d20..494d1aa97 100644
--- a/src/harness/harness-shared.ts
+++ b/src/harness/harness-shared.ts
@@ -118,6 +118,7 @@ export function harnessToolContext(turn: HarnessTurnInput): ToolContextRef {
silentRequested: false,
pollFire: Boolean(turn.pollFire),
goal: turn.goal ?? rehydrateOpenGoal(turn.history),
+ ...(turn.goal || turn.continueTurn ? { goalRound: 1 } : {}),
emit: turn.emit,
scopeLabel: turn.scopeLabel,
orgScopeId: turn.orgScopeId,
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index 1cea8ba63..558a3da25 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -1953,7 +1953,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
if (!entry.ref.goal) entry.ref.goal = rehydrateOpenGoal(turn.history);
entry.ref.goalMeter = grindMeter;
- entry.ref.goalRound = 0;
+ entry.ref.goalRound = turn.continueTurn ? 1 : 0;
const activeGoalAtStart = entry.ref.goal?.status === "active" ? entry.ref.goal : null;
const pausedGoalAtStart = entry.ref.goal?.status === "paused" ? entry.ref.goal : null;
const goalNote = (() => {
diff --git a/src/runs/turn-stream.ts b/src/runs/turn-stream.ts
index 9288f3705..fa98acdcc 100644
--- a/src/runs/turn-stream.ts
+++ b/src/runs/turn-stream.ts
@@ -1,6 +1,6 @@
export interface GoalView {
objective: string;
- status: "active" | "paused" | "complete" | "blocked";
+ status: "active" | "paused" | "complete" | "cancelled";
floor?: string;
createdAt: number;
@@ -231,7 +231,7 @@ export function goalViewFromEntry(type: string, payload: unknown): GoalView | nu
if (!goal || typeof goal !== "object") return null;
if (typeof goal.objective !== "string" || !goal.objective.trim()) return null;
const status = goal.status;
- if (status !== "active" && status !== "paused" && status !== "complete" && status !== "blocked") return null;
+ if (status !== "active" && status !== "paused" && status !== "complete" && status !== "cancelled") return null;
const floor = formatFloor(goal.floor ?? null);
return {
objective: goal.objective,
diff --git a/src/slack/presenters.ts b/src/slack/presenters.ts
index 338079040..754dd7e4d 100644
--- a/src/slack/presenters.ts
+++ b/src/slack/presenters.ts
@@ -280,7 +280,7 @@ export function createTaskListPresenter(deps: {
export interface GoalNoticeView {
objective: string;
- status: "active" | "paused" | "complete" | "blocked";
+ status: "active" | "paused" | "complete" | "cancelled";
floor?: string;
}
@@ -292,7 +292,7 @@ export function renderGoalNotice(goal: GoalNoticeView): string {
const bounded = oneLine.length > 140 ? `${oneLine.slice(0, 139)}…` : oneLine;
const objective = bounded.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
if (goal.status === "complete") return `✓ Goal complete: ${objective}`;
- if (goal.status === "blocked") return `✕ Goal blocked: ${objective}`;
+ if (goal.status === "cancelled") return `✕ Goal cancelled: ${objective}`;
if (goal.status === "paused") return `⏸ Goal paused: ${objective}`;
return `◐ Pursuing goal: ${objective}${goal.floor ? ` · at least ${goal.floor}` : ""}`;
}
diff --git a/test/goal-tools.test.ts b/test/goal-tools.test.ts
index 9ef2b7bd9..df34c73c7 100644
--- a/test/goal-tools.test.ts
+++ b/test/goal-tools.test.ts
@@ -2,13 +2,14 @@ import test from "node:test";
import assert from "node:assert/strict";
import { createAgentTools, type ToolContextRef } from "../src/harness/agent-tools.ts";
import { createGrindMeter } from "../src/harness/grind.ts";
+import { harnessToolContext } from "../src/harness/harness-shared.ts";
import {
bankGoalTurn,
goalContinuationPrompt,
goalFloorUnmet,
- goalPausedNote,
goalSnapshotPayload,
rehydrateOpenGoal,
+ type GoalRecord,
} from "../src/harness/goal.ts";
import type { ScopeId } from "../src/types.ts";
@@ -282,10 +283,6 @@ test("stop, then a later human turn resumes from the persisted pause and complet
next.ref.emit = first.ref.emit;
next.ref.goal = rehydrateOpenGoal(history);
assert.equal(next.ref.goal?.status, "paused");
- assert.match(
- goalPausedNote(next.ref.goal!),
- /explicitly asks to resume[\s\S]*never resume it on your own initiative/,
- );
next.ref.current = { humanTurn: true } as never;
await next.update.execute("u1", { status: "resume", note: "user: resume the goal" });
assert.equal(rehydrateOpenGoal(history)?.status, "active");
@@ -347,10 +344,11 @@ test("agent cannot pause a goal or bypass its work floor", async () => {
assert.deepEqual(ref.goal, before);
});
-test("goal update schema offers only complete and resume", () => {
+test("goal update schema offers only complete, resume and cancel", () => {
const { tools } = toolbox();
const goal = tools.find((tool) => tool.name === "goal")!;
assert.doesNotMatch(JSON.stringify(goal.parameters), /"paused"|"blocked"|"active"/);
+ assert.match(JSON.stringify(goal.parameters), /"cancel"/);
});
test("invalid goal status cannot fall through to completion", async () => {
@@ -378,3 +376,116 @@ test("update reads named workspace files into the governor's evidence", async ()
assert.match(seen, /<file path="gone.md">\n\[missing: no such file\]/);
assert.equal(ref.goal?.status, "complete");
});
+
+function nextTurn(goal: GoalRecord) {
+ const box = toolbox();
+ box.ref.goal = rehydrateOpenGoal([{ type: "system", payload: goalSnapshotPayload(goal) }]);
+ return box;
+}
+
+for (const start of ["active", "paused"] as const) {
+ test(`cancel of a ${start} goal is refused on turns no person started, and the goal is unchanged`, async () => {
+ const first = toolbox();
+ await first.create.execute("c1", { objective: "long haul" });
+ first.ref.goal!.status = start;
+ const { ref, create, update } = nextTurn(first.ref.goal!);
+ const before = structuredClone(ref.goal);
+ for (const current of [null, {}, { humanTurn: false }]) {
+ ref.current = current as never;
+ const result = await update.execute("u1", { status: "cancel", note: "giving up" });
+ assert.match(textOf(result as never), /Only the user's own message can cancel/);
+ }
+ assert.deepEqual(ref.goal, before);
+ assert.match(textOf((await create.execute("c2", { objective: "another" })) as never), /already registered/);
+ });
+
+ test(`a person's request cancels a ${start} goal without completing it, and a replacement can be registered`, async () => {
+ const first = toolbox();
+ await first.create.execute("c1", { objective: "old research", floor: { minTurns: 50 } });
+ first.ref.goal!.status = start;
+ const { ref, create, update } = nextTurn(first.ref.goal!);
+ let governorCalls = 0;
+ ref.governGoal = async () => {
+ governorCalls++;
+ return { verdict: "complete", reasons: "proven" };
+ };
+ ref.current = { humanTurn: true } as never;
+ const result = await update.execute("u1", {
+ status: "cancel",
+ note: "user: drop the old goal and start the new one",
+ });
+ assert.match(textOf(result as never), /cancelled at the user's request/);
+ assert.equal(ref.goal?.status, "cancelled");
+ assert.equal(ref.goal?.cancelNote, "user: drop the old goal and start the new one");
+ assert.equal(ref.goal?.completionNote, undefined);
+ assert.equal(governorCalls, 0, "cancelling never asks the governor to call the work complete");
+ assert.equal(
+ rehydrateOpenGoal([{ type: "system", payload: goalSnapshotPayload(ref.goal!) }]),
+ null,
+ "a cancelled goal is not revived by a later turn",
+ );
+ const replaced = await create.execute("c2", { objective: "broader research and sending" });
+ assert.match(textOf(replaced as never), /registered and now enforced/);
+ assert.equal(ref.goal?.objective, "broader research and sending");
+ assert.equal(ref.goal?.status, "active");
+ });
+}
+
+test("the agent cannot cancel from a keep-going round or a goal it started or resumed this turn", async () => {
+ const first = toolbox();
+ await first.create.execute("c1", { objective: "grind on QA for 30 minutes" });
+ first.ref.current = { humanTurn: true } as never;
+ const same = await first.update.execute("u0", { status: "cancel", note: "user: grind on QA" });
+ assert.match(textOf(same as never), /Only the user's own message can cancel/);
+ assert.equal(first.ref.goal?.status, "active");
+
+ const keepGoing = nextTurn(first.ref.goal!);
+ keepGoing.ref.current = { humanTurn: true } as never;
+ keepGoing.ref.goalRound = 1;
+ assert.match(
+ textOf((await keepGoing.update.execute("u1", { status: "cancel", note: "this is hopeless" })) as never),
+ /Only the user's own message can cancel/,
+ );
+ assert.equal(keepGoing.ref.goal?.status, "active");
+
+ first.ref.goal!.status = "paused";
+ const resumed = nextTurn(first.ref.goal!);
+ resumed.ref.current = { humanTurn: true } as never;
+ await resumed.update.execute("u2", { status: "resume", note: "user: resume" });
+ assert.match(
+ textOf((await resumed.update.execute("u3", { status: "cancel", note: "user: resume" })) as never),
+ /Only the user's own message can cancel/,
+ );
+ assert.equal(resumed.ref.goal?.status, "active");
+});
+
+test("cancel needs an open goal", async () => {
+ const { ref, create, update } = toolbox();
+ ref.current = { humanTurn: true } as never;
+ assert.match(
+ textOf((await update.execute("u0", { status: "cancel", note: "x" })) as never),
+ /No active or paused goal/,
+ );
+ await create.execute("c1", { objective: "ship it" });
+ await update.execute("u1", { status: "complete", note: "done" });
+ assert.equal(ref.goal?.status, "complete");
+ assert.match(
+ textOf((await update.execute("u2", { status: "cancel", note: "x" })) as never),
+ /No active or paused goal/,
+ );
+ assert.equal(ref.goal?.status, "complete");
+});
+
+test("a turn resumed mid-way cannot cancel: it is not answering a fresh message from the person", async () => {
+ const first = toolbox();
+ await first.create.execute("c1", { objective: "long haul" });
+ const resumed = nextTurn(first.ref.goal!);
+ Object.assign(
+ resumed.ref,
+ harnessToolContext({ continueTurn: true, history: [], tools: { humanTurn: true } } as never),
+ { goal: resumed.ref.goal },
+ );
+ const result = await resumed.update.execute("u1", { status: "cancel", note: "user: cancel" });
+ assert.match(textOf(result as never), /Only the user's own message can cancel/);
+ assert.equal(resumed.ref.goal?.status, "active");
+});
diff --git a/test/goal.test.ts b/test/goal.test.ts
index 0552f925e..7eae92488 100644
--- a/test/goal.test.ts
+++ b/test/goal.test.ts
@@ -95,7 +95,6 @@ test("prompts carry the objective as escaped user data plus audit language", ()
assert.match(cont, /finish &lt;thing&gt; &amp; verify/);
assert.match(cont, /treat completion as unproven/);
assert.match(cont, /NOT met/);
- assert.match(cont, /only the user can stop it/);
assert.match(cont, /change approach/);
assert.doesNotMatch(cont, /"blocked"/);
goal.capTokens = 1000;
diff --git a/test/harness-router-goal.test.ts b/test/harness-router-goal.test.ts
index 6624433a6..4593f97db 100644
--- a/test/harness-router-goal.test.ts
+++ b/test/harness-router-goal.test.ts
@@ -4,6 +4,8 @@ import { createGoalRecord, latestGoalRecord, rehydrateOpenGoal } from "../src/ha
import type { Harness, HarnessTurnInput, HarnessTurnResult } from "../src/harness/harness.ts";
import { createHarnessRouter } from "../src/harness/harness-router.ts";
import { createMockHarness } from "../src/harness/mock-harness.ts";
+import { createAgentTools, type ToolContextRef } from "../src/harness/agent-tools.ts";
+import { harnessToolContext } from "../src/harness/harness-shared.ts";
import type { ScopeId, SessionEntry } from "../src/types.ts";
import { createMemoryRunSignalStore, startSignalPoll } from "../src/runs/run-signal-store.ts";
@@ -231,3 +233,68 @@ for (const harnessId of ["codex", "claude", "opencode"] as const) {
assert.equal(rehydrateOpenGoal(emitted)?.status, "paused");
});
}
+
+function goalTools(turn: HarnessTurnInput) {
+ const ref = harnessToolContext(turn);
+ ref.current = { humanTurn: true } as ToolContextRef["current"];
+ const goal = createAgentTools(ref).find((tool) => tool.name === "goal")!;
+ const call = (id: string, params: Record<string, unknown>) =>
+ (goal.execute as unknown as (id: string, p: unknown) => Promise<{ content: Array<{ text?: string }> }>)(id, params);
+ return { ref, call };
+}
+
+function earlierGoal(objective: string): SessionEntry[] {
+ const goal = createGoalRecord({ objective });
+ return [
+ { type: "system", payload: { kind: "goal", goal }, sessionId: "s1", seq: 0, parentSeq: null, createdAt: 1 },
+ ] as unknown as SessionEntry[];
+}
+
+test("a person's message cancels the goal and registers a replacement, which the router then enforces", async () => {
+ const emitted: SessionEntry[] = [];
+ const { harness, calls } = fakeAdapter(async (turn, round) => {
+ if (round === 0) {
+ const { call } = goalTools(turn);
+ await call("c1", { action: "update", status: "cancel", note: "user: cancel the old goal, start the new one" });
+ await call("c2", { action: "create", objective: "broader research and sending" });
+ return { reply: "replaced" };
+ }
+ assert.match(turn.input, /broader research and sending/);
+ if (round > 1) return { reply: "", stopped: true };
+ return { reply: "working" };
+ });
+
+ await router(harness).turns.runTurn(
+ stubTurn(emitted, { history: earlierGoal("old outreach goal"), turnWallClockMs: 600_000 }),
+ );
+
+ assert.ok(calls.length >= 2, "the replacement goal is enforced in the same turn");
+ const goals = emitted.flatMap((e) => {
+ const g = (e.payload as { goal?: { objective: string; status: string } }).goal;
+ return g ? [`${g.objective}:${g.status}`] : [];
+ });
+ assert.deepEqual(goals.slice(0, 2), ["old outreach goal:cancelled", "broader research and sending:active"]);
+ assert.equal(latestGoalRecord(emitted)?.objective, "broader research and sending");
+ assert.equal(rehydrateOpenGoal(emitted)?.status, "paused");
+});
+
+test("the agent cannot cancel its goal from a keep-going round", async () => {
+ const emitted: SessionEntry[] = [];
+ const refusals: string[] = [];
+ const { harness, calls } = fakeAdapter(async (turn, round) => {
+ if (round === 0) return { reply: "starting" };
+ const { call } = goalTools(turn);
+ const result = await call(`c${round}`, { action: "update", status: "cancel", note: "this is hopeless" });
+ refusals.push(result.content.map((c) => c.text ?? "").join(""));
+ if (round > 1) return { reply: "", stopped: true };
+ return { reply: "giving up" };
+ });
+
+ await router(harness).turns.runTurn(
+ stubTurn(emitted, { history: earlierGoal("ship the migration"), turnWallClockMs: 600_000 }),
+ );
+
+ assert.equal(calls.length, 3, "the goal keeps going after the refused cancel");
+ assert.match(refusals[0]!, /Only the user's own message can cancel/);
+ assert.equal(latestGoalRecord(emitted)?.status, "paused", "only the stop paused it; it was never cancelled");
+});
diff --git a/test/session-goal-cancel.test.ts b/test/session-goal-cancel.test.ts
new file mode 100644
index 000000000..c45867912
--- /dev/null
+++ b/test/session-goal-cancel.test.ts
@@ -0,0 +1,132 @@
+import "./support/auto-fake-sprites.ts";
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildApp } from "../src/wiring.ts";
+import { createGoalRecord, goalSnapshotPayload, latestGoalRecord, rehydrateOpenGoal } from "../src/harness/goal.ts";
+import { appendEntryOutsideTurn } from "../src/sessions/session-store.ts";
+import type { Principal } from "../src/types.ts";
+import type { OrchestratorInput } from "../src/core/orchestrator.ts";
+import { testConfig } from "./support/test-config.ts";
+
+function freshApp() {
+ return buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "goal-cancel-")) }));
+}
+
+function runRequest(): OrchestratorInput {
+ const principal: Principal = { id: "internal:U1", type: "internal" };
+ return {
+ actor: principal,
+ conversation: { kind: "dm", threadRef: "t", audience: [principal] },
+ origin: { kind: "direct" },
+ text: "keep going",
+ };
+}
+
+async function sessionWithGoal(built: ReturnType<typeof freshApp>, ref: string, status: "active" | "paused") {
+ const { sessions } = built;
+ const session = await sessions.getOrCreateByThread(ref, "dm", "personal:U1");
+ await sessions.addParticipant(session.id, "U1");
+ const goal = createGoalRecord({ objective: "old outreach goal", floor: { minTurns: 40 } });
+ goal.status = status;
+ const { lease } = await sessions.acquireLease(session.id);
+ assert.ok(lease);
+ await appendEntryOutsideTurn(sessions, lease, {
+ type: "system",
+ payload: goalSnapshotPayload(goal),
+ scopeLabel: session.scopeId,
+ });
+ await sessions.releaseLease(lease);
+ return session;
+}
+
+for (const status of ["active", "paused"] as const) {
+ test(`the owner cancels an idle ${status} goal; it closes for good and frees the session for a new goal`, async () => {
+ const built = freshApp();
+ const session = await sessionWithGoal(built, `web:U1:${status}`, status);
+
+ assert.equal(await built.app.cancelSessionGoal(session.id, "U2"), null, "a non-participant cannot cancel");
+ await built.sessions.addParticipant(session.id, "U2");
+ assert.equal(
+ await built.app.cancelSessionGoal(session.id, "U2"),
+ null,
+ "a participant who cannot write to the owner's personal scope cannot cancel",
+ );
+ assert.equal(rehydrateOpenGoal(await built.sessions.getEntries(session.id))?.status, status);
+
+ assert.deepEqual(await built.app.cancelSessionGoal(session.id, "U1"), { cancelled: true });
+
+ const entries = await built.sessions.getEntries(session.id);
+ const last = entries.at(-1)!;
+ assert.equal(last.type, "system");
+ assert.equal((last.payload as { cancelledBy?: string }).cancelledBy, "U1");
+ assert.equal(latestGoalRecord(entries)?.status, "cancelled");
+ assert.equal(latestGoalRecord(entries)?.completionNote, undefined, "cancelling is not completing");
+ assert.equal(rehydrateOpenGoal(entries), null, "later turns start with no goal to enforce");
+ const tape = JSON.stringify(await built.sessions.getTape(session.id));
+ assert.match(tape, /The user cancelled this goal/, "the model is told the goal was cancelled");
+ assert.ok(!(await built.app.listSessions("U1")).find((s) => s.id === session.id)?.goal);
+ assert.deepEqual(await built.app.cancelSessionGoal(session.id, "U1"), {
+ cancelled: false,
+ reason: "no_open_goal",
+ });
+ });
+}
+
+for (const status of ["active", "paused"] as const) {
+ test(`cancelling a ${status} goal while a turn runs lands after that turn's own final goal snapshot`, async () => {
+ const built = freshApp();
+ const ref = `web:U1:running-${status}`;
+ const session = await sessionWithGoal(built, ref, status);
+ await built.runs.enqueue({ sessionId: ref, request: runRequest() });
+ const run = await built.runs.claim("w1", 60_000);
+ assert.equal(run?.sessionId, ref);
+ const { lease } = await built.sessions.acquireLease(session.id, "turn");
+ assert.ok(lease, "the running turn holds the session");
+
+ const cancelling = built.app.cancelSessionGoal(session.id, "U1");
+ await new Promise((r) => setTimeout(r, 200));
+ assert.deepEqual(
+ (await built.signals.pending(run!.id)).map((p) => p.signal.kind),
+ status === "active" ? ["abort"] : [],
+ status === "active"
+ ? "a turn pursuing the goal is stopped"
+ : "an unrelated reply is left to finish while the goal is paused",
+ );
+
+ const final = latestGoalRecord(await built.sessions.getEntries(session.id))!;
+ final.status = "paused";
+ await appendEntryOutsideTurn(built.sessions, lease, {
+ type: "system",
+ payload: goalSnapshotPayload(final),
+ scopeLabel: session.scopeId,
+ });
+ await built.sessions.releaseLease(lease);
+ await built.runs.complete(run!.id, run!.leaseToken ?? "", { status: "ok", reply: "done" });
+
+ assert.deepEqual(await cancelling, { cancelled: true });
+ const entries = await built.sessions.getEntries(session.id);
+ assert.deepEqual(
+ entries.filter((e) => (e.payload as { kind?: string }).kind === "goal").map((e) => latestGoalRecord([e])?.status),
+ [status, "paused", "cancelled"],
+ );
+ assert.equal(rehydrateOpenGoal(entries), null);
+ });
+}
+
+test("cancelling with no open goal touches nothing", async () => {
+ const built = freshApp();
+ const ref = "web:U1:none";
+ const session = await built.sessions.getOrCreateByThread(ref, "dm", "personal:U1");
+ await built.sessions.addParticipant(session.id, "U1");
+ await built.runs.enqueue({ sessionId: ref, request: runRequest() });
+ const run = await built.runs.claim("w1", 60_000);
+ assert.deepEqual(await built.app.cancelSessionGoal(session.id, "U1"), {
+ cancelled: false,
+ reason: "no_open_goal",
+ });
+ assert.deepEqual(await built.signals.pending(run!.id), []);
+});
diff --git a/test/slack-presenters.test.ts b/test/slack-presenters.test.ts
index ede6c6d6f..37e91f7a6 100644
--- a/test/slack-presenters.test.ts
+++ b/test/slack-presenters.test.ts
@@ -348,7 +348,7 @@ test("renderGoalNotice: one line per status, floor shown while active", () => {
"◐ Pursuing goal: get the tests green &lt;fast&gt; · at least 30m",
);
assert.equal(renderGoalNotice({ objective: "obj", status: "complete" }), "✓ Goal complete: obj");
- assert.equal(renderGoalNotice({ objective: "obj", status: "blocked" }), "✕ Goal blocked: obj");
+ assert.equal(renderGoalNotice({ objective: "obj", status: "cancelled" }), "✕ Goal cancelled: obj");
assert.equal(renderGoalNotice({ objective: "obj", status: "paused" }), "⏸ Goal paused: obj");
});