Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex de5270e2d7 Persist provider runtime mode settings
Store approval policy and sandbox mode in provider session runtime records, carry them through session recovery, and cover the behavior with provider layer tests.

Co-authored-by: codex <[email protected]>
2026-02-27 21:55:23 -08:00
Julius Marminge d48b42c017 fix type 2026-02-27 21:32:15 -08:00
Julius Marminge fb45896588 simplify layers 2026-02-27 21:30:46 -08:00
Julius Marminge b52518f85f Flatten attachment paths with message-prefixed filenames
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
2026-02-27 21:30:46 -08:00
Julius Marminge 3e99019af8 Serve attachments using URL-encoded relative paths
- Read attachment route paths without URI decoding before normalization
- Align test fixture paths with encoded thread/message/file names
2026-02-27 21:30:46 -08:00
Julius Marminge 7d4b02689e Overwrite attachment bytes for repeated message attachment index
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
2026-02-27 21:30:46 -08:00
Julius Marminge 9962f57ad0 Preserve empty attachment updates in projection pipeline
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
2026-02-27 21:30:46 -08:00
Julius Marminge 8b538e2802 dedupe 2026-02-27 21:30:46 -08:00
Julius Marminge a6c57e169a nit 2026-02-27 21:30:46 -08:00
Julius Marminge 6f92f0a668 kewl 2026-02-27 21:30:46 -08:00
Julius Marminge 35817601ff fixxx 2026-02-27 21:30:46 -08:00
Julius Marminge 2b154db938 Add gallery navigation to expanded chat image previews
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
2026-02-27 21:30:46 -08:00
Julius Marminge b9ff7aa5cd Make attachment writes transactional and decode attachment URLs
- Stage attachment file writes until projector transactions commit, then apply write/prune/delete side effects
- Remove orphaned attachment files on thread revert and delete thread attachment dirs on thread deletion
- Serve URL-encoded attachment paths in `wsServer` and stream file responses
- Add regression tests for rollback safety, revert/delete cleanup, and encoded attachment URLs
2026-02-27 21:30:46 -08:00
Julius Marminge b5188e8cea Harden attachment materialization and static file path handling
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
2026-02-27 21:30:46 -08:00
Julius Marminge 992db16586 Persist and serve projected message image attachments
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
2026-02-27 21:30:46 -08:00
Julius Marminge 2aad749e24 Reuse persisted cwd when recovering stale provider sessions
- Read and validate `cwd` from persisted runtime payload when restarting sessions
- Apply persisted `cwd` during stale-session recovery paths, including `sendTurn`
- Add tests to verify resumed sessions preserve the original working directory
2026-02-27 20:58:21 -08:00
9 changed files with 160 additions and 2 deletions

No files matched your search

@@ -50,6 +50,8 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
adapter_key,
provider_thread_id,
status,
approval_policy,
sandbox_mode,
last_seen_at,
resume_cursor_json,
runtime_payload_json
@@ -61,6 +63,8 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
${runtime.adapterKey},
${runtime.providerThreadId},
${runtime.status},
${runtime.approvalPolicy},
${runtime.sandboxMode},
${runtime.lastSeenAt},
${runtime.resumeCursor},
${runtime.runtimePayload}
@@ -72,6 +76,8 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
adapter_key = excluded.adapter_key,
provider_thread_id = excluded.provider_thread_id,
status = excluded.status,
approval_policy = excluded.approval_policy,
sandbox_mode = excluded.sandbox_mode,
last_seen_at = excluded.last_seen_at,
resume_cursor_json = excluded.resume_cursor_json,
runtime_payload_json = excluded.runtime_payload_json
@@ -90,6 +96,8 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
adapter_key AS "adapterKey",
provider_thread_id AS "providerThreadId",
status,
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
last_seen_at AS "lastSeenAt",
resume_cursor_json AS "resumeCursor",
runtime_payload_json AS "runtimePayload"
@@ -110,6 +118,8 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
adapter_key AS "adapterKey",
provider_thread_id AS "providerThreadId",
status,
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
last_seen_at AS "lastSeenAt",
resume_cursor_json AS "resumeCursor",
runtime_payload_json AS "runtimePayload"
@@ -19,6 +19,7 @@ import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
import Migration0005 from "./Migrations/005_Projections.ts";
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
import Migration0008 from "./Migrations/008_ProviderSessionRuntimeModeColumns.ts";
/**
* Migration loader with all migrations defined inline.
@@ -38,6 +39,7 @@ const loader = Migrator.fromRecord({
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
"7_ProjectionThreadMessageAttachments": Migration0007,
"8_ProviderSessionRuntimeModeColumns": Migration0008,
});
/**
@@ -0,0 +1,31 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
const DEFAULT_APPROVAL_POLICY = "never";
const DEFAULT_SANDBOX_MODE = "workspace-write";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
`;
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
`;
yield* sql`
UPDATE provider_session_runtime
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
WHERE approval_policy IS NULL
`;
yield* sql`
UPDATE provider_session_runtime
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
WHERE sandbox_mode IS NULL
`;
});
@@ -7,6 +7,8 @@
*/
import {
IsoDateTime,
ProviderApprovalPolicy,
ProviderSandboxMode,
ProviderSessionId,
ProviderSessionRuntimeStatus,
ProviderThreadId,
@@ -24,6 +26,8 @@ export const ProviderSessionRuntime = Schema.Struct({
adapterKey: Schema.String,
providerThreadId: Schema.NullOr(ProviderThreadId),
status: ProviderSessionRuntimeStatus,
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
lastSeenAt: IsoDateTime,
resumeCursor: Schema.NullOr(Schema.Unknown),
runtimePayload: Schema.NullOr(Schema.Unknown),
@@ -327,6 +327,8 @@ it.effect(
return yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project",
approvalPolicy: "never",
sandboxMode: "danger-full-access",
});
}).pipe(Effect.provide(firstProviderLayer));
@@ -378,7 +380,10 @@ it.effect(
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: startedSession.threadId,
approvalPolicy: "never",
sandboxMode: "danger-full-access",
},
],
]);
@@ -451,6 +456,8 @@ routing.layer("ProviderServiceLive routing", (it) => {
const initial = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project",
approvalPolicy: "never",
sandboxMode: "danger-full-access",
});
yield* routing.codex.stopSession(initial.sessionId);
routing.codex.startSession.mockClear();
@@ -465,7 +472,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: initial.threadId,
approvalPolicy: "never",
sandboxMode: "danger-full-access",
},
],
]);
@@ -475,6 +485,42 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project-send-turn",
approvalPolicy: "never",
sandboxMode: "danger-full-access",
});
yield* provider.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
sessionId: initial.sessionId,
input: "resume",
attachments: [],
});
assert.deepEqual(routing.codex.startSession.mock.calls, [
[
{
provider: "codex",
cwd: "/tmp/project-send-turn",
resumeThreadId: initial.threadId,
approvalPolicy: "never",
sandboxMode: "danger-full-access",
},
],
]);
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
}),
);
it.effect("stops all sessions and clears adapter runtime", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -18,6 +18,8 @@ import {
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
type ProviderApprovalPolicy,
type ProviderSandboxMode,
type ProviderRuntimeEvent,
type ProviderSession,
} from "@t3tools/contracts";
@@ -93,6 +95,18 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
};
}
function readPersistedCwd(
runtimePayload: ProviderSessionBinding["runtimePayload"],
): string | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
if (typeof rawCwd !== "string") return undefined;
const trimmed = rawCwd.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const canonicalEventLogger =
@@ -143,6 +157,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
session: ProviderSession,
operation: string,
threadId: ThreadId,
options?: {
readonly approvalPolicy?: ProviderApprovalPolicy;
readonly sandboxMode?: ProviderSandboxMode;
},
) =>
Effect.gen(function* () {
const providerThreadId = session.threadId;
@@ -159,6 +177,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId,
providerThreadId,
status: toRuntimeStatus(session),
...(options?.approvalPolicy !== undefined
? { approvalPolicy: options.approvalPolicy }
: {}),
...(options?.sandboxMode !== undefined ? { sandboxMode: options.sandboxMode } : {}),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session),
});
@@ -231,6 +253,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const resumeThreadId = input.binding.providerThreadId ?? undefined;
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const persistedApprovalPolicy = input.binding.approvalPolicy;
const persistedSandboxMode = input.binding.sandboxMode;
const existing =
resumeThreadId === undefined
? undefined
@@ -240,6 +264,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
existing,
`${input.operation}:upsertExistingSession`,
input.binding.threadId,
{
...(persistedApprovalPolicy ? { approvalPolicy: persistedApprovalPolicy } : {}),
...(persistedSandboxMode ? { sandboxMode: persistedSandboxMode } : {}),
},
);
yield* directory.upsert({
sessionId: input.staleSessionId,
@@ -266,10 +294,15 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(resumeThreadId ? { resumeThreadId } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
...(persistedApprovalPolicy ? { approvalPolicy: persistedApprovalPolicy } : {}),
...(persistedSandboxMode ? { sandboxMode: persistedSandboxMode } : {}),
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
@@ -282,6 +315,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
resumed,
`${input.operation}:upsertRecoveredSession`,
input.binding.threadId,
{
...(persistedApprovalPolicy ? { approvalPolicy: persistedApprovalPolicy } : {}),
...(persistedSandboxMode ? { sandboxMode: persistedSandboxMode } : {}),
},
);
yield* directory.upsert({
@@ -401,7 +438,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
yield* upsertSessionBinding(session, "ProviderService.startSession", threadId);
yield* upsertSessionBinding(session, "ProviderService.startSession", threadId, {
approvalPolicy: input.approvalPolicy,
sandboxMode: input.sandboxMode,
});
return session;
});
@@ -118,6 +118,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
threadId,
providerThreadId,
status: "starting",
approvalPolicy: "never",
sandboxMode: "danger-full-access",
resumeCursor: {
resumeThreadId: "provider-thread-runtime",
},
@@ -131,6 +133,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
sessionId,
provider: "codex",
status: "running",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimePayload: {
activeTurnId: "turn-1",
},
@@ -144,6 +148,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
assert.equal(runtime.value.threadId, threadId);
assert.equal(runtime.value.providerThreadId, providerThreadId);
assert.equal(runtime.value.status, "running");
assert.equal(runtime.value.approvalPolicy, "on-request");
assert.equal(runtime.value.sandboxMode, "workspace-write");
assert.deepEqual(runtime.value.resumeCursor, {
resumeThreadId: providerThreadId,
});
@@ -1,4 +1,9 @@
import { ProviderSessionId, type ProviderKind } from "@t3tools/contracts";
import {
ProviderSessionId,
type ProviderApprovalPolicy,
type ProviderKind,
type ProviderSandboxMode,
} from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
@@ -13,6 +18,9 @@ import {
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
function toPersistenceError(operation: string) {
return (cause: unknown) =>
new ProviderSessionDirectoryPersistenceError({
@@ -76,6 +84,8 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
adapterKey: value.adapterKey,
providerThreadId: value.providerThreadId,
status: value.status,
approvalPolicy: value.approvalPolicy,
sandboxMode: value.sandboxMode,
resumeCursor: value.resumeCursor,
runtimePayload: value.runtimePayload,
}),
@@ -113,6 +123,11 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
? binding.providerThreadId
: (existingRuntime?.providerThreadId ?? null),
status: binding.status ?? existingRuntime?.status ?? "running",
approvalPolicy:
binding.approvalPolicy ??
existingRuntime?.approvalPolicy ??
DEFAULT_APPROVAL_POLICY,
sandboxMode: binding.sandboxMode ?? existingRuntime?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
lastSeenAt: now,
resumeCursor:
binding.resumeCursor !== undefined
@@ -8,7 +8,9 @@
* @module ProviderSessionDirectory
*/
import type {
ProviderApprovalPolicy,
ProviderKind,
ProviderSandboxMode,
ProviderSessionId,
ProviderSessionRuntimeStatus,
ProviderThreadId,
@@ -30,6 +32,8 @@ export interface ProviderSessionBinding {
readonly adapterKey?: string;
readonly providerThreadId?: ProviderThreadId | null;
readonly status?: ProviderSessionRuntimeStatus;
readonly approvalPolicy?: ProviderApprovalPolicy;
readonly sandboxMode?: ProviderSandboxMode;
readonly resumeCursor?: unknown | null;
readonly runtimePayload?: unknown | null;
}