approvals
This commit is contained in:
16 files changed
+560
-33
No files matched your search
@@ -26,6 +26,17 @@ CodeThing is a desktop shell for coding agents. This first implementation is:
|
||||
- Renderer talks only to `window.nativeApi` exposed by preload.
|
||||
- Preload and main both validate inputs using shared Zod schemas.
|
||||
|
||||
`sandbox: true` above is Electron renderer sandboxing. It is separate from Codex execution sandbox policy (`read-only`, `workspace-write`, `danger-full-access`) used when starting provider sessions.
|
||||
|
||||
## Runtime modes
|
||||
|
||||
CodeThing has a global runtime mode switch in the sidebar:
|
||||
|
||||
- `Full access` (default): starts new sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- `Approval required`: starts new sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
|
||||
Mode changes apply across all threads. Existing live sessions are restarted so old and new threads use the selected mode.
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev`: starts contract build/watch, renderer dev server, and Electron process.
|
||||
@@ -47,8 +58,9 @@ The renderer now depends on `nativeApi.providers.*`:
|
||||
1. `startSession`
|
||||
2. `sendTurn`
|
||||
3. `interruptTurn`
|
||||
4. `stopSession`
|
||||
5. `listSessions`
|
||||
6. `onEvent`
|
||||
4. `respondToRequest`
|
||||
5. `stopSession`
|
||||
6. `listSessions`
|
||||
7. `onEvent`
|
||||
|
||||
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but returns a not-implemented error in main-process dispatch.
|
||||
@@ -1,6 +1,4 @@
|
||||
## TODO
|
||||
|
||||
- [x] Remove model picker from new project menu
|
||||
- [x] CMD+Shift+O to create new thread in current project
|
||||
- [x] Remove project title pill from input box and topnav
|
||||
- [x] Remove connection status from topnav
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [ ] Pasting/adding images to submit with prompts
|
||||
@@ -4,7 +4,9 @@ import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import type {
|
||||
ProviderApprovalDecision,
|
||||
ProviderEvent,
|
||||
ProviderRequestKind,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
@@ -21,11 +23,24 @@ interface PendingRequest {
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface PendingApprovalRequest {
|
||||
requestId: string;
|
||||
jsonRpcId: string | number;
|
||||
method:
|
||||
| "item/commandExecution/requestApproval"
|
||||
| "item/fileChange/requestApproval";
|
||||
requestKind: ProviderRequestKind;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
}
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<string, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -137,6 +152,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -273,6 +289,45 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
decision: ProviderApprovalDecision,
|
||||
): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const pendingRequest = context.pendingApprovals.get(requestId);
|
||||
if (!pendingRequest) {
|
||||
throw new Error(`Unknown pending approval request: ${requestId}`);
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(requestId);
|
||||
this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
},
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/requestApproval/decision",
|
||||
threadId: pendingRequest.threadId,
|
||||
turnId: pendingRequest.turnId,
|
||||
itemId: pendingRequest.itemId,
|
||||
requestId: pendingRequest.requestId,
|
||||
requestKind: pendingRequest.requestKind,
|
||||
payload: {
|
||||
requestId: pendingRequest.requestId,
|
||||
requestKind: pendingRequest.requestKind,
|
||||
decision,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
stopSession(sessionId: string): void {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
@@ -286,6 +341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending.reject(new Error("Session stopped before request completed."));
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
|
||||
context.output.close();
|
||||
|
||||
@@ -498,6 +554,25 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
request: JsonRpcRequest,
|
||||
): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: string | undefined;
|
||||
if (requestKind) {
|
||||
requestId = randomUUID();
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
method:
|
||||
requestKind === "command"
|
||||
? "item/commandExecution/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
...(route.threadId ? { threadId: route.threadId } : {}),
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "request",
|
||||
@@ -508,22 +583,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: route.threadId,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
});
|
||||
|
||||
if (request.method === "item/commandExecution/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.method === "item/fileChange/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
if (requestKind) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -656,6 +721,20 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
}
|
||||
|
||||
private requestKindForMethod(
|
||||
method: string,
|
||||
): ProviderRequestKind | undefined {
|
||||
if (method === "item/commandExecution/requestApproval") {
|
||||
return "command";
|
||||
}
|
||||
|
||||
if (method === "item/fileChange/requestApproval") {
|
||||
return "file-change";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
agentSessionIdSchema,
|
||||
newTodoInputSchema,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
@@ -175,6 +176,16 @@ function registerIpcHandlers(): void {
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerRequestRespond,
|
||||
withParsedPayload(
|
||||
providerRespondToRequestInputSchema,
|
||||
async (_event, payload) => {
|
||||
await providerManager.respondToRequest(payload);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerSessionStop,
|
||||
withParsedPayload(
|
||||
|
||||
@@ -41,6 +41,8 @@ const nativeApi: NativeApi = {
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnStart, input),
|
||||
interruptTurn: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnInterrupt, input),
|
||||
respondToRequest: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerRequestRespond, input),
|
||||
stopSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStop, input),
|
||||
listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.providerSessionList),
|
||||
|
||||
@@ -48,4 +48,18 @@ describe("ProviderManager", () => {
|
||||
manager.dispose();
|
||||
expect(() => manager.dispose()).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects request responses for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.respondToRequest({
|
||||
sessionId: "missing-session",
|
||||
requestId: "req-1",
|
||||
decision: "accept",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -5,12 +5,14 @@ import path from "node:path";
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
@@ -79,6 +81,19 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
await this.codex.interruptTurn(input.sessionId, input.turnId);
|
||||
}
|
||||
|
||||
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
|
||||
const input = providerRespondToRequestInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
await this.codex.respondToRequest(
|
||||
input.sessionId,
|
||||
input.requestId,
|
||||
input.decision,
|
||||
);
|
||||
}
|
||||
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ProviderApprovalDecision, ProviderEvent } from "@acme/contracts";
|
||||
import {
|
||||
type FormEvent,
|
||||
Fragment,
|
||||
@@ -39,6 +40,70 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
return "text-[#606060]";
|
||||
}
|
||||
|
||||
interface PendingApprovalCard {
|
||||
requestId: string;
|
||||
requestKind: "command" | "file-change";
|
||||
createdAt: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function approvalDetail(event: ProviderEvent): string | undefined {
|
||||
const payload = asRecord(event.payload);
|
||||
const command = asString(payload?.command);
|
||||
if (command) return command;
|
||||
return asString(payload?.reason);
|
||||
}
|
||||
|
||||
function derivePendingApprovals(
|
||||
events: ProviderEvent[],
|
||||
): PendingApprovalCard[] {
|
||||
const pending = new Map<string, PendingApprovalCard>();
|
||||
const ordered = [...events].reverse();
|
||||
|
||||
for (const event of ordered) {
|
||||
if (
|
||||
event.method === "session/closed" ||
|
||||
event.method === "session/exited"
|
||||
) {
|
||||
pending.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
const requestId =
|
||||
event.requestId ?? asString(asRecord(event.payload)?.requestId);
|
||||
if (!requestId) continue;
|
||||
|
||||
if (
|
||||
event.kind === "request" &&
|
||||
(event.requestKind === "command" || event.requestKind === "file-change")
|
||||
) {
|
||||
const detail = approvalDetail(event);
|
||||
pending.set(requestId, {
|
||||
requestId,
|
||||
requestKind: event.requestKind,
|
||||
createdAt: event.createdAt,
|
||||
...(detail ? { detail } : {}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.method === "item/requestApproval/decision") {
|
||||
pending.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(pending.values());
|
||||
}
|
||||
|
||||
export default function ChatView() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
@@ -48,6 +113,9 @@ export default function ChatView() {
|
||||
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
|
||||
const [selectedEffort, setSelectedEffort] =
|
||||
useState<string>(DEFAULT_REASONING);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>(
|
||||
[],
|
||||
);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
@@ -68,6 +136,10 @@ export default function ChatView() {
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
[activeThread?.events],
|
||||
);
|
||||
const pendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(activeThread?.events ?? []),
|
||||
[activeThread?.events],
|
||||
);
|
||||
const assistantCompletionByItemId = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
const ordered = [...(activeThread?.events ?? [])].reverse();
|
||||
@@ -127,6 +199,16 @@ export default function ChatView() {
|
||||
timelineEntries,
|
||||
workLogEntries.length,
|
||||
]);
|
||||
const runtimeSessionConfig =
|
||||
state.runtimeMode === "full-access"
|
||||
? ({
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
} as const)
|
||||
: ({
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
} as const);
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageCount = activeThread?.messages.length ?? 0;
|
||||
@@ -191,6 +273,8 @@ export default function ChatView() {
|
||||
provider: "codex",
|
||||
cwd: activeProject.cwd || undefined,
|
||||
model: selectedModel || undefined,
|
||||
approvalPolicy: runtimeSessionConfig.approvalPolicy,
|
||||
sandboxMode: runtimeSessionConfig.sandboxMode,
|
||||
});
|
||||
dispatch({
|
||||
type: "UPDATE_SESSION",
|
||||
@@ -270,6 +354,37 @@ export default function ChatView() {
|
||||
});
|
||||
};
|
||||
|
||||
const onRespondToApproval = async (
|
||||
requestId: string,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => {
|
||||
if (!api || !activeThread?.session) return;
|
||||
|
||||
setRespondingRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
);
|
||||
try {
|
||||
await api.providers.respondToRequest({
|
||||
sessionId: activeThread.session.sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error:
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Failed to submit approval decision.",
|
||||
});
|
||||
} finally {
|
||||
setRespondingRequestIds((existing) =>
|
||||
existing.filter((id) => id !== requestId),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const onModelSelect = (model: string) => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
@@ -335,6 +450,81 @@ export default function ChatView() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pendingApprovals.length > 0 && (
|
||||
<div className="mx-4 mt-3 space-y-2">
|
||||
{pendingApprovals.map((approval) => {
|
||||
const isResponding = respondingRequestIds.includes(
|
||||
approval.requestId,
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={approval.requestId}
|
||||
className="rounded-lg border border-amber-300/20 bg-amber-500/[0.07] px-3 py-2"
|
||||
>
|
||||
<p className="text-xs font-medium text-amber-100">
|
||||
{approval.requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: "File-change approval requested"}
|
||||
</p>
|
||||
{approval.detail && (
|
||||
<p
|
||||
className="mt-1 truncate font-mono text-[11px] text-amber-100/75"
|
||||
title={approval.detail}
|
||||
>
|
||||
{approval.detail}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/[0.15] bg-white/[0.08] px-2 py-1 text-[11px] text-[#e8e8e8] transition-colors duration-150 hover:bg-white/[0.13] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() =>
|
||||
void onRespondToApproval(approval.requestId, "accept")
|
||||
}
|
||||
>
|
||||
Approve once
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() =>
|
||||
void onRespondToApproval(
|
||||
approval.requestId,
|
||||
"acceptForSession",
|
||||
)
|
||||
}
|
||||
>
|
||||
Always allow this session
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/[0.15] px-2 py-1 text-[11px] text-[#d8d8d8] transition-colors duration-150 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() =>
|
||||
void onRespondToApproval(approval.requestId, "decline")
|
||||
}
|
||||
>
|
||||
Decline
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() =>
|
||||
void onRespondToApproval(approval.requestId, "cancel")
|
||||
}
|
||||
>
|
||||
Cancel turn
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
{activeThread.messages.length === 0 && !isWorking ? (
|
||||
|
||||
@@ -28,6 +28,7 @@ export default function Sidebar() {
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
|
||||
|
||||
const handleAddProject = () => {
|
||||
const cwd = newCwd.trim();
|
||||
@@ -79,6 +80,43 @@ export default function Sidebar() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleRuntimeModeChange = useCallback(
|
||||
async (mode: "approval-required" | "full-access") => {
|
||||
if (mode === state.runtimeMode) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_RUNTIME_MODE",
|
||||
mode,
|
||||
});
|
||||
|
||||
if (!api) return;
|
||||
|
||||
const sessionIds = state.threads
|
||||
.map((thread) => thread.session)
|
||||
.filter(
|
||||
(session): session is NonNullable<typeof session> =>
|
||||
session !== null && session.status !== "closed",
|
||||
)
|
||||
.map((session) => session.sessionId);
|
||||
|
||||
if (sessionIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSwitchingRuntimeMode(true);
|
||||
try {
|
||||
await Promise.all(
|
||||
sessionIds.map((sessionId) =>
|
||||
api.providers.stopSession({ sessionId }).catch(() => undefined),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setIsSwitchingRuntimeMode(false);
|
||||
}
|
||||
},
|
||||
[api, dispatch, state.runtimeMode, state.threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const isNewThreadShortcut =
|
||||
@@ -151,6 +189,43 @@ export default function Sidebar() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="px-3 pb-3">
|
||||
<div className="rounded-lg border border-white/[0.08] bg-white/[0.03] p-2">
|
||||
<p className="px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-[#a0a0a0]/60">
|
||||
Runtime mode
|
||||
</p>
|
||||
<p className="px-1 pt-0.5 pb-2 text-[10px] text-[#a0a0a0]/45">
|
||||
Switching restarts live sessions.
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md px-2 py-1.5 text-[11px] transition-colors duration-150 ${
|
||||
state.runtimeMode === "approval-required"
|
||||
? "bg-white/12 text-white"
|
||||
: "text-[#a0a0a0]/70 hover:bg-white/[0.06]"
|
||||
}`}
|
||||
disabled={isSwitchingRuntimeMode}
|
||||
onClick={() => void handleRuntimeModeChange("approval-required")}
|
||||
>
|
||||
Approval required
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md px-2 py-1.5 text-[11px] transition-colors duration-150 ${
|
||||
state.runtimeMode === "full-access"
|
||||
? "bg-white/12 text-white"
|
||||
: "text-[#a0a0a0]/70 hover:bg-white/[0.06]"
|
||||
}`}
|
||||
disabled={isSwitchingRuntimeMode}
|
||||
onClick={() => void handleRuntimeModeChange("full-access")}
|
||||
>
|
||||
Full access
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Project list */}
|
||||
<nav className="flex-1 overflow-y-auto px-2">
|
||||
{state.projects.map((project) => {
|
||||
|
||||
@@ -47,6 +47,7 @@ describe("hydratePersistedState", () => {
|
||||
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("filters unknown project references and repairs active thread", () => {
|
||||
@@ -85,11 +86,33 @@ describe("hydratePersistedState", () => {
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
|
||||
expect(hydrated?.activeThreadId).toBe("t-1");
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("hydrates runtime mode from v3 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 3,
|
||||
runtimeMode: "approval-required",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v2 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v3 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
@@ -122,9 +145,11 @@ describe("toPersistedState", () => {
|
||||
],
|
||||
threads: [thread],
|
||||
activeThreadId: "t-1",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(2);
|
||||
expect(persisted.version).toBe(3);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import type { Project, Thread } from "./types";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
} from "./types";
|
||||
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
@@ -36,6 +41,8 @@ const persistedStateBodySchema = z.object({
|
||||
activeThreadId: z.string().min(1).nullable(),
|
||||
});
|
||||
|
||||
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
|
||||
|
||||
export const persistedStateV1Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(1).optional(),
|
||||
});
|
||||
@@ -44,7 +51,13 @@ export const persistedStateV2Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(2).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV3Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(3).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV3Schema,
|
||||
persistedStateV2Schema,
|
||||
persistedStateV1Schema,
|
||||
]);
|
||||
@@ -53,6 +66,7 @@ export interface PersistedStoreSnapshot {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
function maybeMigrateLegacyModel(
|
||||
@@ -134,14 +148,18 @@ export function hydratePersistedState(
|
||||
activeThreadId: hasActiveThread
|
||||
? parsedState.data.activeThreadId
|
||||
: (threads[0]?.id ?? null),
|
||||
runtimeMode:
|
||||
"runtimeMode" in parsedState.data
|
||||
? parsedState.data.runtimeMode
|
||||
: DEFAULT_RUNTIME_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV2Schema> {
|
||||
): z.infer<typeof persistedStateV3Schema> {
|
||||
return {
|
||||
version: 2,
|
||||
version: 3,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
@@ -152,5 +170,6 @@ export function toPersistedState(
|
||||
createdAt: thread.createdAt,
|
||||
})),
|
||||
activeThreadId: state.activeThreadId,
|
||||
runtimeMode: state.runtimeMode,
|
||||
};
|
||||
}
|
||||
@@ -17,7 +17,12 @@ import {
|
||||
asString,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { Project, Thread } from "./types";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -36,7 +41,8 @@ type Action =
|
||||
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string };
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -44,16 +50,21 @@ export interface AppState {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "codething:renderer-state:v2";
|
||||
const LEGACY_PERSISTED_STATE_KEY = "codething:renderer-state:v1";
|
||||
const PERSISTED_STATE_KEY = "codething:renderer-state:v3";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"codething:renderer-state:v2",
|
||||
"codething:renderer-state:v1",
|
||||
] as const;
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
};
|
||||
|
||||
@@ -64,12 +75,14 @@ function readPersistedState(): AppState {
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawLegacy = window.localStorage.getItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
const [legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
|
||||
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
|
||||
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
|
||||
const raw = rawCurrent ?? rawLegacyV2 ?? rawLegacyV1;
|
||||
if (!raw) return initialState;
|
||||
const hydrated = hydratePersistedState(
|
||||
raw,
|
||||
!rawCurrent && Boolean(rawLegacy),
|
||||
!rawCurrent && !rawLegacyV2 && Boolean(rawLegacyV1),
|
||||
);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
@@ -87,7 +100,9 @@ function persistState(state: AppState): void {
|
||||
PERSISTED_STATE_KEY,
|
||||
JSON.stringify(toPersistedState(state)),
|
||||
);
|
||||
window.localStorage.removeItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
@@ -285,6 +300,12 @@ function reducer(state: AppState, action: Action): AppState {
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
@@ -28,6 +29,7 @@ export const IPC_CHANNELS = {
|
||||
providerTurnInterrupt: "provider:turn:interrupt",
|
||||
providerSessionStop: "provider:session:stop",
|
||||
providerSessionList: "provider:session:list",
|
||||
providerRequestRespond: "provider:request:respond",
|
||||
providerEvent: "provider:event",
|
||||
} as const;
|
||||
|
||||
@@ -59,6 +61,7 @@ export interface NativeApi {
|
||||
input: ProviderSendTurnInput,
|
||||
) => Promise<ProviderTurnStartResult>;
|
||||
interruptTurn: (input: ProviderInterruptTurnInput) => Promise<void>;
|
||||
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
providerEventSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
} from "./provider";
|
||||
@@ -45,4 +46,40 @@ describe("providerEventSchema", () => {
|
||||
});
|
||||
expect(parsed.method).toBe("item/agentMessage/delta");
|
||||
});
|
||||
|
||||
it("accepts request approval metadata", () => {
|
||||
const parsed = providerEventSchema.parse({
|
||||
id: "evt_2",
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req_123",
|
||||
requestKind: "command",
|
||||
});
|
||||
expect(parsed.requestId).toBe("req_123");
|
||||
expect(parsed.requestKind).toBe("command");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerRespondToRequestInputSchema", () => {
|
||||
it("accepts valid decisions", () => {
|
||||
const parsed = providerRespondToRequestInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
requestId: "req_1",
|
||||
decision: "acceptForSession",
|
||||
});
|
||||
expect(parsed.decision).toBe("acceptForSession");
|
||||
});
|
||||
|
||||
it("rejects unknown decisions", () => {
|
||||
expect(() =>
|
||||
providerRespondToRequestInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
requestId: "req_1",
|
||||
decision: "always",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,15 @@ export const providerSandboxModeSchema = z.enum([
|
||||
"danger-full-access",
|
||||
]);
|
||||
|
||||
export const providerRequestKindSchema = z.enum(["command", "file-change"]);
|
||||
|
||||
export const providerApprovalDecisionSchema = z.enum([
|
||||
"accept",
|
||||
"acceptForSession",
|
||||
"decline",
|
||||
"cancel",
|
||||
]);
|
||||
|
||||
export const providerSessionStatusSchema = z.enum([
|
||||
"connecting",
|
||||
"ready",
|
||||
@@ -65,6 +74,12 @@ export const providerStopSessionInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerRespondToRequestInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1),
|
||||
decision: providerApprovalDecisionSchema,
|
||||
});
|
||||
|
||||
export const providerEventKindSchema = z.enum([
|
||||
"session",
|
||||
"notification",
|
||||
@@ -83,6 +98,8 @@ export const providerEventSchema = z.object({
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
itemId: z.string().min(1).optional(),
|
||||
requestId: z.string().min(1).optional(),
|
||||
requestKind: providerRequestKindSchema.optional(),
|
||||
textDelta: z.string().optional(),
|
||||
payload: z.unknown().optional(),
|
||||
});
|
||||
@@ -92,6 +109,10 @@ export type ProviderApprovalPolicy = z.infer<
|
||||
typeof providerApprovalPolicySchema
|
||||
>;
|
||||
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
|
||||
export type ProviderRequestKind = z.infer<typeof providerRequestKindSchema>;
|
||||
export type ProviderApprovalDecision = z.infer<
|
||||
typeof providerApprovalDecisionSchema
|
||||
>;
|
||||
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
|
||||
export type ProviderSession = z.infer<typeof providerSessionSchema>;
|
||||
export type ProviderSessionStartInput = z.input<
|
||||
@@ -107,5 +128,8 @@ export type ProviderInterruptTurnInput = z.input<
|
||||
export type ProviderStopSessionInput = z.input<
|
||||
typeof providerStopSessionInputSchema
|
||||
>;
|
||||
export type ProviderRespondToRequestInput = z.input<
|
||||
typeof providerRespondToRequestInputSchema
|
||||
>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
Reference in new issue
Block a user