Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
53f17d1
chore: upgrade AI SDK v6 → v7 (api) — chat#1816
sweetmantech Jun 26, 2026
3c1f0b5
fix: green up the v7 PR — lint, format, and the Workflow build
sweetmantech Jun 26, 2026
31af216
fix: keep @vercel/oidc external so the Workflow build resolves it
sweetmantech Jun 26, 2026
018d65c
fix: preserve current-main chat contracts in SDK v7 migration
sidneyswift Nov 18, 2026
fe8a873
fix: retain legacy usage and isolate SDK from durable workflow imports
sidneyswift Nov 18, 2026
9ff75e6
test: requalify registration bindings for reviewed SDK dependency graph
sidneyswift Nov 18, 2026
85c58a7
fix: preserve async tool iteration through cancellation wrapper
sidneyswift Nov 18, 2026
6c8043a
fix: bound async iterator fallback throw cleanup on abort
sidneyswift Nov 18, 2026
a50f600
fix: isolate fallback chat pricing in its own durable step
sidneyswift Nov 18, 2026
b6b9e0c
feat: add fail-closed journal-backed projection proof foundation
sidneyswift Nov 18, 2026
c40cf61
fix: separate observation and aggregate projection proof limits
sidneyswift Nov 18, 2026
e0f51d9
fix(chat): bind projection evidence to active context and retention m…
sidneyswift Nov 18, 2026
dfb906d
feat(chat): wire verified projection ingress and canonical generation
sidneyswift Nov 18, 2026
c408619
fix(chat): preserve Stop accounting and reject unknown effect redelivery
sidneyswift Nov 18, 2026
2909b8e
feat(chat): define bounded continuation admission contract
sidneyswift Nov 18, 2026
5bc0b42
feat(chat): gate durable canonical continuations before streaming
sidneyswift Nov 18, 2026
ea32054
fix(chat): validate continuation before fenced message writes
sidneyswift Nov 18, 2026
2ed9207
fix(chat): report admitted runs after stream ownership loss
sidneyswift Nov 18, 2026
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
2 changes: 1 addition & 1 deletion .github/workflows/format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
node-version: "22"

- name: Setup pnpm
uses: pnpm/action-setup@v4
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
node-version: "22"

- name: Setup pnpm
uses: pnpm/action-setup@v4
Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,17 @@ jobs:
- name: Check production TypeScript configuration
run: pnpm exec tsc --noEmit --project tsconfig.build.json

- name: Check actual chat pricing durable boundary without pricing seams
run: |
node scripts/chat-pricing-durable-compile.mjs
node scripts/chat-pricing-step-fixture.mjs

- name: Check journal-backed projection proof with offline World
run: node scripts/chat-projection-proof-fixture.mjs

- name: Check installed AI SDK v7 contract signatures
run: pnpm exec tsc --noEmit --project tsconfig.ai-sdk-v7.json

- name: Check response contract types
run: pnpm typecheck:response-contracts

Expand Down
2 changes: 1 addition & 1 deletion app/api/chat/[chatId]/stream/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const dynamic = "force-dynamic";
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: getCorsHeaders(),
headers: getCorsHeaders({ streamContinuation: true }),
});
}

Expand Down
2 changes: 1 addition & 1 deletion app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const maxDuration = 800;
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: getCorsHeaders(),
headers: getCorsHeaders({ streamContinuation: true }),
});
}

Expand Down
2 changes: 1 addition & 1 deletion app/api/chat/runs/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { handleStartChatRun } from "@/lib/chat/runs/handleStartChatRun";
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: getCorsHeaders(),
headers: getCorsHeaders({ streamContinuation: true }),
});
}

Expand Down
42 changes: 42 additions & 0 deletions app/lib/workflows/__tests__/persistProjectedAssistantStep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { beforeEach, expect, it, vi } from "vitest";
import { persistProjectedAssistantStep } from "../projection/persistProjectedAssistantStep";
import { upsertChatMessage } from "@/lib/supabase/chat_messages/upsertChatMessage";
import { updateChat } from "@/lib/supabase/chats/updateChat";
vi.mock("workflow", async original => ({
...(await original<typeof import("workflow")>()),
getStepMetadata: () => ({ attempt: 1 }),
}));
vi.mock("@/lib/supabase/chat_messages/upsertChatMessage", () => ({ upsertChatMessage: vi.fn() }));
vi.mock("@/lib/supabase/chats/updateChat", () => ({ updateChat: vi.fn() }));
const message = {
id: "a",
role: "assistant",
parts: [{ type: "text", text: "canonical" }],
} as never;
beforeEach(() => vi.resetAllMocks());
it("requires exact returned canonical message", async () => {
vi.mocked(upsertChatMessage).mockResolvedValue({
ok: true,
isDuplicate: false,
row: { id: "a", chat_id: "chat", role: "assistant", parts: message },
} as never);
await expect(persistProjectedAssistantStep("chat", message)).resolves.toBeUndefined();
expect(upsertChatMessage).toHaveBeenCalledTimes(1);
});
it.each([
null,
{ id: "a", chat_id: "other", role: "assistant", parts: message },
{ id: "a", chat_id: "chat", role: "assistant", parts: {} },
])("rejects missing or mismatched ACK without retry", async row => {
vi.mocked(upsertChatMessage).mockResolvedValue({ ok: true, isDuplicate: !row, row } as never);
await expect(persistProjectedAssistantStep("chat", message)).rejects.toThrow("reconciliation");
expect(upsertChatMessage).toHaveBeenCalledTimes(1);
expect(updateChat).not.toHaveBeenCalled();
});
it("classifies unknown transport outcome as required reconciliation", async () => {
vi.mocked(upsertChatMessage).mockRejectedValue(new Error("transport"));
await expect(persistProjectedAssistantStep("chat", message)).rejects.toMatchObject({
name: "FatalError",
});
expect(upsertChatMessage).toHaveBeenCalledTimes(1);
});
108 changes: 108 additions & 0 deletions app/lib/workflows/__tests__/projectionRedelivery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { beforeEach, expect, it, vi } from "vitest";
import { streamText } from "ai";
import { buildAgentTools } from "@/lib/agent/buildAgentTools";
import { upsertChatMessage } from "@/lib/supabase/chat_messages/upsertChatMessage";
import { runAgentStep } from "../runAgentStep";
import { persistProjectedAssistantStep } from "../projection/persistProjectedAssistantStep";
import { sendProjectionFailureStep } from "../projection/sendProjectionFailureStep";
const state = vi.hoisted(() => ({ attempt: 1 as number | undefined }));
vi.mock("workflow", async original => ({
...(await original<typeof import("workflow")>()),
getStepMetadata: () => ({ attempt: state.attempt, stepId: "step" }),
getWorkflowMetadata: () => ({ workflowRunId: "run" }),
}));
vi.mock("ai", async original => ({
...(await original<typeof import("ai")>()),
streamText: vi.fn(() => ({
toUIMessageStream: () =>
(async function* () {
yield { type: "text-start", id: "t" };
yield { type: "text-end", id: "t" };
})(),
finishReason: Promise.resolve("stop"),
responseMessages: Promise.resolve([]),
})),
}));
vi.mock("@ai-sdk/gateway", () => ({ gateway: () => ({}) }));
vi.mock("@/lib/agent/buildAgentTools", () => ({ buildAgentTools: vi.fn(() => ({})) }));
vi.mock("@/lib/chat/pollWorkflowCancellation", () => ({
pollWorkflowCancellation: () => ({ stop() {}, done: Promise.resolve() }),
}));
vi.mock("@/lib/chat/isRunCancelled", () => ({ isRunCancelled: async () => false }));
vi.mock("@/lib/supabase/chat_messages/upsertChatMessage", () => ({ upsertChatMessage: vi.fn() }));
vi.mock("@/lib/supabase/chats/updateChat", () => ({ updateChat: vi.fn() }));
const input = {
modelMessages: [],
originalMessages: [],
modelId: "synthetic",
assistantMessageId: "a",
agentContext: { sandbox: { state: { type: "vercel" }, workingDirectory: "/synthetic" } },
} as never;
const message = { id: "a", role: "assistant", parts: [] } as never;
beforeEach(() => {
state.attempt = 1;
vi.clearAllMocks();
vi.stubGlobal(
"fetch",
vi.fn(() => {
throw new Error("Network forbidden");
}),
);
});
it("does not reenter provider or append effects after unknown producer completion", async () => {
const writes = vi.fn();
const writable = new WritableStream({ write: writes });
await runAgentStep({ ...(input as object), writable } as never);
state.attempt = 2;
await expect(runAgentStep({ ...(input as object), writable } as never)).rejects.toMatchObject({
name: "FatalError",
});
expect(streamText).toHaveBeenCalledTimes(1);
expect(writes).toHaveBeenCalledTimes(2);
expect(fetch).not.toHaveBeenCalled();
});
it("does not repeat a required row write after unknown completion", async () => {
vi.mocked(upsertChatMessage).mockResolvedValue({
ok: true,
isDuplicate: false,
row: { id: "a", chat_id: "chat", role: "assistant", parts: message },
} as never);
await persistProjectedAssistantStep("chat", message);
state.attempt = 2;
await expect(persistProjectedAssistantStep("chat", message)).rejects.toMatchObject({
name: "FatalError",
});
expect(upsertChatMessage).toHaveBeenCalledTimes(1);
});
it("does not append a failure stream again after unknown completion", async () => {
const writes = vi.fn();
const writable = new WritableStream({ write: writes });
await sendProjectionFailureStep(writable);
state.attempt = 2;
await expect(sendProjectionFailureStep(writable)).rejects.toMatchObject({ name: "FatalError" });
expect(writes).toHaveBeenCalledTimes(2);
});
it("also refuses redelivery after a pre-provider failure rather than guessing its effect boundary", async () => {
vi.mocked(buildAgentTools).mockImplementationOnce(() => {
throw new Error("before model");
});
await expect(
runAgentStep({ ...(input as object), writable: new WritableStream() } as never),
).rejects.toThrow("before model");
state.attempt = 2;
await expect(
runAgentStep({ ...(input as object), writable: new WritableStream() } as never),
).rejects.toThrow("reconciliation");
expect(streamText).not.toHaveBeenCalled();
expect(buildAgentTools).toHaveBeenCalledTimes(1);
});
it.each([undefined, 0, NaN])(
"refuses invalid attempt metadata %s before effects",
async attempt => {
state.attempt = attempt;
await expect(
runAgentStep({ ...(input as object), writable: new WritableStream() } as never),
).rejects.toThrow("reconciliation");
expect(streamText).not.toHaveBeenCalled();
},
);
30 changes: 16 additions & 14 deletions app/lib/workflows/__tests__/runAgentStep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ vi.mock("@ai-sdk/gateway", () => ({
// runAgentStep now reads workflowRunId via getWorkflowMetadata() and polls
// getRun(runId).status to source its abort signal. Stub both so the tests
// don't pull in the workflow runtime.
vi.mock("workflow", () => ({
vi.mock("workflow", async original => ({
...(await original<typeof import("workflow")>()),
getStepMetadata: vi.fn(() => ({ attempt: 1, stepId: "step" })),
getWorkflowMetadata: vi.fn(() => ({
workflowRunId: "test-run-id",
workflowName: "test",
Expand Down Expand Up @@ -46,7 +48,7 @@ type StreamOpts = {
messageMetadata?: unknown;
generateMessageId?: unknown;
originalMessages?: unknown[];
onFinish?: (e: { responseMessage: unknown }) => unknown;
onEnd?: (e: { responseMessage: unknown }) => unknown;
};

function makeStreamResult(opts?: {
Expand All @@ -67,12 +69,12 @@ function makeStreamResult(opts?: {
yield { type: "text-start", id: "t1" };
yield { type: "text-end", id: "t1" };
if (opts && "emitResponseMessage" in opts) {
streamOpts.onFinish?.({ responseMessage: opts.emitResponseMessage });
streamOpts.onEnd?.({ responseMessage: opts.emitResponseMessage });
}
})();
}),
finishReason: Promise.resolve("stop"),
response: Promise.resolve({ messages: [] }),
responseMessages: Promise.resolve([]),
};
}

Expand Down Expand Up @@ -165,10 +167,10 @@ describe("runAgentStep", () => {
writable: stream,
} as never);

const args = vi.mocked(streamText).mock.calls[0]?.[0] as { system?: string };
expect(args.system).toMatch(/# Environment/);
expect(args.system).toMatch(/Working directory: \. \(workspace root\)/);
expect(args.system).toMatch(/workspace-relative paths/);
const args = vi.mocked(streamText).mock.calls[0]?.[0] as { instructions?: string };
expect(args.instructions).toMatch(/# Environment/);
expect(args.instructions).toMatch(/Working directory: \. \(workspace root\)/);
expect(args.instructions).toMatch(/workspace-relative paths/);
});

it("wraps tools with anthropic cacheControl on the last tool before passing to streamText", async () => {
Expand Down Expand Up @@ -241,7 +243,7 @@ describe("runAgentStep", () => {
return (async function* () {})();
}),
finishReason: Promise.resolve("stop"),
response: Promise.resolve({ messages: [] }),
responseMessages: Promise.resolve([]),
} as never);
const { stream } = makeWritable();

Expand All @@ -256,7 +258,7 @@ describe("runAgentStep", () => {
vi.mocked(streamText).mockReturnValue({
toUIMessageStream: vi.fn(() => (async function* () {})()),
finishReason: Promise.resolve("tool-calls"),
response: Promise.resolve({ messages: produced }),
responseMessages: Promise.resolve(produced),
} as never);
const { stream } = makeWritable();

Expand Down Expand Up @@ -303,7 +305,7 @@ describe("runAgentStep", () => {
expect(result.finishReason).toBe("stop");
});

it("returns the responseMessage captured from onFinish (so the workflow can charge credits)", async () => {
it("returns the responseMessage captured from onEnd (so the workflow can charge credits)", async () => {
const emitted = {
id: "asst-test-id",
role: "assistant",
Expand All @@ -320,8 +322,8 @@ describe("runAgentStep", () => {
expect(result.responseMessage).toEqual(emitted);
});

it("returns responseMessage: undefined when onFinish never fires", async () => {
// Default mock never invokes onFinish.
it("returns responseMessage: undefined when onEnd never fires", async () => {
// Default mock never invokes onEnd.
vi.mocked(streamText).mockReturnValue(makeStreamResult() as never);
const { stream } = makeWritable();

Expand Down Expand Up @@ -354,7 +356,7 @@ describe("runAgentStep", () => {
})(),
),
finishReason: Promise.resolve("length"),
response: Promise.resolve({ messages: [] }),
responseMessages: Promise.resolve([]),
} as never);
const { stream } = makeWritable();

Expand Down
Loading
Loading