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
42 changes: 42 additions & 0 deletions packages/app/src/electro-bridge/ipc/local-ai-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,48 @@ describe("local AI IPC", () => {
expect(runtime.startChat).not.toHaveBeenCalled();
});

it("rejects malformed metadata, generation options, and oversized prompts", () => {
const sender = new FakeWebContents(1);
const runtime = createRuntime();
const { handlers, ipc } = createMainIPC();
setupLocalAIIPC(
{
runtime,
getAllowedWebContents: () => sender as never,
},
ipc as never,
);
const start = handlers.get(LOCAL_AI_CHANNELS.START_CHAT);
const baseRequest = {
requestId: "request-1",
providerId: "codex-cli",
messages: [{ role: "user", content: "hello" }],
};
const invalidRequests = [
{ ...baseRequest, modelId: { id: "not-a-string" } },
{ ...baseRequest, agent: { systemPrompt: 42 } },
{ ...baseRequest, options: { temperature: Number.NaN } },
{ ...baseRequest, options: { maxOutputTokens: 0 } },
{
...baseRequest,
agent: { systemPrompt: "x" },
messages: Array.from({ length: 5 }, () => ({
role: "user",
content: "x".repeat(200_000),
})),
},
];

for (const invalidRequest of invalidRequests) {
expect(start?.(createEvent(sender), invalidRequest)).toMatchObject({
success: false,
accepted: false,
error: { code: "LOCAL_AI_INVALID_REQUEST" },
});
}
expect(runtime.startChat).not.toHaveBeenCalled();
});

it("accepts interaction responses only from the active request owner", async () => {
const allowedSender = new FakeWebContents(1);
const otherSender = new FakeWebContents(2);
Expand Down
47 changes: 47 additions & 0 deletions packages/app/src/electro-bridge/ipc/local-ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ const ALLOWED_PROVIDER_IDS = new Set(["claude-code", "codex-cli"]);
const MAX_MESSAGE_CHARS = 200_000;
const MAX_REQUEST_CHARS = 1_000_000;
const MAX_INTERACTION_RESPONSE_CHARS = 20_000;
const MAX_METADATA_CHARS = 512;
const MAX_CWD_CHARS = 4_096;
const MAX_OUTPUT_TOKENS = 1_000_000;

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
Expand All @@ -57,6 +60,13 @@ function createError(message: string, code: string): LocalAISerializableError {
return { name: "LocalAIIPCError", message, code };
}

function isOptionalString(value: unknown, maximumLength: number): boolean {
return (
value === undefined ||
(typeof value === "string" && value.length <= maximumLength)
);
}

export function serializeLocalAIError(
error: unknown,
): LocalAISerializableError {
Expand Down Expand Up @@ -116,10 +126,47 @@ function validateRequest(request: unknown): request is LocalAIChatRequest {
return false;
}

if (!isOptionalString(request.modelId, MAX_METADATA_CHARS)) {
return false;
}

let totalChars = 0;
if (request.agent !== undefined) {
if (!isRecord(request.agent)) return false;
if (!isOptionalString(request.agent.id, MAX_METADATA_CHARS)) return false;
if (!isOptionalString(request.agent.systemPrompt, MAX_MESSAGE_CHARS)) {
return false;
}
if (typeof request.agent.systemPrompt === "string") {
totalChars += request.agent.systemPrompt.length;
}
}

if (request.options !== undefined) {
if (!isRecord(request.options)) return false;
if (!isOptionalString(request.options.cwd, MAX_CWD_CHARS)) return false;
if (
request.options.temperature !== undefined &&
(typeof request.options.temperature !== "number" ||
!Number.isFinite(request.options.temperature))
) {
return false;
}
if (
request.options.maxOutputTokens !== undefined &&
(typeof request.options.maxOutputTokens !== "number" ||
!Number.isInteger(request.options.maxOutputTokens) ||
request.options.maxOutputTokens <= 0 ||
request.options.maxOutputTokens > MAX_OUTPUT_TOKENS)
) {
return false;
}
}

return request.messages.every((message) => {
if (
isRecord(message) &&
isOptionalString(message.id, MAX_METADATA_CHARS) &&
(message.role === "system" ||
message.role === "user" ||
message.role === "assistant") &&
Expand Down
101 changes: 101 additions & 0 deletions packages/app/src/electron/ai/__tests__/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,107 @@ describe("LocalAiRuntime", () => {
expect(adapter.dispose).toHaveBeenCalledOnce();
});

it("does not create a provider model after aborting during status discovery", async () => {
const events: LocalAIStreamEvent[] = [];
const adapter = fakeAdapter("codex-cli");
let finishStatusDiscovery: (() => void) | undefined;
vi.mocked(adapter.getStatus).mockImplementation(
() =>
new Promise((resolve) => {
finishStatusDiscovery = () =>
resolve({
...LOCAL_AI_PROVIDER_DESCRIPTORS["codex-cli"],
available: true,
authenticated: true,
executablePath: "/test/codex",
checkedAt: new Date(0).toISOString(),
});
}),
);
const streamInvoker = vi.fn<RuntimeStreamInvoker>();
const runtime = new LocalAiRuntime({
adapters: [adapter],
streamInvoker,
});

const chat = runtime.startChat(
request({ providerId: "codex-cli" }),
(event) => events.push(event),
);
await vi.waitFor(() => {
expect(adapter.getStatus).toHaveBeenCalledOnce();
});
expect(runtime.abort("request-1")).toBe(true);
finishStatusDiscovery?.();
await chat;

expect(adapter.createModel).not.toHaveBeenCalled();
expect(streamInvoker).not.toHaveBeenCalled();
expect(events.at(-1)).toEqual({
type: "finish",
requestId: "request-1",
finishReason: "aborted",
});
});

it("rejects a tool interaction that starts after its request was aborted", async () => {
const events: LocalAIStreamEvent[] = [];
let toolContext:
| Parameters<LocalAiProviderAdapter["createModel"]>[2]
| undefined;
let continueStream: (() => void) | undefined;
const adapter = fakeAdapter("claude-code");
vi.mocked(adapter.createModel).mockImplementation(
async (_request, _status, context) => {
toolContext = context;
return {} as LanguageModel;
},
);
const executeTool = vi.fn(async () => ({ written: true }));
const runtime = new LocalAiRuntime({
adapters: [adapter],
getToolGroups: () => [
{
serverName: "external",
tools: [
{
name: "write_value",
inputSchema: { type: "object", properties: {} },
},
],
},
],
executeTool,
streamInvoker: () => ({
toUIMessageStream: async function* () {
yield { type: "start" as const, messageId: "assistant-1" };
await new Promise<void>((resolve) => {
continueStream = resolve;
});
await toolContext?.tools[0]?.execute({});
},
}),
});

const chat = runtime.startChat(request(), (event) => events.push(event));
await vi.waitFor(() => {
expect(continueStream).toBeTypeOf("function");
});
expect(runtime.abort("request-1")).toBe(true);
continueStream?.();
await chat;

expect(executeTool).not.toHaveBeenCalled();
expect(events).not.toContainEqual(
expect.objectContaining({ type: "interaction" }),
);
expect(events.at(-1)).toEqual({
type: "finish",
requestId: "request-1",
finishReason: "aborted",
});
});

it("pauses an approval-gated tool until the renderer responds", async () => {
const events: LocalAIStreamEvent[] = [];
let toolContext:
Expand Down
11 changes: 10 additions & 1 deletion packages/app/src/electron/ai/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ export class LocalAiRuntime implements LocalAIRuntimeService {

try {
const probeStatus = await adapter.getStatus();
controller.signal.throwIfAborted();
if (!probeStatus.available || !probeStatus.authenticated) {
this.emitFailure(
request.requestId,
Expand Down Expand Up @@ -355,15 +356,18 @@ export class LocalAiRuntime implements LocalAIRuntimeService {
controller.signal,
emit,
);
const toolGroups = await this.getToolGroups();
controller.signal.throwIfAborted();
const tools = createAgentToolCatalog({
groups: await this.getToolGroups(),
groups: toolGroups,
executeTool: this.executeTool,
requestInteraction,
});
const model = await adapter.createModel(trustedRequest, probeStatus, {
tools,
requestInteraction,
});
controller.signal.throwIfAborted();
const result = this.streamInvoker({
model,
messages: toMessages(request),
Expand Down Expand Up @@ -497,6 +501,11 @@ export class LocalAiRuntime implements LocalAIRuntimeService {
const interactionId = randomUUID();

return new Promise((resolve, reject) => {
if (abortSignal.aborted) {
reject(new Error(`Interaction cancelled for ${interaction.name}.`));
return;
}

const onAbort = () => {
const pending = this.pendingInteractions.get(interactionId);
if (!pending) return;
Expand Down
9 changes: 7 additions & 2 deletions packages/app/src/renderer/components/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,14 @@ export function HomePage() {
</button>
<button
onClick={handleNewChat}
className="p-3 rounded-lg bg-background/80 backdrop-blur-sm border border-border/40 text-muted-foreground hover:bg-accent hover:text-accent-foreground hover:border-border/60 transition-all duration-150"
disabled={isLoading}
className="p-3 rounded-lg bg-background/80 backdrop-blur-sm border border-border/40 text-muted-foreground hover:bg-accent hover:text-accent-foreground hover:border-border/60 transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-40"
aria-label="New chat"
title="New Chat"
title={
isLoading
? "Stop the current response before starting a new chat"
: "New Chat"
}
>
<Plus size={16} />
</button>
Expand Down
Loading