Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8aadcff89 | ||
|
|
b9bb89cf52 | ||
|
|
c03bb95282 | ||
|
|
05aa27a0d9 |
No files matched your search
@@ -90,7 +90,7 @@ This plan intentionally removes migration code instead of improving it. The targ
|
||||
- Replace always-true catch-up sequence assertion with monotonic/defined sequence checks.
|
||||
- Update/add tests for Group A/B/C behavior changes.
|
||||
|
||||
## Workstream 3: Review Thread Triage/Closure Strategy
|
||||
## Workstream 3: Review Thread Triage/Closure Strategy [COMPLETE]
|
||||
|
||||
### Threads closed by deletion (Workstream 1)
|
||||
- Legacy renderer import flow/race concerns in root route.
|
||||
@@ -103,6 +103,56 @@ This plan intentionally removes migration code instead of improving it. The targ
|
||||
### Threads closed with rationale (no change)
|
||||
- Keep concise “not adopted” notes only where behavior is intentional and safe.
|
||||
|
||||
### Disposition Matrix (Ready for PR Thread Closure)
|
||||
- `superseded-by-deletion`
|
||||
- Legacy renderer-state import path comments (root-route import race, legacy import RPC/schema/service concerns).
|
||||
- Rationale: Workstream 1 deleted the entire runtime migration pathway and removed related contracts/callers/handlers.
|
||||
- `fixed`
|
||||
- `listMessages` pagination progress now advances by fetched row count.
|
||||
- `withTransaction` post-commit event emission no longer surfaces listener exceptions as write failures.
|
||||
- `checkpointTurnCount = 0` is preserved in summary merge logic.
|
||||
- Out-of-order `item/started` no longer clobbers accumulated assistant text.
|
||||
- Provider checkpoint revert no longer returns failure when persistence follow-up write fails.
|
||||
- Generic `threads.update` is explicitly unsupported; canonical path is `threads.updateTerminalState`.
|
||||
- `wsServer.stop()` now closes persistence only when internally owned.
|
||||
- `StateDb` closes DB on migration failure and preserves original transaction error if rollback also fails.
|
||||
- `sqliteAdapter` now emits explicit guidance when `node:sqlite` is unavailable.
|
||||
- `appSettings` hydration now guards against overwriting optimistic writes.
|
||||
- `thread.upsert` reducer path now safely defaults missing terminal arrays.
|
||||
- Sidebar no-API fallback now creates a local thread.
|
||||
- Duplicate `updateBranch` write path removed from `BranchToolbar`; canonical write remains in `ChatView` effect.
|
||||
- `declined-with-rationale`
|
||||
- None in this workstream. No remaining high/medium CR findings required intentional non-adoption.
|
||||
|
||||
### Evidence Anchors for Thread Replies
|
||||
- Server behavior fixes:
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/sqliteAdapter.ts`
|
||||
- Web/contracts fixes:
|
||||
- `packages/contracts/src/ws.ts`
|
||||
- `packages/contracts/src/ipc.ts`
|
||||
- `apps/web/src/wsNativeApi.ts`
|
||||
- `apps/web/src/appSettings.ts`
|
||||
- `apps/web/src/store.ts`
|
||||
- `apps/web/src/components/Sidebar.tsx`
|
||||
- `apps/web/src/components/BranchToolbar.tsx`
|
||||
- Regression coverage:
|
||||
- `apps/server/src/persistenceService.test.ts`
|
||||
- `apps/server/src/wsServer.test.ts`
|
||||
- `apps/server/src/stateDb.test.ts`
|
||||
- `apps/server/src/sqliteAdapter.test.ts`
|
||||
- `apps/web/src/appSettings.test.ts`
|
||||
- `apps/web/src/store.test.ts`
|
||||
- `apps/web/src/components/Sidebar.logic.test.ts`
|
||||
- `packages/contracts/src/ws.test.ts`
|
||||
|
||||
### Suggested Reply Templates
|
||||
- `superseded-by-deletion`: "Superseded by Workstream 1 removal of legacy renderer-state migration path; related RPC/schema/client callsites were deleted."
|
||||
- `fixed`: "Fixed in Workstream 2 with tests added; see referenced file(s) and regression coverage."
|
||||
- `declined-with-rationale`: "Intentional behavior retained; safe by design and documented here with rationale and test coverage."
|
||||
|
||||
## Execution Order
|
||||
1. Contracts + protocol deletions (Workstream 1.1).
|
||||
2. Server deletion and compilation fixes (Workstream 1.2).
|
||||
|
||||
@@ -34,15 +34,6 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Persistence architecture
|
||||
|
||||
Server persistence now runs on the Effect v4 beta SQL stack with SQLite:
|
||||
|
||||
- Effect SQL drivers are selected by runtime (Bun in development, Node in production).
|
||||
- Schema bootstrapping is managed through the Effect SQL migrator.
|
||||
- Persistence reads/writes are organized into Effect-backed repositories under `apps/server/src/persistence/`.
|
||||
- State synchronization (`state.bootstrap`, ordered `state.event`, `state.catchUp`) is still exposed through the existing WebSocket API surface, with typed state-event payloads shared through `@t3tools/contracts`.
|
||||
|
||||
## Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
@@ -72,6 +63,19 @@ bun run dist:desktop:dmg
|
||||
npx t3
|
||||
```
|
||||
|
||||
## Remote usage (phone/tablet/laptop)
|
||||
|
||||
To run the server on one device and control it from another (for example over Tailscale), use:
|
||||
|
||||
- `docs/remote-access.md`
|
||||
|
||||
This includes:
|
||||
|
||||
- architecture and security model
|
||||
- production setup for remote control
|
||||
- remote dev setup with hot reload
|
||||
- troubleshooting for cross-device connectivity
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
|
||||
@@ -17,10 +17,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/sql-sqlite-bun": "^4.0.0-beta.6",
|
||||
"@effect/sql-sqlite-node": "^4.0.0-beta.6",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "^4.0.0-beta.6",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import path from "node:path";
|
||||
|
||||
export interface PersistenceConfig {
|
||||
dbPath: string;
|
||||
legacyProjectsJsonPath?: string;
|
||||
}
|
||||
|
||||
export function resolvePersistenceConfig(input: PersistenceConfig): PersistenceConfig {
|
||||
const resolved: PersistenceConfig = {
|
||||
dbPath: path.resolve(input.dbPath),
|
||||
};
|
||||
if (input.legacyProjectsJsonPath) {
|
||||
resolved.legacyProjectsJsonPath = path.resolve(input.legacyProjectsJsonPath);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import {
|
||||
type AppSettings,
|
||||
type AppSettingsUpdateInput,
|
||||
appSettingsSchema,
|
||||
appSettingsUpdateInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export function resolveAppSettings(metadataValue: unknown): AppSettings {
|
||||
const parsed = appSettingsSchema.safeParse(metadataValue);
|
||||
if (parsed.success) {
|
||||
return parsed.data;
|
||||
}
|
||||
return appSettingsSchema.parse({});
|
||||
}
|
||||
|
||||
export function buildUpdatedAppSettings(
|
||||
current: AppSettings,
|
||||
rawPatch: AppSettingsUpdateInput,
|
||||
): AppSettings {
|
||||
const patch = appSettingsUpdateInputSchema.parse(rawPatch);
|
||||
return appSettingsSchema.parse({
|
||||
...current,
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import {
|
||||
type ProviderSendTurnInput,
|
||||
type StateMessage,
|
||||
stateMessageSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export function messageDocId(threadId: string, messageId: string): string {
|
||||
return `message:${threadId}:${messageId}`;
|
||||
}
|
||||
|
||||
export function buildUserTurnMessage(input: {
|
||||
turn: ProviderSendTurnInput;
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
createdAt: string;
|
||||
}): StateMessage {
|
||||
const text = input.turn.clientMessageText ?? input.turn.input ?? "";
|
||||
const inputAttachments = input.turn.attachments ?? [];
|
||||
const attachments =
|
||||
inputAttachments.length > 0
|
||||
? inputAttachments.map((attachment, index) => ({
|
||||
type: "image" as const,
|
||||
id: `${input.messageId}:image:${index + 1}`,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
}))
|
||||
: undefined;
|
||||
return stateMessageSchema.parse({
|
||||
id: input.messageId,
|
||||
threadId: input.threadId,
|
||||
role: "user",
|
||||
text,
|
||||
...(attachments ? { attachments } : {}),
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.createdAt,
|
||||
streaming: false,
|
||||
});
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export function normalizeCwd(rawCwd: string): string {
|
||||
const resolved = path.resolve(rawCwd.trim());
|
||||
const normalized = path.normalize(resolved);
|
||||
if (process.platform === "win32") {
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function isDirectory(cwd: string): boolean {
|
||||
try {
|
||||
return fs.statSync(cwd).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function inferProjectName(cwd: string): string {
|
||||
const name = path.basename(cwd);
|
||||
return name.length > 0 ? name : "project";
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { ProviderEvent } from "@t3tools/contracts";
|
||||
|
||||
export function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
export function normalizeProviderItemType(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const normalized = value.trim();
|
||||
if (normalized.length === 0) return undefined;
|
||||
return normalized.replace(/[_\-\s]+/g, "").toLowerCase();
|
||||
}
|
||||
|
||||
export function parseThreadIdFromEventPayload(payload: unknown): string | null {
|
||||
const record = asObject(payload);
|
||||
const threadId = asString(record?.threadId) ?? asString(record?.thread_id);
|
||||
if (threadId) return threadId;
|
||||
const thread = asObject(record?.thread);
|
||||
return asString(thread?.id) ?? null;
|
||||
}
|
||||
|
||||
export function parseTurnIdFromEvent(event: ProviderEvent): string | null {
|
||||
if (event.turnId) return event.turnId;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return asString(turn?.id) ?? null;
|
||||
}
|
||||
|
||||
export function parseAssistantItemId(event: ProviderEvent): string | null {
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
const itemType = asString(item?.type);
|
||||
if (itemType !== "agentMessage") return null;
|
||||
return asString(item?.id) ?? event.itemId ?? null;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import {
|
||||
type StateBootstrapResult,
|
||||
type StateBootstrapThread,
|
||||
type StateCatchUpResult,
|
||||
type StateEvent,
|
||||
type StateListMessagesResult,
|
||||
type StateMessage,
|
||||
type StateProject,
|
||||
stateBootstrapResultSchema,
|
||||
stateCatchUpResultSchema,
|
||||
stateListMessagesResultSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export function buildStateBootstrapResult(input: {
|
||||
projects: StateProject[];
|
||||
threads: StateBootstrapThread[];
|
||||
lastStateSeq: number;
|
||||
}): StateBootstrapResult {
|
||||
return stateBootstrapResultSchema.parse(input);
|
||||
}
|
||||
|
||||
export function buildStateCatchUpResult(input: {
|
||||
events: StateEvent[];
|
||||
lastStateSeq: number;
|
||||
}): StateCatchUpResult {
|
||||
return stateCatchUpResultSchema.parse(input);
|
||||
}
|
||||
|
||||
export function buildStateListMessagesResult(input: {
|
||||
messages: StateMessage[];
|
||||
total: number;
|
||||
offset: number;
|
||||
pageSize: number;
|
||||
}): StateListMessagesResult {
|
||||
const nextOffset = input.offset + input.pageSize;
|
||||
return stateListMessagesResultSchema.parse({
|
||||
messages: input.messages,
|
||||
total: input.total,
|
||||
nextOffset: nextOffset < input.total ? nextOffset : null,
|
||||
});
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import type { StateThread } from "@t3tools/contracts";
|
||||
|
||||
const MAX_TERMINAL_COUNT = 4;
|
||||
const DEFAULT_TERMINAL_ID = "default";
|
||||
|
||||
export function normalizeTerminalIds(ids: readonly string[]): string[] {
|
||||
const normalized = [
|
||||
...new Set(ids.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].slice(0, MAX_TERMINAL_COUNT);
|
||||
if (normalized.length > 0) {
|
||||
return normalized;
|
||||
}
|
||||
return [DEFAULT_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: readonly string[],
|
||||
terminalIds: readonly string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const validTerminalIds = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIds.has(id))
|
||||
.slice(0, MAX_TERMINAL_COUNT);
|
||||
}
|
||||
|
||||
export function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
groups: StateThread["terminalGroups"],
|
||||
terminalIds: readonly string[],
|
||||
): StateThread["terminalGroups"] {
|
||||
const validTerminalIds = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const normalizedGroups: StateThread["terminalGroups"] = [];
|
||||
|
||||
for (const group of groups) {
|
||||
const groupTerminalIds = [
|
||||
...new Set(group.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].filter((terminalId) => {
|
||||
if (!validTerminalIds.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_TERMINAL_ID);
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (normalizedGroups.length > 0) {
|
||||
return normalizedGroups;
|
||||
}
|
||||
|
||||
return [{ id: fallbackGroupId(DEFAULT_TERMINAL_ID), terminalIds: [DEFAULT_TERMINAL_ID] }];
|
||||
}
|
||||
|
||||
export function normalizeThread(thread: StateThread): StateThread {
|
||||
const terminalIds = normalizeTerminalIds(thread.terminalIds);
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds);
|
||||
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (terminalIds[0] ?? DEFAULT_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(thread.terminalGroups, terminalIds);
|
||||
const activeGroupId =
|
||||
terminalGroups.find((group) => group.id === thread.activeTerminalGroupId)?.id ??
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(activeTerminalId);
|
||||
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: activeGroupId,
|
||||
};
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { mergeTurnSummaryFiles, summarizeUnifiedDiff } from "./turnSummaries";
|
||||
|
||||
describe("turnSummaries domain helpers", () => {
|
||||
test("summarizeUnifiedDiff returns per-file diff stats", () => {
|
||||
const diff = [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/src/example.ts",
|
||||
"+++ b/src/example.ts",
|
||||
"@@ -1,2 +1,3 @@",
|
||||
" line1",
|
||||
"-line2",
|
||||
"+line2-updated",
|
||||
"+line3",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
expect(summarizeUnifiedDiff(diff)).toEqual([
|
||||
{
|
||||
path: "src/example.ts",
|
||||
kind: "change",
|
||||
additions: 2,
|
||||
deletions: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("mergeTurnSummaryFiles merges by path while preserving prior fields", () => {
|
||||
const existing = [
|
||||
{ path: "a.ts", kind: "modified" as const, additions: 1, deletions: 2 },
|
||||
{ path: "b.ts", kind: "deleted" as const, additions: 0, deletions: 4 },
|
||||
];
|
||||
const incoming = [
|
||||
{ path: "a.ts", additions: 3, deletions: 5 },
|
||||
{ path: "c.ts", kind: "added" as const, additions: 7, deletions: 0 },
|
||||
];
|
||||
|
||||
expect(mergeTurnSummaryFiles(existing, incoming)).toEqual([
|
||||
{ path: "a.ts", kind: "modified", additions: 3, deletions: 5 },
|
||||
{ path: "b.ts", kind: "deleted", additions: 0, deletions: 4 },
|
||||
{ path: "c.ts", kind: "added", additions: 7, deletions: 0 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,115 +0,0 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import type { StateTurnDiffFileChange } from "@t3tools/contracts";
|
||||
|
||||
function parsePathFromDiff(diff: string): string | null {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
|
||||
if (bPath?.[1]) return bPath[1];
|
||||
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
|
||||
if (gitHeader?.[1]) return gitHeader[1];
|
||||
const direct = normalized.match(/^\+\+\+ (.+)$/m);
|
||||
if (!direct?.[1] || direct[1] === "/dev/null") {
|
||||
return null;
|
||||
}
|
||||
return direct[1];
|
||||
}
|
||||
|
||||
function splitUnifiedDiffByFile(diff: string): Map<string, string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const byPath = new Map<string, string>();
|
||||
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
|
||||
|
||||
if (headerMatches.length === 0) {
|
||||
const pathFromDiff = parsePathFromDiff(normalized);
|
||||
if (pathFromDiff) {
|
||||
byPath.set(pathFromDiff, normalized.trim());
|
||||
}
|
||||
return byPath;
|
||||
}
|
||||
|
||||
for (let index = 0; index < headerMatches.length; index += 1) {
|
||||
const match = headerMatches[index];
|
||||
if (!match) continue;
|
||||
const start = match.index ?? 0;
|
||||
const end = headerMatches[index + 1]?.index ?? normalized.length;
|
||||
const segment = normalized.slice(start, end).trim();
|
||||
const pathFromDiff = parsePathFromDiff(segment);
|
||||
if (!pathFromDiff || segment.length === 0) continue;
|
||||
byPath.set(pathFromDiff, segment);
|
||||
}
|
||||
|
||||
return byPath;
|
||||
}
|
||||
|
||||
function countDiffStat(patch: string): { additions: number; deletions: number } {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
||||
if (line.startsWith("+")) {
|
||||
additions += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
deletions += 1;
|
||||
}
|
||||
}
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
export function summarizeUnifiedDiff(diff: string): StateTurnDiffFileChange[] {
|
||||
try {
|
||||
const parsedPatches = parsePatchFiles(diff, "state-turn-summary", false);
|
||||
const files: StateTurnDiffFileChange[] = [];
|
||||
for (const patch of parsedPatches) {
|
||||
for (const file of patch.files) {
|
||||
const additions = file.hunks.reduce((sum, hunk) => sum + hunk.additionLines, 0);
|
||||
const deletions = file.hunks.reduce((sum, hunk) => sum + hunk.deletionLines, 0);
|
||||
files.push({
|
||||
path: file.name,
|
||||
kind: file.type,
|
||||
additions,
|
||||
deletions,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (files.length > 0) {
|
||||
return files.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
} catch {
|
||||
// Fallback below.
|
||||
}
|
||||
|
||||
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
|
||||
const fallback: StateTurnDiffFileChange[] = [];
|
||||
for (const [filePath, fileDiff] of fileDiffsByPath) {
|
||||
const stat = countDiffStat(fileDiff);
|
||||
fallback.push({
|
||||
path: filePath,
|
||||
additions: stat.additions,
|
||||
deletions: stat.deletions,
|
||||
});
|
||||
}
|
||||
return fallback.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
export function mergeTurnSummaryFiles(
|
||||
existing: StateTurnDiffFileChange[],
|
||||
incoming: StateTurnDiffFileChange[],
|
||||
): StateTurnDiffFileChange[] {
|
||||
const byPath = new Map(existing.map((file) => [file.path, { ...file }] as const));
|
||||
for (const file of incoming) {
|
||||
const previous = byPath.get(file.path);
|
||||
if (!previous) {
|
||||
byPath.set(file.path, { ...file });
|
||||
continue;
|
||||
}
|
||||
byPath.set(file.path, {
|
||||
...previous,
|
||||
...(file.kind !== undefined ? { kind: file.kind } : {}),
|
||||
...(file.additions !== undefined ? { additions: file.additions } : {}),
|
||||
...(file.deletions !== undefined ? { deletions: file.deletions } : {}),
|
||||
});
|
||||
}
|
||||
return Array.from(byPath.values()).toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export class PersistenceInitializationError extends Error {
|
||||
constructor(message: string, options?: { cause?: unknown }) {
|
||||
super(message, options);
|
||||
this.name = "PersistenceInitializationError";
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
project_id TEXT NULL,
|
||||
thread_id TEXT NULL,
|
||||
sort_key INTEGER NULL,
|
||||
schema_version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
data_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
session_id TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT NOT NULL,
|
||||
thread_id TEXT NULL,
|
||||
turn_id TEXT NULL,
|
||||
item_id TEXT NULL,
|
||||
request_id TEXT NULL,
|
||||
request_kind TEXT NULL,
|
||||
text_delta TEXT NULL,
|
||||
message TEXT NULL,
|
||||
payload_json TEXT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS state_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
value_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind ON documents(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_project_kind ON documents(project_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_thread_kind_sort ON documents(thread_id, kind, sort_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind_updated ON documents(kind, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_session_seq ON provider_events(session_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_thread_seq ON provider_events(thread_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_state_events_seq ON state_events(seq);
|
||||
@@ -1,53 +0,0 @@
|
||||
export const MIGRATION_V1_SQL = `
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
project_id TEXT NULL,
|
||||
thread_id TEXT NULL,
|
||||
sort_key INTEGER NULL,
|
||||
schema_version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
data_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
session_id TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT NOT NULL,
|
||||
thread_id TEXT NULL,
|
||||
turn_id TEXT NULL,
|
||||
item_id TEXT NULL,
|
||||
request_id TEXT NULL,
|
||||
request_kind TEXT NULL,
|
||||
text_delta TEXT NULL,
|
||||
message TEXT NULL,
|
||||
payload_json TEXT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS state_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
value_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind ON documents(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_project_kind ON documents(project_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_thread_kind_sort ON documents(thread_id, kind, sort_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind_updated ON documents(kind, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_session_seq ON provider_events(session_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_thread_seq ON provider_events(thread_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_state_events_seq ON state_events(seq);
|
||||
`;
|
||||
@@ -1,57 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { PersistenceInitializationError } from "./errors";
|
||||
import { applyStateDbPragmas, runPersistenceMigrations } from "./migrator";
|
||||
import type { SqliteDatabase, SqliteStatement } from "./sqliteAdapter";
|
||||
|
||||
class MockStatement implements SqliteStatement {
|
||||
run(): unknown {
|
||||
return undefined;
|
||||
}
|
||||
get(): unknown {
|
||||
return undefined;
|
||||
}
|
||||
all(): unknown[] {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class MockSqliteDatabase implements SqliteDatabase {
|
||||
readonly statements: string[] = [];
|
||||
|
||||
exec(sql: string): void {
|
||||
this.statements.push(sql);
|
||||
}
|
||||
|
||||
prepare(): SqliteStatement {
|
||||
return new MockStatement();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
// no-op for tests
|
||||
}
|
||||
}
|
||||
|
||||
describe("persistence migrator", () => {
|
||||
test("applies sqlite pragmas in order", () => {
|
||||
const db = new MockSqliteDatabase();
|
||||
applyStateDbPragmas(db);
|
||||
expect(db.statements).toEqual([
|
||||
"PRAGMA journal_mode=WAL;",
|
||||
"PRAGMA synchronous=FULL;",
|
||||
"PRAGMA busy_timeout=5000;",
|
||||
"PRAGMA foreign_keys=ON;",
|
||||
]);
|
||||
});
|
||||
|
||||
test("throws when database adapter is not Effect-backed", () => {
|
||||
const db = new MockSqliteDatabase();
|
||||
expect(() => runPersistenceMigrations(db)).toThrow(PersistenceInitializationError);
|
||||
expect(db.statements).toEqual([
|
||||
"PRAGMA journal_mode=WAL;",
|
||||
"PRAGMA synchronous=FULL;",
|
||||
"PRAGMA busy_timeout=5000;",
|
||||
"PRAGMA foreign_keys=ON;",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Migrator from "effect/unstable/sql/Migrator";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { PersistenceInitializationError } from "./errors";
|
||||
import { MIGRATION_V1_SQL } from "./migrations";
|
||||
import type { EffectSqliteDatabaseAdapter, SqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
export const STATE_DB_SCHEMA_VERSION = 1;
|
||||
|
||||
export function applyStateDbPragmas(db: SqliteDatabase): void {
|
||||
db.exec("PRAGMA journal_mode=WAL;");
|
||||
db.exec("PRAGMA synchronous=FULL;");
|
||||
db.exec("PRAGMA busy_timeout=5000;");
|
||||
db.exec("PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
function normalizeStatementBatch(sql: string): string[] {
|
||||
const normalized = sql.replace(/\r\n/g, "\n");
|
||||
const statements: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let inBacktick = false;
|
||||
|
||||
for (const char of normalized) {
|
||||
if (char === "'" && !inDoubleQuote && !inBacktick) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === '"' && !inSingleQuote && !inBacktick) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === "`" && !inSingleQuote && !inDoubleQuote) {
|
||||
inBacktick = !inBacktick;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === ";" && !inSingleQuote && !inDoubleQuote && !inBacktick) {
|
||||
const statement = current.trim();
|
||||
if (statement.length > 0) {
|
||||
statements.push(statement);
|
||||
}
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
current += char;
|
||||
}
|
||||
|
||||
const trailing = current.trim();
|
||||
if (trailing.length > 0) {
|
||||
statements.push(trailing);
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
function isEffectSqliteDatabase(db: SqliteDatabase): db is EffectSqliteDatabaseAdapter {
|
||||
return "runWithSqlClient" in db && typeof db.runWithSqlClient === "function";
|
||||
}
|
||||
|
||||
function runEffectMigrations(db: EffectSqliteDatabaseAdapter): void {
|
||||
const migrationV1Effect = Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
for (const statement of normalizeStatementBatch(MIGRATION_V1_SQL)) {
|
||||
yield* sql.unsafe(statement).raw;
|
||||
}
|
||||
yield* sql.unsafe(`PRAGMA user_version=${STATE_DB_SCHEMA_VERSION};`).raw;
|
||||
});
|
||||
|
||||
const migrationLoader = Migrator.fromRecord({
|
||||
"0001_initial_schema": migrationV1Effect,
|
||||
});
|
||||
const runMigrations = Migrator.make({});
|
||||
|
||||
db.runWithSqlClient(
|
||||
runMigrations({ loader: migrationLoader }).pipe(
|
||||
Effect.mapError((error) => {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to run Effect SQL migrations for state database.";
|
||||
return new Error(message, { cause: error });
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function runPersistenceMigrations(db: SqliteDatabase): void {
|
||||
applyStateDbPragmas(db);
|
||||
if (!isEffectSqliteDatabase(db)) {
|
||||
throw new PersistenceInitializationError("Expected Effect-backed sqlite adapter for migrations");
|
||||
}
|
||||
runEffectMigrations(db);
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import {
|
||||
DataJsonRowSchema,
|
||||
DocumentRowSchema,
|
||||
TotalCountRowSchema,
|
||||
} from "../schema";
|
||||
|
||||
export interface DocumentRow {
|
||||
id: string;
|
||||
kind: string;
|
||||
project_id: string | null;
|
||||
thread_id: string | null;
|
||||
sort_key: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
data_json: string;
|
||||
}
|
||||
|
||||
interface DataJsonRow {
|
||||
data_json: string;
|
||||
}
|
||||
|
||||
export interface PaginatedMessagePayloadsRow {
|
||||
data_json: string;
|
||||
}
|
||||
|
||||
export interface TotalCountRow {
|
||||
total?: number | bigint;
|
||||
}
|
||||
|
||||
function toSafeInteger(value: unknown, fallback = 0): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const decodeDocumentRows = Schema.decodeUnknownSync(Schema.Array(DocumentRowSchema));
|
||||
const decodeDataJsonRows = Schema.decodeUnknownSync(Schema.Array(DataJsonRowSchema));
|
||||
const decodeTotalCountRows = Schema.decodeUnknownSync(Schema.Array(TotalCountRowSchema));
|
||||
|
||||
export const getDocumentRowById = (
|
||||
id: string,
|
||||
): Effect.Effect<DocumentRow | null, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<DocumentRow>(
|
||||
"SELECT id, kind, project_id, thread_id, sort_key, created_at, updated_at, data_json FROM documents WHERE id = ? LIMIT 1;",
|
||||
[id],
|
||||
)
|
||||
.unprepared) as DocumentRow[];
|
||||
const parsedRows = decodeDocumentRows(rows);
|
||||
return parsedRows[0] ?? null;
|
||||
});
|
||||
|
||||
export const upsertDocument = (input: {
|
||||
id: string;
|
||||
kind: "project" | "thread" | "message" | "turn_summary";
|
||||
projectId: string | null;
|
||||
threadId: string | null;
|
||||
sortKey: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
dataJson: string;
|
||||
}): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql
|
||||
.unsafe(
|
||||
`INSERT INTO documents (
|
||||
id,
|
||||
kind,
|
||||
project_id,
|
||||
thread_id,
|
||||
sort_key,
|
||||
schema_version,
|
||||
created_at,
|
||||
updated_at,
|
||||
data_json
|
||||
) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
kind = excluded.kind,
|
||||
project_id = excluded.project_id,
|
||||
thread_id = excluded.thread_id,
|
||||
sort_key = excluded.sort_key,
|
||||
schema_version = excluded.schema_version,
|
||||
updated_at = excluded.updated_at,
|
||||
data_json = excluded.data_json;`,
|
||||
[
|
||||
input.id,
|
||||
input.kind,
|
||||
input.projectId,
|
||||
input.threadId,
|
||||
input.sortKey,
|
||||
input.createdAt,
|
||||
input.updatedAt,
|
||||
input.dataJson,
|
||||
],
|
||||
)
|
||||
.raw;
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
export const readNextSortKey = (
|
||||
kind: "message" | "turn_summary",
|
||||
threadId: string,
|
||||
): Effect.Effect<number, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ next_sort_key?: number }>(
|
||||
"SELECT COALESCE(MAX(sort_key), 0) + 1 AS next_sort_key FROM documents WHERE kind = ? AND thread_id = ?;",
|
||||
[kind, threadId],
|
||||
)
|
||||
.unprepared) as Array<{ next_sort_key?: number }>;
|
||||
return rows[0]?.next_sort_key ?? 1;
|
||||
});
|
||||
|
||||
export const listProjectPayloads = (): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<DataJsonRow>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'project' ORDER BY updated_at DESC, created_at DESC;",
|
||||
)
|
||||
.unprepared) as DataJsonRow[];
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const listThreadPayloads = (): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<DataJsonRow>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'thread' ORDER BY updated_at DESC, created_at DESC;",
|
||||
)
|
||||
.unprepared) as DataJsonRow[];
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const listThreadPayloadsByProject = (
|
||||
projectId: string,
|
||||
): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<DataJsonRow>("SELECT data_json FROM documents WHERE kind = 'thread' AND project_id = ?;", [
|
||||
projectId,
|
||||
])
|
||||
.unprepared) as DataJsonRow[];
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const findThreadPayloadByRuntimeThreadId = (
|
||||
runtimeThreadId: string,
|
||||
): Effect.Effect<string | null, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<DataJsonRow>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'thread' AND json_extract(data_json, '$.codexThreadId') = ? LIMIT 1;",
|
||||
[runtimeThreadId],
|
||||
)
|
||||
.unprepared) as DataJsonRow[];
|
||||
const parsedRows = decodeDataJsonRows(rows);
|
||||
return parsedRows[0]?.data_json ?? null;
|
||||
});
|
||||
|
||||
export const deleteDocumentsByProjectId = (
|
||||
projectId: string,
|
||||
): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("DELETE FROM documents WHERE project_id = ?;", [projectId]).raw;
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
export const deleteDocumentsByThreadId = (
|
||||
threadId: string,
|
||||
): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("DELETE FROM documents WHERE thread_id = ?;", [threadId]).raw;
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
export const deleteDocumentByIdAndKind = (
|
||||
id: string,
|
||||
kind: "thread" | "message" | "turn_summary",
|
||||
): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("DELETE FROM documents WHERE id = ? AND kind = ?;", [id, kind]).raw;
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
export const listMessagePayloadsForThread = (
|
||||
threadId: string,
|
||||
): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ data_json: string }>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC;",
|
||||
[threadId],
|
||||
)
|
||||
.unprepared) as Array<{ data_json: string }>;
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const listPaginatedMessagePayloadsForThread = (input: {
|
||||
threadId: string;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<PaginatedMessagePayloadsRow>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC LIMIT ? OFFSET ?;",
|
||||
[input.threadId, input.limit, input.offset],
|
||||
)
|
||||
.unprepared) as PaginatedMessagePayloadsRow[];
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const countMessagesForThread = (
|
||||
threadId: string,
|
||||
): Effect.Effect<number, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<TotalCountRow>("SELECT COUNT(1) AS total FROM documents WHERE kind = 'message' AND thread_id = ?;", [
|
||||
threadId,
|
||||
])
|
||||
.unprepared) as TotalCountRow[];
|
||||
const parsedRows = decodeTotalCountRows(rows);
|
||||
return toSafeInteger(parsedRows[0]?.total, 0);
|
||||
});
|
||||
|
||||
export const listMessagePayloadsForThreadDesc = (
|
||||
threadId: string,
|
||||
): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ data_json: string }>(
|
||||
`SELECT data_json
|
||||
FROM documents
|
||||
WHERE kind = 'message' AND thread_id = ?
|
||||
ORDER BY sort_key DESC, updated_at DESC;`,
|
||||
[threadId],
|
||||
)
|
||||
.unprepared) as Array<{ data_json: string }>;
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
|
||||
export const listTurnSummaryPayloadsForThread = (
|
||||
threadId: string,
|
||||
): Effect.Effect<string[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ data_json: string }>(
|
||||
"SELECT data_json FROM documents WHERE kind = 'turn_summary' AND thread_id = ? ORDER BY sort_key DESC, updated_at DESC;",
|
||||
[threadId],
|
||||
)
|
||||
.unprepared) as Array<{ data_json: string }>;
|
||||
return decodeDataJsonRows(rows).map((row) => row.data_json);
|
||||
});
|
||||
@@ -1,43 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { MetadataRowSchema } from "../schema";
|
||||
|
||||
function tryParseJson(value: string): unknown {
|
||||
try {
|
||||
return JSON.parse(value) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const decodeMetadataRows = Schema.decodeUnknownSync(Schema.Array(MetadataRowSchema));
|
||||
|
||||
export const readMetadataValue = (
|
||||
key: string,
|
||||
): Effect.Effect<unknown | null, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ value_json: string }>("SELECT value_json FROM metadata WHERE key = ? LIMIT 1;", [key])
|
||||
.unprepared) as Array<{ value_json: string }>;
|
||||
const row = decodeMetadataRows(rows)[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
return tryParseJson(row.value_json);
|
||||
});
|
||||
|
||||
export const writeMetadataValue = (
|
||||
key: string,
|
||||
value: unknown,
|
||||
): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql
|
||||
.unsafe(
|
||||
"INSERT INTO metadata (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json;",
|
||||
[key, JSON.stringify(value)],
|
||||
)
|
||||
.raw;
|
||||
}).pipe(Effect.asVoid);
|
||||
@@ -1,147 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import {
|
||||
CompletedProviderItemRowSchema,
|
||||
ProviderEventInsertStatsSchema,
|
||||
} from "../schema";
|
||||
|
||||
function toSafeInteger(value: unknown, fallback = 0): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const decodeProviderEventInsertStats = Schema.decodeUnknownSync(ProviderEventInsertStatsSchema);
|
||||
const decodeCompletedProviderItemRows = Schema.decodeUnknownSync(
|
||||
Schema.Array(CompletedProviderItemRowSchema),
|
||||
);
|
||||
|
||||
export interface CompletedProviderItemRow {
|
||||
item_id: string | null;
|
||||
payload_json: string | null;
|
||||
}
|
||||
|
||||
export const insertProviderEvent = (input: {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
provider: string;
|
||||
kind: string;
|
||||
method: string;
|
||||
runtimeThreadId: string | null;
|
||||
turnId: string | null;
|
||||
itemId: string | null;
|
||||
requestId: string | null;
|
||||
requestKind: string | null;
|
||||
textDelta: string | null;
|
||||
message: string | null;
|
||||
payloadJson: string | null;
|
||||
createdAt: string;
|
||||
}): Effect.Effect<number, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rawResult = (yield* sql
|
||||
.unsafe<{ changes?: number | bigint }>(
|
||||
`INSERT OR IGNORE INTO provider_events (
|
||||
id,
|
||||
session_id,
|
||||
provider,
|
||||
kind,
|
||||
method,
|
||||
thread_id,
|
||||
turn_id,
|
||||
item_id,
|
||||
request_id,
|
||||
request_kind,
|
||||
text_delta,
|
||||
message,
|
||||
payload_json,
|
||||
created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
|
||||
[
|
||||
input.id,
|
||||
input.sessionId,
|
||||
input.provider,
|
||||
input.kind,
|
||||
input.method,
|
||||
input.runtimeThreadId,
|
||||
input.turnId,
|
||||
input.itemId,
|
||||
input.requestId,
|
||||
input.requestKind,
|
||||
input.textDelta,
|
||||
input.message,
|
||||
input.payloadJson,
|
||||
input.createdAt,
|
||||
],
|
||||
)
|
||||
.raw) as { changes?: number | bigint };
|
||||
const stats = decodeProviderEventInsertStats(rawResult);
|
||||
return toSafeInteger(stats.changes, 0);
|
||||
});
|
||||
|
||||
export const listCompletedItemEventsBySessionTurn = (input: {
|
||||
sessionId: string;
|
||||
turnId: string;
|
||||
}): Effect.Effect<CompletedProviderItemRow[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<CompletedProviderItemRow>(
|
||||
`SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE session_id = ? AND turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
[input.sessionId, input.turnId],
|
||||
)
|
||||
.unprepared) as CompletedProviderItemRow[];
|
||||
return decodeCompletedProviderItemRows(rows).map((row) => ({
|
||||
item_id: row.item_id,
|
||||
payload_json: row.payload_json,
|
||||
}));
|
||||
});
|
||||
|
||||
export const listCompletedItemEventsByThreadTurn = (input: {
|
||||
runtimeThreadId: string;
|
||||
turnId: string;
|
||||
}): Effect.Effect<CompletedProviderItemRow[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<CompletedProviderItemRow>(
|
||||
`SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
[input.runtimeThreadId, input.turnId],
|
||||
)
|
||||
.unprepared) as CompletedProviderItemRow[];
|
||||
return decodeCompletedProviderItemRows(rows).map((row) => ({
|
||||
item_id: row.item_id,
|
||||
payload_json: row.payload_json,
|
||||
}));
|
||||
});
|
||||
|
||||
export const listCompletedItemEventsByTurn = (
|
||||
turnId: string,
|
||||
): Effect.Effect<CompletedProviderItemRow[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<CompletedProviderItemRow>(
|
||||
`SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
[turnId],
|
||||
)
|
||||
.unprepared) as CompletedProviderItemRow[];
|
||||
return decodeCompletedProviderItemRows(rows).map((row) => ({
|
||||
item_id: row.item_id,
|
||||
payload_json: row.payload_json,
|
||||
}));
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { runPersistenceMigrations } from "../migrator";
|
||||
import { runWithSqlClient } from "../runtime";
|
||||
import { openPersistenceSqliteDatabase } from "../sqliteLayer";
|
||||
import { appendStateEvent, listStateEventsAfterSeq, readLastStateSeq } from "./stateEventsRepo";
|
||||
|
||||
describe("stateEventsRepo", () => {
|
||||
test("appends and lists ordered state events", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-persistence-state-events-repo-"));
|
||||
const dbPath = path.join(dir, "state.sqlite");
|
||||
try {
|
||||
const db = openPersistenceSqliteDatabase(dbPath);
|
||||
try {
|
||||
runPersistenceMigrations(db);
|
||||
const createdAt = new Date().toISOString();
|
||||
const first = runWithSqlClient(
|
||||
db,
|
||||
appendStateEvent({
|
||||
eventType: "project.upsert",
|
||||
entityId: "project-1",
|
||||
payload: {
|
||||
project: {
|
||||
id: "project-1",
|
||||
name: "Project One",
|
||||
cwd: "/tmp/project-one",
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
const second = runWithSqlClient(
|
||||
db,
|
||||
appendStateEvent({
|
||||
eventType: "project.delete",
|
||||
entityId: "project-1",
|
||||
payload: { projectId: "project-1" },
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const lastSeq = runWithSqlClient(db, readLastStateSeq);
|
||||
const events = runWithSqlClient(db, listStateEventsAfterSeq(first.seq - 1));
|
||||
|
||||
expect(first.seq).toBeGreaterThan(0);
|
||||
expect(second.seq).toBeGreaterThan(first.seq);
|
||||
expect(lastSeq).toBe(second.seq);
|
||||
expect(events.map((event) => event.eventType)).toEqual(["project.upsert", "project.delete"]);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,102 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { stateEventSchema, type StateEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
StateEventRowSchema,
|
||||
StateSeqRowSchema,
|
||||
StateEventInsertStatsSchema,
|
||||
} from "../schema";
|
||||
|
||||
interface StateEventRow {
|
||||
seq: number;
|
||||
event_type: string;
|
||||
entity_id: string;
|
||||
payload_json: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
function toSafeInteger(value: unknown, fallback = 0): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function tryParseJson(value: string): unknown {
|
||||
try {
|
||||
return JSON.parse(value) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const decodeStateEventRows = Schema.decodeUnknownSync(Schema.Array(StateEventRowSchema));
|
||||
const decodeStateSeqRows = Schema.decodeUnknownSync(Schema.Array(StateSeqRowSchema));
|
||||
const decodeStateEventInsertStats = Schema.decodeUnknownSync(StateEventInsertStatsSchema);
|
||||
|
||||
export const appendStateEvent = (input: {
|
||||
eventType: string;
|
||||
entityId: string;
|
||||
payload: unknown;
|
||||
createdAt: string;
|
||||
}): Effect.Effect<StateEvent, unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const result = (yield* sql
|
||||
.unsafe<{ changes?: number | bigint; lastInsertRowid?: number | bigint }>(
|
||||
"INSERT INTO state_events (event_type, entity_id, payload_json, created_at) VALUES (?, ?, ?, ?);",
|
||||
[input.eventType, input.entityId, JSON.stringify(input.payload), input.createdAt],
|
||||
)
|
||||
.raw) as {
|
||||
changes?: number | bigint;
|
||||
lastInsertRowid?: number | bigint;
|
||||
};
|
||||
const stats = decodeStateEventInsertStats(result);
|
||||
|
||||
return stateEventSchema.parse({
|
||||
seq: toSafeInteger(stats.lastInsertRowid, 0),
|
||||
eventType: input.eventType,
|
||||
entityId: input.entityId,
|
||||
payload: input.payload,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
export const readLastStateSeq: Effect.Effect<number, unknown, SqlClient.SqlClient> = Effect.gen(
|
||||
function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<{ seq?: number | bigint }>(
|
||||
"SELECT COALESCE(MAX(seq), 0) AS seq FROM state_events;",
|
||||
)
|
||||
.unprepared) as Array<{ seq?: number | bigint }>;
|
||||
const parsedRows = decodeStateSeqRows(rows);
|
||||
return toSafeInteger(parsedRows[0]?.seq, 0);
|
||||
},
|
||||
);
|
||||
|
||||
export const listStateEventsAfterSeq = (
|
||||
afterSeq: number,
|
||||
): Effect.Effect<StateEvent[], unknown, SqlClient.SqlClient> =>
|
||||
Effect.gen(function*() {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const rows = (yield* sql
|
||||
.unsafe<StateEventRow>(
|
||||
"SELECT seq, event_type, entity_id, payload_json, created_at FROM state_events WHERE seq > ? ORDER BY seq ASC;",
|
||||
[afterSeq],
|
||||
)
|
||||
.unprepared) as StateEventRow[];
|
||||
return decodeStateEventRows(rows).map((row) =>
|
||||
stateEventSchema.parse({
|
||||
seq: row.seq,
|
||||
eventType: row.event_type,
|
||||
entityId: row.entity_id,
|
||||
payload: tryParseJson(row.payload_json),
|
||||
createdAt: row.created_at,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import type { EffectSqliteDatabaseAdapter, SqliteDatabase } from "./sqliteAdapter";
|
||||
import { PersistenceInitializationError } from "./errors";
|
||||
|
||||
function isEffectSqliteDatabase(db: SqliteDatabase): db is EffectSqliteDatabaseAdapter {
|
||||
return "runWithSqlClient" in db && typeof db.runWithSqlClient === "function";
|
||||
}
|
||||
|
||||
export function runWithSqlClient<A>(
|
||||
db: SqliteDatabase,
|
||||
effect: Effect.Effect<A, unknown, SqlClient.SqlClient>,
|
||||
): A {
|
||||
if (isEffectSqliteDatabase(db)) {
|
||||
return db.runWithSqlClient(effect);
|
||||
}
|
||||
throw new PersistenceInitializationError("Expected Effect-backed sqlite adapter");
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DocumentRowSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
kind: Schema.String,
|
||||
project_id: Schema.NullOr(Schema.String),
|
||||
thread_id: Schema.NullOr(Schema.String),
|
||||
sort_key: Schema.NullOr(Schema.Number),
|
||||
created_at: Schema.String,
|
||||
updated_at: Schema.String,
|
||||
data_json: Schema.String,
|
||||
});
|
||||
|
||||
export const DataJsonRowSchema = Schema.Struct({
|
||||
data_json: Schema.String,
|
||||
});
|
||||
|
||||
const NumberOrBigIntSchema = Schema.Union([Schema.Number, Schema.BigInt]);
|
||||
|
||||
export const ProviderEventInsertStatsSchema = Schema.Struct({
|
||||
changes: Schema.optional(Schema.NullOr(NumberOrBigIntSchema)),
|
||||
});
|
||||
|
||||
export const CompletedProviderItemRowSchema = Schema.Struct({
|
||||
item_id: Schema.NullOr(Schema.String),
|
||||
payload_json: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
export const StateEventInsertStatsSchema = Schema.Struct({
|
||||
changes: Schema.optional(Schema.NullOr(NumberOrBigIntSchema)),
|
||||
lastInsertRowid: Schema.optional(Schema.NullOr(NumberOrBigIntSchema)),
|
||||
});
|
||||
|
||||
export const StateEventRowSchema = Schema.Struct({
|
||||
seq: Schema.Number,
|
||||
event_type: Schema.String,
|
||||
entity_id: Schema.String,
|
||||
payload_json: Schema.String,
|
||||
created_at: Schema.String,
|
||||
});
|
||||
|
||||
export const StateSeqRowSchema = Schema.Struct({
|
||||
seq: Schema.optional(Schema.NullOr(NumberOrBigIntSchema)),
|
||||
});
|
||||
|
||||
export const TotalCountRowSchema = Schema.Struct({
|
||||
total: Schema.optional(Schema.NullOr(NumberOrBigIntSchema)),
|
||||
});
|
||||
|
||||
export const MetadataRowSchema = Schema.Struct({
|
||||
value_json: Schema.String,
|
||||
});
|
||||
@@ -1,229 +0,0 @@
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as ServiceMap from "effect/ServiceMap";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export interface SqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
export interface SqliteDatabase {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export interface EffectSqliteDatabaseAdapter extends SqliteDatabase {
|
||||
runWithSqlClient: <A, E>(effect: Effect.Effect<A, E, SqlClient.SqlClient>) => A;
|
||||
}
|
||||
|
||||
interface SqliteDriverModule {
|
||||
SqliteClient?: {
|
||||
layer: (config: { filename: string }) => Layer.Layer<SqlClient.SqlClient>;
|
||||
};
|
||||
}
|
||||
|
||||
function isNodeSqliteUnavailableError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false;
|
||||
}
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
error.message.includes("node:sqlite") ||
|
||||
error.message.includes("@effect/sql-sqlite-node") ||
|
||||
error.message.includes("Only URLs with a scheme in: file, data, and node")
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeStatementBatch(sql: string): string[] {
|
||||
const normalized = sql.replace(/\r\n/g, "\n");
|
||||
const statements: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let inBacktick = false;
|
||||
|
||||
for (const char of normalized) {
|
||||
if (char === "'" && !inDoubleQuote && !inBacktick) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === '"' && !inSingleQuote && !inBacktick) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === "`" && !inSingleQuote && !inDoubleQuote) {
|
||||
inBacktick = !inBacktick;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === ";" && !inSingleQuote && !inDoubleQuote && !inBacktick) {
|
||||
const statement = current.trim();
|
||||
if (statement.length > 0) {
|
||||
statements.push(statement);
|
||||
}
|
||||
current = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
current += char;
|
||||
}
|
||||
|
||||
const trailing = current.trim();
|
||||
if (trailing.length > 0) {
|
||||
statements.push(trailing);
|
||||
}
|
||||
|
||||
return statements;
|
||||
}
|
||||
|
||||
function toSafeInteger(value: unknown, fallback = 0): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
class EffectSqliteDatabase implements SqliteDatabase {
|
||||
private readonly scope: Scope.Closeable;
|
||||
private readonly services: ServiceMap.ServiceMap<SqlClient.SqlClient>;
|
||||
private readonly sql: SqlClient.SqlClient;
|
||||
private closed = false;
|
||||
|
||||
constructor(layer: Layer.Layer<SqlClient.SqlClient>) {
|
||||
this.scope = Effect.runSync(Scope.make());
|
||||
try {
|
||||
this.services = Effect.runSync(Layer.buildWithScope(layer, this.scope));
|
||||
this.sql = Effect.runSync(
|
||||
Effect.provideServices(Effect.service(SqlClient.SqlClient), this.services),
|
||||
);
|
||||
} catch (error) {
|
||||
try {
|
||||
Effect.runSync(Scope.close(this.scope, Exit.void));
|
||||
} catch {
|
||||
// Best effort cleanup on failed adapter construction.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
exec(sql: string): void {
|
||||
for (const statement of normalizeStatementBatch(sql)) {
|
||||
this.runEffect(this.sql.unsafe(statement).raw);
|
||||
}
|
||||
}
|
||||
|
||||
prepare(sql: string): SqliteStatement {
|
||||
return {
|
||||
run: (...params: unknown[]) => this.runStatement(sql, params),
|
||||
get: (...params: unknown[]) => {
|
||||
const rows = this.queryStatement(sql, params);
|
||||
return rows[0];
|
||||
},
|
||||
all: (...params: unknown[]) => this.queryStatement(sql, params),
|
||||
};
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.closed = true;
|
||||
Effect.runSync(Scope.close(this.scope, Exit.void));
|
||||
}
|
||||
|
||||
runWithSqlClient<A, E>(effect: Effect.Effect<A, E, SqlClient.SqlClient>): A {
|
||||
return this.runEffect(effect);
|
||||
}
|
||||
|
||||
private runStatement(sql: string, params: ReadonlyArray<unknown>): unknown {
|
||||
this.runEffect(this.sql.unsafe(sql, params).raw);
|
||||
const stats = this.runEffect(
|
||||
this.sql
|
||||
.unsafe<{ changes?: number | bigint; lastInsertRowid?: number | bigint }>(
|
||||
"SELECT changes() AS changes, last_insert_rowid() AS lastInsertRowid;",
|
||||
)
|
||||
.unprepared,
|
||||
)[0];
|
||||
return {
|
||||
changes: toSafeInteger(stats?.changes, 0),
|
||||
lastInsertRowid: toSafeInteger(stats?.lastInsertRowid, 0),
|
||||
};
|
||||
}
|
||||
|
||||
private queryStatement(sql: string, params: ReadonlyArray<unknown>): unknown[] {
|
||||
return this.runEffect(this.sql.unsafe(sql, params).unprepared) as unknown[];
|
||||
}
|
||||
|
||||
private runEffect<A, E, R>(effect: Effect.Effect<A, E, R>): A {
|
||||
const provided = Effect.provideServices(effect, this.services) as Effect.Effect<A, E, never>;
|
||||
return Effect.runSync(provided);
|
||||
}
|
||||
}
|
||||
|
||||
function openDriverDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
moduleId: string,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
const sqliteDriver = requireFn(moduleId) as SqliteDriverModule;
|
||||
const layer = sqliteDriver.SqliteClient?.layer;
|
||||
if (typeof layer !== "function") {
|
||||
throw new Error(`${moduleId} was loaded but SqliteClient.layer is missing.`);
|
||||
}
|
||||
return new EffectSqliteDatabase(layer({ filename: dbPath })) satisfies EffectSqliteDatabaseAdapter;
|
||||
}
|
||||
|
||||
function openNodeSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
try {
|
||||
return openDriverDatabase(requireFn, "@effect/sql-sqlite-node", dbPath);
|
||||
} catch (error) {
|
||||
if (isNodeSqliteUnavailableError(error)) {
|
||||
throw new Error(
|
||||
"@effect/sql-sqlite-node is unavailable in this runtime. Ensure dependencies are installed and use Node.js 22+ (or run the server with Bun).",
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function openBunSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
return openDriverDatabase(requireFn, "@effect/sql-sqlite-bun", dbPath);
|
||||
}
|
||||
|
||||
export function openSqliteDatabase(
|
||||
dbPath: string,
|
||||
requireFn: ReturnType<typeof createRequire> = createRequire(
|
||||
path.join(process.cwd(), "t3code-sqlite-adapter.cjs"),
|
||||
),
|
||||
runtimeIsBun = Boolean(process.versions.bun),
|
||||
): SqliteDatabase {
|
||||
if (runtimeIsBun) {
|
||||
// Development mode runs in Bun, so use Bun's SQLite adapter
|
||||
return openBunSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
|
||||
return openNodeSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { runPersistenceMigrations } from "./migrator";
|
||||
import { openPersistenceSqliteDatabase } from "./sqliteLayer";
|
||||
|
||||
describe("persistence sqlite layer", () => {
|
||||
test("opens sqlite database and runs migrations idempotently", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-persistence-sqlite-layer-"));
|
||||
const dbPath = path.join(dir, "state.sqlite");
|
||||
try {
|
||||
const db = openPersistenceSqliteDatabase(dbPath);
|
||||
try {
|
||||
runPersistenceMigrations(db);
|
||||
runPersistenceMigrations(db);
|
||||
|
||||
db.prepare(
|
||||
"INSERT INTO metadata (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json;",
|
||||
).run("app.settings.v1", JSON.stringify({ theme: "dark" }));
|
||||
|
||||
const row = db.prepare("SELECT value_json FROM metadata WHERE key = ? LIMIT 1;").get(
|
||||
"app.settings.v1",
|
||||
) as { value_json?: string } | undefined;
|
||||
expect(row?.value_json).toBe(JSON.stringify({ theme: "dark" }));
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
export function openPersistenceSqliteDatabase(dbPath: string): SqliteDatabase {
|
||||
const resolvedPath = path.resolve(dbPath);
|
||||
fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
|
||||
return openSqliteDatabase(resolvedPath);
|
||||
}
|
||||
@@ -102,7 +102,7 @@ describe("PersistenceService", () => {
|
||||
sessionId: "sess-1",
|
||||
};
|
||||
|
||||
service.ingestProviderEvent({
|
||||
const event1 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-1",
|
||||
createdAt: iso(10),
|
||||
@@ -115,8 +115,9 @@ describe("PersistenceService", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(event1?.seq).toBeGreaterThan(0);
|
||||
|
||||
service.ingestProviderEvent({
|
||||
const event2 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-2",
|
||||
createdAt: iso(20),
|
||||
@@ -128,8 +129,9 @@ describe("PersistenceService", () => {
|
||||
delta: "hi",
|
||||
},
|
||||
});
|
||||
expect((event2?.seq ?? 0) > (event1?.seq ?? 0)).toBe(true);
|
||||
|
||||
service.ingestProviderEvent({
|
||||
const event3 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-3",
|
||||
createdAt: iso(30),
|
||||
@@ -142,8 +144,9 @@ describe("PersistenceService", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((event3?.seq ?? 0) > (event2?.seq ?? 0)).toBe(true);
|
||||
|
||||
service.ingestProviderEvent({
|
||||
const event4 = service.ingestProviderEvent({
|
||||
...baseEvent,
|
||||
id: "evt-4",
|
||||
createdAt: iso(40),
|
||||
@@ -156,6 +159,7 @@ describe("PersistenceService", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((event4?.seq ?? 0) > (event3?.seq ?? 0)).toBe(true);
|
||||
|
||||
const snapshot = service.loadSnapshot();
|
||||
expect(snapshot.projects).toHaveLength(1);
|
||||
@@ -179,6 +183,24 @@ describe("PersistenceService", () => {
|
||||
expect(catchUp.events.some((event) => event.eventType === "project.upsert")).toBe(true);
|
||||
expect(catchUp.events.some((event) => event.eventType === "thread.upsert")).toBe(true);
|
||||
expect(catchUp.events.some((event) => event.eventType === "message.upsert")).toBe(true);
|
||||
|
||||
const providerCatchUp = service.providerCatchUp({ afterSeq: 0 });
|
||||
expect(providerCatchUp.lastProviderSeq).toBe(event4?.seq ?? 0);
|
||||
expect(providerCatchUp.events.map((event) => event.id)).toEqual([
|
||||
"evt-1",
|
||||
"evt-2",
|
||||
"evt-3",
|
||||
"evt-4",
|
||||
]);
|
||||
const providerSeqs = providerCatchUp.events.map((event) => event.seq ?? 0);
|
||||
for (let index = 1; index < providerSeqs.length; index += 1) {
|
||||
expect(providerSeqs[index]).toBeGreaterThan(providerSeqs[index - 1] ?? Number.NEGATIVE_INFINITY);
|
||||
}
|
||||
|
||||
const providerCatchUpAfterSecond = service.providerCatchUp({
|
||||
afterSeq: event2?.seq ?? 0,
|
||||
});
|
||||
expect(providerCatchUpAfterSecond.events.map((event) => event.id)).toEqual(["evt-3", "evt-4"]);
|
||||
} finally {
|
||||
service.close();
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,58 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
describe("ProviderManager", () => {
|
||||
it("emits persisted provider events with durable sequence metadata when available", () => {
|
||||
const ingestProviderEvent = vi.fn((event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => ({
|
||||
...event,
|
||||
seq: 11,
|
||||
}));
|
||||
const persistenceService = {
|
||||
ingestProviderEvent,
|
||||
unbindSession: vi.fn(),
|
||||
};
|
||||
const manager = new ProviderManager({
|
||||
persistenceService: persistenceService as never,
|
||||
});
|
||||
const events: Array<{ id: string; seq?: number }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({ id: event.id, seq: event.seq });
|
||||
});
|
||||
|
||||
const internals = manager as unknown as {
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
};
|
||||
|
||||
internals.onCodexEvent({
|
||||
id: "evt-seq-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "turn/started",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
|
||||
expect(ingestProviderEvent).toHaveBeenCalledTimes(1);
|
||||
expect(events).toEqual([{ id: "evt-seq-1", seq: 11 }]);
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("detaches provider event listener and ends thread log streams on dispose", () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
|
||||
@@ -2,9 +2,6 @@ import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Queue from "effect/Queue";
|
||||
|
||||
import {
|
||||
type ProviderCheckpoint,
|
||||
@@ -178,21 +175,16 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private readonly sessionCheckpointCwds = new Map<string, string>();
|
||||
private readonly filesystemLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistenceQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
|
||||
private readonly persistenceWorker = Effect.runFork(this.runPersistenceWorker());
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.enqueuePersistenceEvent(event);
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
this.persistenceService?.unbindSession(event.sessionId);
|
||||
const emittedEvent = this.publishProviderEvent(event);
|
||||
if (!emittedEvent) {
|
||||
return;
|
||||
}
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
this.maybeCaptureFilesystemCheckpoint(emittedEvent);
|
||||
};
|
||||
|
||||
constructor(options: ProviderManagerOptions = {}) {
|
||||
@@ -416,7 +408,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
this.shutdownPersistenceWorker();
|
||||
this.codex.off("event", this.onCodexEvent);
|
||||
for (const stream of this.threadLogStreams.values()) {
|
||||
stream.end();
|
||||
@@ -428,41 +419,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
private runPersistenceWorker(): Effect.Effect<void> {
|
||||
return Effect.forever(
|
||||
Effect.flatMap(Queue.take(this.persistenceQueue), (event) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
this.persistenceService?.ingestProviderEvent(event);
|
||||
} catch {
|
||||
// Persistence failures should not break provider streaming.
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private enqueuePersistenceEvent(event: ProviderEvent): void {
|
||||
try {
|
||||
Effect.runSync(Queue.offer(this.persistenceQueue, event));
|
||||
} catch {
|
||||
// Best effort ingest queue; runtime event stream should continue.
|
||||
}
|
||||
}
|
||||
|
||||
private shutdownPersistenceWorker(): void {
|
||||
try {
|
||||
Effect.runSync(Queue.shutdown(this.persistenceQueue));
|
||||
} catch {
|
||||
// Ignore queue shutdown failures during dispose.
|
||||
}
|
||||
try {
|
||||
Effect.runSync(Fiber.interrupt(this.persistenceWorker));
|
||||
} catch {
|
||||
// Ignore worker interrupt failures during dispose.
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeFilesystemCheckpointing(
|
||||
session: ProviderSession,
|
||||
preferredCwd?: string,
|
||||
@@ -583,7 +539,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
}
|
||||
|
||||
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
|
||||
this.emit("event", {
|
||||
this.publishProviderEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
@@ -603,7 +559,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
message: string,
|
||||
threadId?: string,
|
||||
): void {
|
||||
this.emit("event", {
|
||||
this.publishProviderEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
@@ -615,6 +571,26 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
});
|
||||
}
|
||||
|
||||
private publishProviderEvent(event: ProviderEvent): ProviderEvent | null {
|
||||
let emittedEvent = event;
|
||||
try {
|
||||
const persistedEvent = this.persistenceService?.ingestProviderEvent(event);
|
||||
if (this.persistenceService && !persistedEvent) {
|
||||
return null;
|
||||
}
|
||||
emittedEvent = persistedEvent ?? event;
|
||||
} catch {
|
||||
// Persistence failures should not break provider streaming.
|
||||
}
|
||||
|
||||
this.routeEventToThreadLog(emittedEvent);
|
||||
if (emittedEvent.method === "session/closed" || emittedEvent.method === "session/exited") {
|
||||
this.persistenceService?.unbindSession(emittedEvent.sessionId);
|
||||
}
|
||||
this.emit("event", emittedEvent);
|
||||
return emittedEvent;
|
||||
}
|
||||
|
||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
||||
const next = previous.catch(() => undefined).then(fn);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { openSqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
describe("sqliteAdapter", () => {
|
||||
it("opens a database and runs basic statements", () => {
|
||||
const db = openSqliteDatabase(":memory:");
|
||||
db.exec("CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL);");
|
||||
|
||||
const insertResult = db.prepare("INSERT INTO sample (value) VALUES (?);").run("hello") as {
|
||||
changes?: number;
|
||||
lastInsertRowid?: number;
|
||||
};
|
||||
expect(insertResult.changes).toBe(1);
|
||||
|
||||
const row = db.prepare("SELECT value FROM sample WHERE id = ?;").get(1) as
|
||||
| { value?: string }
|
||||
| undefined;
|
||||
expect(row?.value).toBe("hello");
|
||||
|
||||
const rows = db.prepare("SELECT value FROM sample ORDER BY id ASC;").all() as Array<{
|
||||
value?: string;
|
||||
}>;
|
||||
expect(rows.map((entry) => entry.value)).toEqual(["hello"]);
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
||||
it("throws a helpful error when node:sqlite is unavailable", () => {
|
||||
const missingModuleError = new Error("No such built-in module: node:sqlite");
|
||||
(missingModuleError as NodeJS.ErrnoException).code = "ERR_UNKNOWN_BUILTIN_MODULE";
|
||||
const requireFn = vi.fn((specifier: string) => {
|
||||
if (specifier === "node:sqlite") {
|
||||
throw missingModuleError;
|
||||
}
|
||||
throw new Error(`Unexpected module request: ${specifier}`);
|
||||
});
|
||||
|
||||
expect(() => openSqliteDatabase(":memory:", requireFn as never, false)).toThrow(
|
||||
"node:sqlite is unavailable",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
export interface SqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
export interface SqliteDatabase {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
interface NodeSqliteModule {
|
||||
DatabaseSync: new (filename: string) => {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
interface BunSqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
interface BunSqliteModule {
|
||||
Database: new (filename: string) => {
|
||||
exec: (sql: string) => unknown;
|
||||
query: (sql: string) => BunSqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
function isNodeSqliteUnavailableError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false;
|
||||
}
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || code === "MODULE_NOT_FOUND") {
|
||||
return true;
|
||||
}
|
||||
return error.message.includes("node:sqlite");
|
||||
}
|
||||
|
||||
function openNodeSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
let nodeSqlite: NodeSqliteModule;
|
||||
try {
|
||||
nodeSqlite = requireFn("node:sqlite") as NodeSqliteModule;
|
||||
} catch (error) {
|
||||
if (isNodeSqliteUnavailableError(error)) {
|
||||
throw new Error(
|
||||
"node:sqlite is unavailable in this runtime. Use Node.js 22+ (or run the server with Bun).",
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (typeof nodeSqlite.DatabaseSync !== "function") {
|
||||
throw new Error(
|
||||
"node:sqlite was loaded but DatabaseSync is missing. Upgrade Node.js or run the server with Bun.",
|
||||
);
|
||||
}
|
||||
const db = new nodeSqlite.DatabaseSync(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => db.prepare(sql),
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function openBunSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
const bunSqlite = requireFn("bun:sqlite") as BunSqliteModule;
|
||||
const db = new bunSqlite.Database(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => {
|
||||
const statement = db.query(sql);
|
||||
return {
|
||||
run: (...params: unknown[]) => statement.run(...params),
|
||||
get: (...params: unknown[]) => statement.get(...params),
|
||||
all: (...params: unknown[]) => statement.all(...params),
|
||||
};
|
||||
},
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function openSqliteDatabase(
|
||||
dbPath: string,
|
||||
requireFn: ReturnType<typeof createRequire> = createRequire(
|
||||
path.join(process.cwd(), "t3code-sqlite-adapter.cjs"),
|
||||
),
|
||||
runtimeIsBun = Boolean(process.versions.bun),
|
||||
): SqliteDatabase {
|
||||
if (runtimeIsBun) {
|
||||
// Development mode runs in Bun, so use Bun's SQLite adapter
|
||||
return openBunSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
|
||||
return openNodeSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { StateDb } from "./stateDb";
|
||||
import * as sqliteAdapter from "./sqliteAdapter";
|
||||
import { STATE_DB_SCHEMA_VERSION } from "./stateMigrations";
|
||||
import * as stateMigrations from "./stateMigrations";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("StateDb", () => {
|
||||
it("creates the SQLite schema and applies migrations", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const stateDb = new StateDb({ dbPath });
|
||||
|
||||
const tables = stateDb.db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table';")
|
||||
.all() as Array<{ name: string }>;
|
||||
const tableNames = new Set(tables.map((table) => table.name));
|
||||
expect(tableNames.has("documents")).toBe(true);
|
||||
expect(tableNames.has("provider_events")).toBe(true);
|
||||
expect(tableNames.has("state_events")).toBe(true);
|
||||
expect(tableNames.has("metadata")).toBe(true);
|
||||
|
||||
const userVersion = stateDb.db
|
||||
.prepare("PRAGMA user_version;")
|
||||
.get() as { user_version: number } | undefined;
|
||||
expect(userVersion?.user_version).toBe(STATE_DB_SCHEMA_VERSION);
|
||||
|
||||
stateDb.close();
|
||||
});
|
||||
|
||||
it("closes the database when migrations fail during construction", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-migration-fail-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const close = vi.fn();
|
||||
const fakeDb = {
|
||||
exec: vi.fn(),
|
||||
prepare: vi.fn(),
|
||||
close,
|
||||
};
|
||||
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
|
||||
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
|
||||
);
|
||||
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {
|
||||
throw new Error("migration failed");
|
||||
});
|
||||
|
||||
expect(() => new StateDb({ dbPath })).toThrow("migration failed");
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves the original transaction error when rollback fails", () => {
|
||||
const tempDir = makeTempDir("t3code-state-db-rollback-fail-");
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const rollbackError = new Error("rollback failed");
|
||||
const exec = vi.fn((sql: string) => {
|
||||
if (sql === "ROLLBACK;") {
|
||||
throw rollbackError;
|
||||
}
|
||||
});
|
||||
const fakeDb = {
|
||||
exec,
|
||||
prepare: vi.fn(),
|
||||
close: vi.fn(),
|
||||
};
|
||||
vi.spyOn(sqliteAdapter, "openSqliteDatabase").mockReturnValue(
|
||||
fakeDb as unknown as sqliteAdapter.SqliteDatabase,
|
||||
);
|
||||
vi.spyOn(stateMigrations, "runStateMigrations").mockImplementation(() => {});
|
||||
|
||||
const stateDb = new StateDb({ dbPath });
|
||||
const originalError = new Error("operation failed");
|
||||
|
||||
let thrown: unknown;
|
||||
try {
|
||||
stateDb.transaction(() => {
|
||||
throw originalError;
|
||||
});
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
|
||||
expect(thrown).toBe(originalError);
|
||||
expect(exec).toHaveBeenCalledWith("ROLLBACK;");
|
||||
stateDb.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
|
||||
import { runStateMigrations } from "./stateMigrations";
|
||||
|
||||
export interface StateDbOptions {
|
||||
dbPath: string;
|
||||
}
|
||||
|
||||
export class StateDb {
|
||||
readonly dbPath: string;
|
||||
readonly db: SqliteDatabase;
|
||||
|
||||
constructor(options: StateDbOptions) {
|
||||
this.dbPath = path.resolve(options.dbPath);
|
||||
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
|
||||
this.db = openSqliteDatabase(this.dbPath);
|
||||
try {
|
||||
runStateMigrations(this.db);
|
||||
} catch (error) {
|
||||
try {
|
||||
this.db.close();
|
||||
} catch {
|
||||
// Best effort close on failed initialization.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
transaction<T>(fn: () => T): T {
|
||||
this.db.exec("BEGIN IMMEDIATE;");
|
||||
try {
|
||||
const result = fn();
|
||||
this.db.exec("COMMIT;");
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
this.db.exec("ROLLBACK;");
|
||||
} catch {
|
||||
// Preserve the original transactional failure.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { SqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
export const STATE_DB_SCHEMA_VERSION = 1;
|
||||
|
||||
export function applyStateDbPragmas(db: SqliteDatabase): void {
|
||||
db.exec("PRAGMA journal_mode=WAL;");
|
||||
db.exec("PRAGMA synchronous=FULL;");
|
||||
db.exec("PRAGMA busy_timeout=5000;");
|
||||
db.exec("PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
function readUserVersion(db: SqliteDatabase): number {
|
||||
const row = db.prepare("PRAGMA user_version;").get() as { user_version?: number } | undefined;
|
||||
const value = row?.user_version;
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function migrationV1(db: SqliteDatabase): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
project_id TEXT NULL,
|
||||
thread_id TEXT NULL,
|
||||
sort_key INTEGER NULL,
|
||||
schema_version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
data_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id TEXT NOT NULL UNIQUE,
|
||||
session_id TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT NOT NULL,
|
||||
thread_id TEXT NULL,
|
||||
turn_id TEXT NULL,
|
||||
item_id TEXT NULL,
|
||||
request_id TEXT NULL,
|
||||
request_kind TEXT NULL,
|
||||
text_delta TEXT NULL,
|
||||
message TEXT NULL,
|
||||
payload_json TEXT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS state_events (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
value_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind ON documents(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_project_kind ON documents(project_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_thread_kind_sort ON documents(thread_id, kind, sort_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_documents_kind_updated ON documents(kind, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_session_seq ON provider_events(session_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_events_thread_seq ON provider_events(thread_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS idx_state_events_seq ON state_events(seq);
|
||||
`);
|
||||
}
|
||||
|
||||
export function runStateMigrations(db: SqliteDatabase): void {
|
||||
applyStateDbPragmas(db);
|
||||
|
||||
const userVersion = readUserVersion(db);
|
||||
if (userVersion >= STATE_DB_SCHEMA_VERSION) {
|
||||
return;
|
||||
}
|
||||
|
||||
db.exec("BEGIN IMMEDIATE;");
|
||||
try {
|
||||
if (userVersion < 1) {
|
||||
migrationV1(db);
|
||||
}
|
||||
db.exec(`PRAGMA user_version=${STATE_DB_SCHEMA_VERSION};`);
|
||||
db.exec("COMMIT;");
|
||||
} catch (error) {
|
||||
db.exec("ROLLBACK;");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -669,6 +669,58 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns durable provider catch-up events ordered by seq", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-provider-catchup-");
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
legacyProjectsJsonPath: path.join(stateDir, "projects.json"),
|
||||
});
|
||||
|
||||
const first = persistenceService.ingestProviderEvent({
|
||||
id: "provider-evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
payload: { turn: { id: "turn-1" } },
|
||||
});
|
||||
const second = persistenceService.ingestProviderEvent({
|
||||
id: "provider-evt-2",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-20T00:00:01.000Z",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
});
|
||||
|
||||
server = createTestServer({ cwd: "/test", stateDir, persistenceService });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.providersCatchUp, {
|
||||
afterSeq: first?.seq ?? 0,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
events: [
|
||||
expect.objectContaining({
|
||||
id: "provider-evt-2",
|
||||
seq: second?.seq,
|
||||
}),
|
||||
],
|
||||
lastProviderSeq: second?.seq ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists app settings through appSettings RPC methods", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-app-settings-");
|
||||
server = createTestServer({ cwd: "/test", stateDir });
|
||||
|
||||
@@ -334,6 +334,9 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
|
||||
case WS_METHODS.providersCatchUp:
|
||||
return persistenceService.providerCatchUp(request.params as never);
|
||||
|
||||
case WS_METHODS.providersListCheckpoints:
|
||||
return providerManager.listCheckpoints(request.params as never);
|
||||
|
||||
|
||||
@@ -182,7 +182,7 @@ export default function BranchToolbar({
|
||||
if (!activeThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-1 sm:px-5 sm:pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{envLocked || activeWorktreePath ? (
|
||||
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
|
||||
@@ -119,6 +119,7 @@ import {
|
||||
setupProjectScript,
|
||||
} from "~/projectScripts";
|
||||
import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -433,6 +434,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||
const canSend =
|
||||
Boolean(api) &&
|
||||
Boolean(activeThread) &&
|
||||
!isSending &&
|
||||
!isConnecting &&
|
||||
(prompt.trim().length > 0 || composerImages.length > 0);
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
@@ -1583,7 +1590,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const ensureSession = useCallback(
|
||||
async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
async (
|
||||
cwdOverride?: string,
|
||||
options?: {
|
||||
silent?: boolean;
|
||||
},
|
||||
): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
const sessionThreadId = activeThread.session.threadId ?? null;
|
||||
@@ -1606,7 +1618,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
const priorCodexThreadId = activeThread.codexThreadId;
|
||||
setIsConnecting(true);
|
||||
const shouldShowConnectingState = !options?.silent;
|
||||
if (shouldShowConnectingState) {
|
||||
setIsConnecting(true);
|
||||
}
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
provider: "codex",
|
||||
@@ -1649,7 +1664,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
if (shouldShowConnectingState) {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
@@ -1679,7 +1696,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
checkpointHydrationSessionRequestRef.current.add(requestKey);
|
||||
setThreadError(activeThreadId, null);
|
||||
void ensureSession().then(
|
||||
void ensureSession(undefined, { silent: true }).then(
|
||||
() => {
|
||||
checkpointHydrationSessionRequestRef.current.delete(requestKey);
|
||||
},
|
||||
@@ -1904,6 +1921,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const triggerSend = () => {
|
||||
if (!canSend) return;
|
||||
const form = textareaRef.current?.form;
|
||||
if (form) {
|
||||
if (typeof form.requestSubmit === "function") {
|
||||
form.requestSubmit();
|
||||
} else {
|
||||
const submitEvent = new Event("submit", { bubbles: true, cancelable: true });
|
||||
const dispatched = form.dispatchEvent(submitEvent);
|
||||
if (!dispatched) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
void onSend({ preventDefault: () => undefined } as FormEvent);
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
if (!api || !activeThread?.session) return;
|
||||
await api.providers.interruptTurn({
|
||||
@@ -2047,7 +2082,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void onSend(e as unknown as FormEvent);
|
||||
triggerSend();
|
||||
}
|
||||
};
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
@@ -2117,7 +2152,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={`flex items-center justify-between border-b border-border px-3 sm:px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
>
|
||||
<ChatHeader
|
||||
activeThreadId={activeThread.id}
|
||||
@@ -2151,7 +2186,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={messagesScrollRef}
|
||||
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
|
||||
className="min-h-0 flex-1 overflow-y-auto px-3 py-3 sm:px-5 sm:py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
>
|
||||
<MessagesTimeline
|
||||
@@ -2176,7 +2211,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{/* Input bar */}
|
||||
<div className={cn("px-5 pt-2", isGitRepo ? "pb-1" : "pb-4")}>
|
||||
<div
|
||||
className={cn(
|
||||
"px-3 pt-2 sm:px-5 max-sm:pb-[calc(0.5rem+env(safe-area-inset-bottom))]",
|
||||
isGitRepo ? "pb-1" : "pb-4",
|
||||
)}
|
||||
>
|
||||
<form onSubmit={onSend} className="mx-auto max-w-3xl">
|
||||
<div
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
|
||||
@@ -2275,8 +2315,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
<div className="flex items-center justify-between px-3 pb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center justify-end px-3 pb-3 sm:justify-between">
|
||||
<div className="hidden items-center gap-1 sm:flex">
|
||||
{/* Model picker */}
|
||||
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
|
||||
|
||||
@@ -2317,7 +2357,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{phase === "running" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105"
|
||||
className="relative z-10 flex h-10 w-10 touch-manipulation items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 pointer-events-auto sm:h-8 sm:w-8 sm:hover:scale-105"
|
||||
onClick={() => void onInterrupt()}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
@@ -2333,11 +2373,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
|
||||
disabled={
|
||||
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
|
||||
}
|
||||
type="button"
|
||||
className="relative z-10 flex h-10 w-10 touch-manipulation items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary pointer-events-auto disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8 sm:hover:scale-105"
|
||||
disabled={!canSend}
|
||||
onClick={triggerSend}
|
||||
aria-label={
|
||||
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
|
||||
}
|
||||
@@ -2387,13 +2426,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
/>
|
||||
<div className="hidden sm:block">
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeThread.terminalOpen && api && activeProject && (
|
||||
@@ -2497,28 +2538,43 @@ const ChatHeader = memo(function ChatHeader({
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
|
||||
<SidebarTrigger className="size-8 md:hidden" />
|
||||
<Separator orientation="vertical" className="md:hidden data-[orientation=vertical]:h-4" />
|
||||
<h2
|
||||
className="truncate text-xs font-medium text-foreground sm:text-sm"
|
||||
title={activeThreadTitle}
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="hidden sm:inline-flex">
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 flex items-center gap-3">
|
||||
<div className="shrink-0 flex items-center gap-1.5 sm:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
onAddScript={onAddProjectScript}
|
||||
onUpdateScript={onUpdateProjectScript}
|
||||
/>
|
||||
<div className="hidden md:block">
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
onAddScript={onAddProjectScript}
|
||||
onUpdateScript={onUpdateProjectScript}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||
<div className="hidden md:block">
|
||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||
</div>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<GitActionsControl api={api} gitCwd={gitCwd} activeThreadId={activeThreadId} />
|
||||
<div className="hidden md:block">
|
||||
<GitActionsControl api={api} gitCwd={gitCwd} activeThreadId={activeThreadId} />
|
||||
</div>
|
||||
)}
|
||||
<Toggle
|
||||
pressed={diffOpen}
|
||||
|
||||
@@ -112,7 +112,11 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
interface SidebarProps {
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
export default function Sidebar({ embedded = false }: SidebarProps = {}) {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
@@ -497,8 +501,12 @@ export default function Sidebar() {
|
||||
};
|
||||
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
|
||||
const rootClassName = embedded
|
||||
? "sidebar flex h-full min-h-0 flex-col bg-card"
|
||||
: "sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card max-sm:w-[36vw] max-sm:min-w-[140px] max-sm:max-w-[200px]";
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||
<aside className={rootClassName}>
|
||||
{/* Branding */}
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
|
||||
@@ -507,7 +515,7 @@ export default function Sidebar() {
|
||||
<span className="truncate text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
|
||||
<span className="hidden rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60 sm:inline-block">
|
||||
{APP_STAGE_LABEL}
|
||||
</span>
|
||||
</div>
|
||||
@@ -563,7 +571,9 @@ export default function Sidebar() {
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
|
||||
<span className="hidden text-[10px] text-muted-foreground/60 sm:inline">
|
||||
{threads.length}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Threads */}
|
||||
@@ -627,7 +637,7 @@ export default function Sidebar() {
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/40">
|
||||
<span className="hidden text-[10px] text-muted-foreground/40 sm:inline">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
"use client";
|
||||
|
||||
import { mergeProps } from "@base-ui/react/merge-props";
|
||||
import { useRender } from "@base-ui/react/use-render";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { PanelLeftIcon } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import {
|
||||
Sheet,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetPopup,
|
||||
SheetTitle,
|
||||
} from "~/components/ui/sheet";
|
||||
import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import { useMediaQuery } from "~/hooks/useMediaQuery";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed";
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
openMobile: boolean;
|
||||
setOpenMobile: (open: boolean) => void;
|
||||
isMobile: boolean;
|
||||
toggleSidebar: () => void;
|
||||
};
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const isMobile = useMediaQuery("(max-width: 767px)");
|
||||
const [openMobile, setOpenMobile] = React.useState(false);
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||
const open = openProp ?? _open;
|
||||
const setOpen = React.useCallback(
|
||||
async (value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value;
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState);
|
||||
} else {
|
||||
_setOpen(openState);
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
await cookieStore.set({
|
||||
expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
|
||||
name: SIDEBAR_COOKIE_NAME,
|
||||
path: "/",
|
||||
value: String(openState),
|
||||
});
|
||||
},
|
||||
[setOpenProp, open],
|
||||
);
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||
}, [isMobile, setOpen]);
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
toggleSidebar();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [toggleSidebar]);
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
isMobile,
|
||||
open,
|
||||
openMobile,
|
||||
setOpen,
|
||||
setOpenMobile,
|
||||
state,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, toggleSidebar],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right";
|
||||
variant?: "sidebar" | "floating" | "inset";
|
||||
collapsible?: "offcanvas" | "icon" | "none";
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
|
||||
<SheetPopup
|
||||
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
data-mobile="true"
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
side={side}
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
data-state={state}
|
||||
data-variant={variant}
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
|
||||
)}
|
||||
data-slot="sidebar-gap"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-container"
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("size-7", className)}
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
}}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Toggle Sidebar"
|
||||
className={cn(
|
||||
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
onClick={toggleSidebar}
|
||||
tabIndex={-1}
|
||||
title="Toggle Sidebar"
|
||||
type="button"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background",
|
||||
"md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm/5",
|
||||
className,
|
||||
)}
|
||||
data-slot="sidebar-inset"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
className={cn("h-8 w-full bg-background shadow-none", className)}
|
||||
data-sidebar="input"
|
||||
data-slot="sidebar-input"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
data-sidebar="header"
|
||||
data-slot="sidebar-header"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
data-sidebar="footer"
|
||||
data-slot="sidebar-footer"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
data-sidebar="separator"
|
||||
data-slot="sidebar-separator"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<ScrollArea className="**:data-[slot=scroll-area-scrollbar]:hidden" scrollFade>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="content"
|
||||
data-slot="sidebar-content"
|
||||
{...props}
|
||||
/>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
data-sidebar="group"
|
||||
data-slot="sidebar-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"flex h-8 shrink-0 items-center rounded-lg px-2 font-medium text-sidebar-foreground text-xs outline-hidden ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "group-label",
|
||||
"data-slot": "sidebar-group-label",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "group-action",
|
||||
"data-slot": "sidebar-group-action",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn("w-full text-sm", className)}
|
||||
data-sidebar="group-content"
|
||||
data-slot="sidebar-group-content"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
data-sidebar="menu"
|
||||
data-slot="sidebar-menu"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
className={cn("group/menu-item relative", className)}
|
||||
data-sidebar="menu-item"
|
||||
data-slot="sidebar-menu-item"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
variant: "default",
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
sm: "h-7 text-xs",
|
||||
},
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function SidebarMenuButton({
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & {
|
||||
isActive?: boolean;
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const { isMobile, state } = useSidebar();
|
||||
|
||||
const defaultProps = {
|
||||
className: cn(sidebarMenuButtonVariants({ size, variant }), className),
|
||||
"data-active": isActive,
|
||||
"data-sidebar": "menu-button",
|
||||
"data-size": size,
|
||||
"data-slot": "sidebar-menu-button",
|
||||
};
|
||||
|
||||
const buttonProps = mergeProps<"button">(defaultProps, props);
|
||||
|
||||
const buttonElement = useRender({
|
||||
defaultTagName: "button",
|
||||
props: buttonProps,
|
||||
render,
|
||||
});
|
||||
|
||||
if (!tooltip) {
|
||||
return buttonElement;
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
|
||||
<TooltipPopup
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
side="right"
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
showOnHover = false,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & {
|
||||
showOnHover?: boolean;
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||
className,
|
||||
),
|
||||
"data-sidebar": "menu-action",
|
||||
"data-slot": "sidebar-menu-action",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-lg px-1 font-medium text-sidebar-foreground text-xs tabular-nums",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="menu-badge"
|
||||
data-slot="sidebar-menu-badge"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
|
||||
data-sidebar="menu-skeleton"
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
{...props}
|
||||
>
|
||||
{showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="menu-sub"
|
||||
data-slot="sidebar-menu-sub"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
data-sidebar="menu-sub-item"
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"a"> & {
|
||||
size?: "sm" | "md";
|
||||
isActive?: boolean;
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className,
|
||||
),
|
||||
"data-active": isActive,
|
||||
"data-sidebar": "menu-sub-button",
|
||||
"data-size": size,
|
||||
"data-slot": "sidebar-menu-sub-button",
|
||||
};
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "a",
|
||||
props: mergeProps<"a">(defaultProps, props),
|
||||
render,
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const TooltipCreateHandle = TooltipPrimitive.createHandle;
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider;
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root;
|
||||
|
||||
function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipPopup({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
side = "top",
|
||||
anchor,
|
||||
children,
|
||||
...props
|
||||
}: TooltipPrimitive.Popup.Props & {
|
||||
align?: TooltipPrimitive.Positioner.Props["align"];
|
||||
side?: TooltipPrimitive.Positioner.Props["side"];
|
||||
sideOffset?: TooltipPrimitive.Positioner.Props["sideOffset"];
|
||||
anchor?: TooltipPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Positioner
|
||||
align={align}
|
||||
anchor={anchor}
|
||||
className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
|
||||
data-slot="tooltip-positioner"
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
>
|
||||
<TooltipPrimitive.Popup
|
||||
className={cn(
|
||||
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) text-balance rounded-md border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs shadow-md/5 transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 data-instant:duration-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
className,
|
||||
)}
|
||||
data-slot="tooltip-popup"
|
||||
{...props}
|
||||
>
|
||||
<TooltipPrimitive.Viewport
|
||||
className="relative size-full overflow-clip px-(--viewport-inline-padding) py-1 [--viewport-inline-padding:--spacing(2)] data-instant:transition-none **:data-current:data-ending-style:opacity-0 **:data-current:data-starting-style:opacity-0 **:data-previous:data-ending-style:opacity-0 **:data-previous:data-starting-style:opacity-0 **:data-current:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:truncate **:data-current:opacity-100 **:data-previous:opacity-100 **:data-current:transition-opacity **:data-previous:transition-opacity"
|
||||
data-slot="tooltip-viewport"
|
||||
>
|
||||
{children}
|
||||
</TooltipPrimitive.Viewport>
|
||||
</TooltipPrimitive.Popup>
|
||||
</TooltipPrimitive.Positioner>
|
||||
</TooltipPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
TooltipCreateHandle,
|
||||
TooltipProvider,
|
||||
Tooltip,
|
||||
TooltipTrigger,
|
||||
TooltipPopup,
|
||||
TooltipPopup as TooltipContent,
|
||||
};
|
||||
@@ -13,6 +13,18 @@ import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
if (!globalThis.crypto.randomUUID) {
|
||||
// https://stackoverflow.com/a/2117523/2800218
|
||||
// LICENSE: https://creativecommons.org/licenses/by-sa/4.0/legalcode
|
||||
// oxlint-disable-next-line unicorn/consistent-function-scoping
|
||||
crypto.randomUUID = function randomUUID() {
|
||||
// @ts-expect-error -- Some cryptic stuff that this polyfill uses
|
||||
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
|
||||
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (c / 4)))).toString(16),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ProviderEvent } from "@t3tools/contracts";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { Button } from "../components/ui/button";
|
||||
@@ -28,7 +29,7 @@ function RootRouteView() {
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex h-dvh flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connecting to {APP_DISPLAY_NAME} server...
|
||||
@@ -120,6 +121,14 @@ function errorDetails(error: unknown): string {
|
||||
}
|
||||
}
|
||||
|
||||
function readProviderSeq(event: ProviderEvent): number | null {
|
||||
const seq = event.seq;
|
||||
if (typeof seq !== "number" || !Number.isInteger(seq) || seq <= 0) {
|
||||
return null;
|
||||
}
|
||||
return seq;
|
||||
}
|
||||
|
||||
function StateSyncRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
@@ -131,6 +140,8 @@ function StateSyncRouter() {
|
||||
});
|
||||
const lastStateSeqRef = useRef(0);
|
||||
const stateQueueRef = useRef(Promise.resolve());
|
||||
const lastProviderSeqRef = useRef(0);
|
||||
const providerQueueRef = useRef(Promise.resolve());
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
@@ -202,7 +213,7 @@ function StateSyncRouter() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.providers.onEvent((event) => {
|
||||
const applyProviderEvent = (event: ProviderEvent) => {
|
||||
if (event.method === "turn/completed") {
|
||||
void invalidateGitQueries(queryClient);
|
||||
}
|
||||
@@ -217,14 +228,73 @@ function StateSyncRouter() {
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
activeThreadId,
|
||||
});
|
||||
};
|
||||
|
||||
const replayProviderCatchUp = async (): Promise<void> => {
|
||||
const catchUp = await api.providers.catchUp({
|
||||
afterSeq: lastProviderSeqRef.current,
|
||||
});
|
||||
if (catchUp.events.length === 0) {
|
||||
lastProviderSeqRef.current = Math.max(lastProviderSeqRef.current, catchUp.lastProviderSeq);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const missingEvent of catchUp.events) {
|
||||
const missingSeq = readProviderSeq(missingEvent);
|
||||
if (!missingSeq || missingSeq <= lastProviderSeqRef.current) continue;
|
||||
applyProviderEvent(missingEvent);
|
||||
lastProviderSeqRef.current = missingSeq;
|
||||
}
|
||||
|
||||
if (lastProviderSeqRef.current < catchUp.lastProviderSeq) {
|
||||
await replayProviderCatchUp();
|
||||
}
|
||||
};
|
||||
|
||||
const enqueueProviderWork = (work: () => Promise<void>) => {
|
||||
providerQueueRef.current = providerQueueRef.current.then(work).catch(() => undefined);
|
||||
};
|
||||
|
||||
const unsubscribeWelcome = onServerWelcome(() => {
|
||||
if (lastProviderSeqRef.current <= 0) {
|
||||
return;
|
||||
}
|
||||
enqueueProviderWork(async () => {
|
||||
await replayProviderCatchUp();
|
||||
});
|
||||
});
|
||||
|
||||
const unsubscribeProvider = api.providers.onEvent((event) => {
|
||||
enqueueProviderWork(async () => {
|
||||
const eventSeq = readProviderSeq(event);
|
||||
if (!eventSeq) {
|
||||
applyProviderEvent(event);
|
||||
return;
|
||||
}
|
||||
if (eventSeq <= lastProviderSeqRef.current) {
|
||||
return;
|
||||
}
|
||||
if (lastProviderSeqRef.current > 0 && eventSeq > lastProviderSeqRef.current + 1) {
|
||||
await replayProviderCatchUp();
|
||||
}
|
||||
if (eventSeq <= lastProviderSeqRef.current) {
|
||||
return;
|
||||
}
|
||||
applyProviderEvent(event);
|
||||
lastProviderSeqRef.current = eventSeq;
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeWelcome();
|
||||
unsubscribeProvider();
|
||||
};
|
||||
}, [activeThreadId, api, dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
import { Suspense, lazy, type CSSProperties, type ReactNode, useCallback, useEffect } from "react";
|
||||
|
||||
import ChatView from "../components/ChatView";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
import { Sheet, SheetPopup } from "../components/ui/sheet";
|
||||
import { Sidebar, SidebarProvider } from "../components/ui/sidebar";
|
||||
|
||||
const DiffPanel = lazy(() => import("../components/DiffPanel"));
|
||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
||||
@@ -53,6 +54,20 @@ function ChatThreadRouteView() {
|
||||
const threadExists = threadId ? state.threads.some((thread) => thread.id === threadId) : false;
|
||||
const diffOpen = search.diff === "1";
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
const setDiffOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (open === diffOpen) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return open ? { ...rest, diff: "1" } : rest;
|
||||
},
|
||||
});
|
||||
},
|
||||
[diffOpen, navigate, threadId],
|
||||
);
|
||||
const closeDiff = useCallback(() => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
@@ -83,26 +98,45 @@ function ChatThreadRouteView() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const diffLoadingFallback =
|
||||
!diffOpen || shouldUseDiffSheet ? (
|
||||
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</div>
|
||||
) : (
|
||||
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</aside>
|
||||
const diffLoadingFallback = (
|
||||
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</div>
|
||||
);
|
||||
|
||||
if (shouldUseDiffSheet) {
|
||||
return (
|
||||
<>
|
||||
<ChatView threadId={threadId} />
|
||||
<DiffPanelWrapper sheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode="sheet" />
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
<ChatView threadId={threadId} />
|
||||
<DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</>
|
||||
<SidebarProvider
|
||||
open={diffOpen}
|
||||
onOpenChange={setDiffOpen}
|
||||
className="w-0 min-w-0 flex-none"
|
||||
style={{ "--sidebar-width": "34rem" } as CSSProperties}
|
||||
>
|
||||
<Sidebar
|
||||
side="right"
|
||||
collapsible="offcanvas"
|
||||
className="border-l border-border bg-card text-foreground"
|
||||
>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffPanel mode="sheet" />
|
||||
</Suspense>
|
||||
</Sidebar>
|
||||
</SidebarProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { Separator } from "../components/ui/separator";
|
||||
import { SidebarTrigger } from "../components/ui/sidebar";
|
||||
|
||||
function ChatIndexRouteView() {
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
{!isElectron && (
|
||||
<header className="sticky top-0 z-20 flex h-11 shrink-0 items-center gap-2 border-b border-border/70 bg-background/95 px-2 backdrop-blur md:hidden">
|
||||
<SidebarTrigger className="size-8" />
|
||||
<Separator orientation="vertical" className="data-[orientation=vertical]:h-4" />
|
||||
<span className="truncate text-xs text-muted-foreground/75">Threads</span>
|
||||
</header>
|
||||
)}
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import Sidebar from "../components/Sidebar";
|
||||
import ThreadSidebar from "../components/Sidebar";
|
||||
import { Sidebar, SidebarInset, SidebarProvider } from "../components/ui/sidebar";
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
@@ -24,16 +25,23 @@ function ChatRouteLayout() {
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
||||
<Sidebar />
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
</div>
|
||||
<SidebarProvider defaultOpen>
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
>
|
||||
<ThreadSidebar embedded />
|
||||
</Sidebar>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden bg-background text-foreground isolate">
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat")({
|
||||
component: ChatRouteLayout,
|
||||
});
|
||||
|
||||
+30
-32
@@ -1,4 +1,4 @@
|
||||
import type { ProviderEvent, ProviderSession, StateEvent, TerminalEvent } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
@@ -566,7 +566,7 @@ describe("store reducer thread continuity", () => {
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: ({
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
@@ -598,7 +598,7 @@ describe("store reducer thread continuity", () => {
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
} as unknown as StateEvent),
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
|
||||
@@ -626,35 +626,33 @@ describe("store reducer thread continuity", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const malformedStateEvent = ({
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
createdAt: "2026-02-09T00:00:06.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: "thr-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
activeTerminalId: "term-2",
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:06.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:06.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
} as unknown) as StateEvent;
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: malformedStateEvent,
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
createdAt: "2026-02-09T00:00:06.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: "thr-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
activeTerminalId: "term-2",
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:06.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:06.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
@@ -676,7 +674,7 @@ describe("store reducer thread continuity", () => {
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: ({
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-2",
|
||||
@@ -698,7 +696,7 @@ describe("store reducer thread continuity", () => {
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
} as unknown as StateEvent),
|
||||
},
|
||||
});
|
||||
|
||||
const createdThread = next.threads.find((thread) => thread.id === "thread-local-2");
|
||||
|
||||
+200
-149
@@ -575,158 +575,209 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}
|
||||
|
||||
case "APPLY_STATE_EVENT": {
|
||||
switch (action.event.eventType) {
|
||||
case "project.upsert": {
|
||||
const project = action.event.payload.project;
|
||||
const previous = state.projects.find((entry) => entry.id === project.id);
|
||||
const nextProject: Project = {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
|
||||
expanded: previous?.expanded ?? true,
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
};
|
||||
const nextProjects = previous
|
||||
? state.projects.map((entry) => (entry.id === project.id ? nextProject : entry))
|
||||
: [...state.projects, nextProject];
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
};
|
||||
}
|
||||
case "project.delete": {
|
||||
const projectId = action.event.payload.projectId;
|
||||
const projects = state.projects.filter((project) => project.id !== projectId);
|
||||
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
case "thread.upsert": {
|
||||
const threadPayload = action.event.payload.thread as Partial<StateBootstrapThread> &
|
||||
Pick<
|
||||
StateBootstrapThread,
|
||||
"id" | "projectId" | "title" | "model" | "createdAt" | "updatedAt"
|
||||
>;
|
||||
const threadId = threadPayload.id;
|
||||
const projectId = threadPayload.projectId;
|
||||
if (!state.projects.some((project) => project.id === projectId)) {
|
||||
return state;
|
||||
}
|
||||
const payload = asObject(action.event.payload);
|
||||
const eventType = action.event.eventType;
|
||||
|
||||
const existing = state.threads.find((thread) => thread.id === threadId);
|
||||
const existingStateMessages =
|
||||
existing?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
threadId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({ ...attachment })),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})) ?? [];
|
||||
const payloadTurnDiffSummaries = Array.isArray(threadPayload.turnDiffSummaries)
|
||||
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
|
||||
: undefined;
|
||||
const payloadTerminalIds = Array.isArray(threadPayload.terminalIds)
|
||||
? (threadPayload.terminalIds as string[])
|
||||
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
|
||||
const payloadRunningTerminalIds = Array.isArray(threadPayload.runningTerminalIds)
|
||||
? (threadPayload.runningTerminalIds as string[])
|
||||
: (existing?.runningTerminalIds ?? []);
|
||||
const payloadTerminalGroups = Array.isArray(threadPayload.terminalGroups)
|
||||
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
|
||||
: (existing?.terminalGroups ?? []);
|
||||
const bootstrapThread: StateBootstrapThread = {
|
||||
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
|
||||
terminalIds: payloadTerminalIds,
|
||||
runningTerminalIds: payloadRunningTerminalIds,
|
||||
terminalGroups: payloadTerminalGroups,
|
||||
messages: existingStateMessages,
|
||||
turnDiffSummaries: payloadTurnDiffSummaries
|
||||
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
|
||||
: existing?.turnDiffSummaries ?? [],
|
||||
};
|
||||
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
|
||||
const nextThreads = existing
|
||||
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
|
||||
: [...state.threads, nextThread];
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
};
|
||||
}
|
||||
case "thread.delete": {
|
||||
const threadId = action.event.payload.threadId;
|
||||
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
case "message.upsert": {
|
||||
const { threadId, message: messagePayload } = action.event.payload;
|
||||
const attachments = messagePayload.attachments as
|
||||
| Thread["messages"][number]["attachments"]
|
||||
| undefined;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: upsertThreadMessage(thread.messages, {
|
||||
id: messagePayload.id,
|
||||
role: messagePayload.role,
|
||||
text: messagePayload.text,
|
||||
...(attachments ? { attachments } : {}),
|
||||
createdAt: messagePayload.createdAt,
|
||||
streaming: messagePayload.streaming,
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
case "message.delete": {
|
||||
const { threadId, messageId } = action.event.payload;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: thread.messages.filter((message) => message.id !== messageId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
case "turn_summary.upsert": {
|
||||
const { threadId, turnSummary } = action.event.payload;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [turnSummary]),
|
||||
})),
|
||||
};
|
||||
}
|
||||
case "turn_summary.delete": {
|
||||
const { threadId, turnId } = action.event.payload;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
|
||||
})),
|
||||
};
|
||||
if (eventType === "project.upsert") {
|
||||
const project = asObject(payload?.project);
|
||||
const id = asString(project?.id);
|
||||
const name = asString(project?.name);
|
||||
const cwd = asString(project?.cwd);
|
||||
const scripts = Array.isArray(project?.scripts) ? (project.scripts as ProjectScript[]) : [];
|
||||
if (!id || !name || !cwd) {
|
||||
return state;
|
||||
}
|
||||
const previous = state.projects.find((entry) => entry.id === id);
|
||||
const nextProject: Project = {
|
||||
id,
|
||||
name,
|
||||
cwd,
|
||||
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
|
||||
expanded: previous?.expanded ?? true,
|
||||
scripts: normalizeProjectScripts(scripts),
|
||||
};
|
||||
const nextProjects = previous
|
||||
? state.projects.map((entry) => (entry.id === id ? nextProject : entry))
|
||||
: [...state.projects, nextProject];
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "project.delete") {
|
||||
const projectId = asString(payload?.projectId) ?? action.event.entityId;
|
||||
const projects = state.projects.filter((project) => project.id !== projectId);
|
||||
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "thread.upsert") {
|
||||
const threadPayload = asObject(payload?.thread);
|
||||
const threadId = asString(threadPayload?.id);
|
||||
const projectId = asString(threadPayload?.projectId);
|
||||
if (!threadId || !projectId) {
|
||||
return state;
|
||||
}
|
||||
if (!state.projects.some((project) => project.id === projectId)) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const existing = state.threads.find((thread) => thread.id === threadId);
|
||||
const existingStateMessages =
|
||||
existing?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
threadId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({ ...attachment })),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})) ?? [];
|
||||
const payloadTurnDiffSummaries = Array.isArray(threadPayload?.turnDiffSummaries)
|
||||
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
|
||||
: undefined;
|
||||
const payloadTerminalIds = Array.isArray(threadPayload?.terminalIds)
|
||||
? (threadPayload.terminalIds as string[])
|
||||
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
|
||||
const payloadRunningTerminalIds = Array.isArray(threadPayload?.runningTerminalIds)
|
||||
? (threadPayload.runningTerminalIds as string[])
|
||||
: (existing?.runningTerminalIds ?? []);
|
||||
const payloadTerminalGroups = Array.isArray(threadPayload?.terminalGroups)
|
||||
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
|
||||
: (existing?.terminalGroups ?? []);
|
||||
const bootstrapThread: StateBootstrapThread = {
|
||||
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
|
||||
terminalIds: payloadTerminalIds,
|
||||
runningTerminalIds: payloadRunningTerminalIds,
|
||||
terminalGroups: payloadTerminalGroups,
|
||||
messages: existingStateMessages,
|
||||
turnDiffSummaries: payloadTurnDiffSummaries
|
||||
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
|
||||
: existing?.turnDiffSummaries ?? [],
|
||||
};
|
||||
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
|
||||
const nextThreads = existing
|
||||
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
|
||||
: [...state.threads, nextThread];
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "thread.delete") {
|
||||
const threadId = asString(payload?.threadId) ?? action.event.entityId;
|
||||
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
return {
|
||||
...state,
|
||||
threads: nextThreads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "message.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messagePayload = asObject(payload?.message);
|
||||
const messageId = asString(messagePayload?.id);
|
||||
const role = messagePayload?.role === "assistant" ? "assistant" : "user";
|
||||
const text = typeof messagePayload?.text === "string" ? messagePayload.text : "";
|
||||
const createdAt = asString(messagePayload?.createdAt);
|
||||
if (!threadId || !messageId || !createdAt) {
|
||||
return state;
|
||||
}
|
||||
const attachments = Array.isArray(messagePayload?.attachments)
|
||||
? (messagePayload.attachments as Thread["messages"][number]["attachments"])
|
||||
: undefined;
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: upsertThreadMessage(thread.messages, {
|
||||
id: messageId,
|
||||
role,
|
||||
text,
|
||||
...(attachments ? { attachments } : {}),
|
||||
createdAt,
|
||||
streaming: messagePayload?.streaming === true,
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "message.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messageId = asString(payload?.messageId);
|
||||
if (!threadId || !messageId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
messages: thread.messages.filter((message) => message.id !== messageId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "turn_summary.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const summaryPayload = asObject(payload?.turnSummary);
|
||||
const turnId = asString(summaryPayload?.turnId);
|
||||
const completedAt = asString(summaryPayload?.completedAt);
|
||||
if (!threadId || !turnId || !completedAt) {
|
||||
return state;
|
||||
}
|
||||
const summary: Thread["turnDiffSummaries"][number] = {
|
||||
turnId,
|
||||
completedAt,
|
||||
status: asString(summaryPayload?.status),
|
||||
files: Array.isArray(summaryPayload?.files)
|
||||
? (summaryPayload.files as Thread["turnDiffSummaries"][number]["files"])
|
||||
: [],
|
||||
assistantMessageId: asString(summaryPayload?.assistantMessageId),
|
||||
checkpointTurnCount:
|
||||
typeof summaryPayload?.checkpointTurnCount === "number"
|
||||
? summaryPayload.checkpointTurnCount
|
||||
: undefined,
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [summary]),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType === "turn_summary.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const turnId = asString(payload?.turnId);
|
||||
if (!threadId || !turnId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, threadId, (thread) => ({
|
||||
...thread,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
case "ADD_PROJECT":
|
||||
|
||||
@@ -93,6 +93,7 @@ export function createWsNativeApi(): NativeApi {
|
||||
listSessions: () => transport.request(WS_METHODS.providersListSessions),
|
||||
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
|
||||
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
|
||||
catchUp: (input) => transport.request(WS_METHODS.providersCatchUp, input),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: (callback) =>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTokenFromPageUrl, resolveWsUrl } from "./wsTransport";
|
||||
|
||||
describe("resolveWsUrl", () => {
|
||||
it("prefers explicit url when provided", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
explicitUrl: "ws://explicit.example:3773/socket",
|
||||
bridgeUrl: "ws://bridge.example:3773",
|
||||
envUrl: "ws://env.example:3773",
|
||||
pageUrl: "http://device.local:3773/?token=abc",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://explicit.example:3773/socket");
|
||||
});
|
||||
|
||||
it("prefers desktop bridge url over env url", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
bridgeUrl: "ws://bridge.example:3773",
|
||||
envUrl: "ws://env.example:3773",
|
||||
pageUrl: "http://device.local:3773/",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://bridge.example:3773");
|
||||
});
|
||||
|
||||
it("falls back to env url when bridge url is missing", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://env.example:3773/path",
|
||||
pageUrl: "http://device.local:3773/",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "device.local",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://env.example:3773/path");
|
||||
});
|
||||
|
||||
it("derives wss url from https page when no explicit, bridge, or env url exists", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
pageUrl: "https://tailnet-host.ts.net/",
|
||||
pageProtocol: "https:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("wss://tailnet-host.ts.net");
|
||||
});
|
||||
|
||||
it("adds token from page url when missing on websocket url", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://tailnet-host.ts.net:3773",
|
||||
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=super-secret");
|
||||
});
|
||||
|
||||
it("does not overwrite existing websocket token", () => {
|
||||
const resolved = resolveWsUrl({
|
||||
envUrl: "ws://tailnet-host.ts.net:3773/?token=already-set",
|
||||
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
|
||||
pageProtocol: "http:",
|
||||
pageHostname: "tailnet-host.ts.net",
|
||||
pagePort: "3773",
|
||||
});
|
||||
|
||||
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=already-set");
|
||||
});
|
||||
});
|
||||
|
||||
describe("appendTokenFromPageUrl", () => {
|
||||
it("returns original url for invalid page urls", () => {
|
||||
expect(appendTokenFromPageUrl("ws://localhost:3773", "not-a-url")).toBe("ws://localhost:3773");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,56 @@ interface PendingRequest {
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
||||
|
||||
interface WsUrlResolutionInput {
|
||||
explicitUrl?: string;
|
||||
bridgeUrl?: string | null;
|
||||
envUrl?: string;
|
||||
pageUrl: string;
|
||||
pageProtocol: string;
|
||||
pageHostname: string;
|
||||
pagePort: string;
|
||||
}
|
||||
|
||||
function normalizeUrl(value: string | null | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function defaultWsUrlForPage(protocol: string, hostname: string, port: string): string {
|
||||
const wsProtocol = protocol === "https:" ? "wss" : "ws";
|
||||
const authority = port.length > 0 ? `${hostname}:${port}` : hostname;
|
||||
return `${wsProtocol}://${authority}`;
|
||||
}
|
||||
|
||||
export function appendTokenFromPageUrl(wsUrl: string, pageUrl: string): string {
|
||||
try {
|
||||
const page = new URL(pageUrl);
|
||||
const token = page.searchParams.get("token")?.trim();
|
||||
if (!token) return wsUrl;
|
||||
|
||||
const resolvedWsUrl = new URL(wsUrl, page.origin);
|
||||
if (!resolvedWsUrl.searchParams.has("token")) {
|
||||
resolvedWsUrl.searchParams.set("token", token);
|
||||
}
|
||||
return resolvedWsUrl.toString();
|
||||
} catch {
|
||||
return wsUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWsUrl(input: WsUrlResolutionInput): string {
|
||||
const explicitUrl = normalizeUrl(input.explicitUrl);
|
||||
if (explicitUrl) return explicitUrl;
|
||||
|
||||
const baseUrl =
|
||||
normalizeUrl(input.bridgeUrl) ??
|
||||
normalizeUrl(input.envUrl) ??
|
||||
defaultWsUrlForPage(input.pageProtocol, input.pageHostname, input.pagePort);
|
||||
|
||||
return appendTokenFromPageUrl(baseUrl, input.pageUrl);
|
||||
}
|
||||
|
||||
export class WsTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private nextId = 1;
|
||||
@@ -26,13 +76,15 @@ export class WsTransport {
|
||||
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
|
||||
// In production, the page is served by the WS server on the same host:port.
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
this.url =
|
||||
url ??
|
||||
(bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`);
|
||||
this.url = resolveWsUrl({
|
||||
explicitUrl: url,
|
||||
bridgeUrl,
|
||||
envUrl,
|
||||
pageUrl: window.location.href,
|
||||
pageProtocol: window.location.protocol,
|
||||
pageHostname: window.location.hostname,
|
||||
pagePort: window.location.port,
|
||||
});
|
||||
this.connect();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5173);
|
||||
const devServerHost = process.env.VITE_DEV_SERVER_HOST ?? "localhost";
|
||||
const hmrHost = process.env.VITE_HMR_HOST ?? "localhost";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
@@ -29,6 +31,7 @@ export default defineConfig({
|
||||
tsconfigPaths: true,
|
||||
},
|
||||
server: {
|
||||
host: devServerHost,
|
||||
port,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
@@ -36,7 +39,7 @@ export default defineConfig({
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host: "localhost",
|
||||
host: hmrHost,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
|
||||
@@ -34,11 +34,8 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/sql-sqlite-bun": "^4.0.0-beta.6",
|
||||
"@effect/sql-sqlite-node": "^4.0.0-beta.6",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "^4.0.0-beta.6",
|
||||
"node-pty": "1.1.0",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
@@ -148,10 +145,6 @@
|
||||
|
||||
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
|
||||
|
||||
"@effect/sql-sqlite-bun": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.6" } }, "sha512-OYojvXs3X8TRMG8tQwxAbnR2LlOb/iM3bNUudU5bWBi2LJoLqQVmxLxDue5SIZbIMuxMfcBES9bPuKbPDd7Hgg=="],
|
||||
|
||||
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "effect": "^4.0.0-beta.6" } }, "sha512-lmV5h1U1VrfNWOlDEQBYidnXlMIWbLapKzwcNPcWuyGZZanHeg939Sve6v6I3AE8r874iIwCdj3e6boxkym89g=="],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -252,18 +245,6 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
|
||||
|
||||
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
|
||||
@@ -602,28 +583,18 @@
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
|
||||
|
||||
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
|
||||
|
||||
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
|
||||
|
||||
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
|
||||
|
||||
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
|
||||
|
||||
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
|
||||
|
||||
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
|
||||
|
||||
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
@@ -654,8 +625,6 @@
|
||||
|
||||
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
|
||||
|
||||
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
|
||||
|
||||
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
|
||||
|
||||
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
|
||||
@@ -688,8 +657,6 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
@@ -720,8 +687,6 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-2xpzTi1f8eRYByMYso/vBiZGCvK74dVOMHOnXbwgzZQg6t5JaZ6ov7i5AU/vKPtb2y9FJbZwhf8owXBZq+LY0g=="],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
@@ -762,32 +727,22 @@
|
||||
|
||||
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
|
||||
|
||||
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
|
||||
|
||||
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
|
||||
|
||||
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
|
||||
|
||||
"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^7.0.0" } }, "sha512-IE9csY7lnhxBnA8g/WI5eg/hygA6MGWJMSNfFRrBlXUciADEhS1EDB0SIsMSvzubzIlOBbVITSsypCsW717poA=="],
|
||||
|
||||
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
|
||||
|
||||
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
|
||||
|
||||
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
|
||||
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
|
||||
|
||||
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
|
||||
|
||||
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
|
||||
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
|
||||
|
||||
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
@@ -806,8 +761,6 @@
|
||||
|
||||
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
|
||||
|
||||
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
|
||||
|
||||
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
|
||||
@@ -856,16 +809,10 @@
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
|
||||
|
||||
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
|
||||
|
||||
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
|
||||
|
||||
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
|
||||
@@ -916,8 +863,6 @@
|
||||
|
||||
"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
|
||||
|
||||
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
|
||||
|
||||
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.31.1", "lightningcss-darwin-arm64": "1.31.1", "lightningcss-darwin-x64": "1.31.1", "lightningcss-freebsd-x64": "1.31.1", "lightningcss-linux-arm-gnueabihf": "1.31.1", "lightningcss-linux-arm64-gnu": "1.31.1", "lightningcss-linux-arm64-musl": "1.31.1", "lightningcss-linux-x64-gnu": "1.31.1", "lightningcss-linux-x64-musl": "1.31.1", "lightningcss-win32-arm64-msvc": "1.31.1", "lightningcss-win32-x64-msvc": "1.31.1" } }, "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ=="],
|
||||
|
||||
"lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg=="],
|
||||
@@ -1062,30 +1007,16 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
|
||||
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
|
||||
|
||||
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
|
||||
|
||||
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
|
||||
|
||||
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
|
||||
|
||||
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
|
||||
|
||||
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
|
||||
|
||||
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
|
||||
|
||||
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
|
||||
|
||||
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
@@ -1130,8 +1061,6 @@
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
@@ -1142,14 +1071,10 @@
|
||||
|
||||
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
|
||||
|
||||
"pure-rand": ["[email protected]", "", {}, "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ=="],
|
||||
|
||||
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
|
||||
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
|
||||
|
||||
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
|
||||
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
@@ -1158,8 +1083,6 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
|
||||
|
||||
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
|
||||
@@ -1210,8 +1133,6 @@
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
@@ -1230,10 +1151,6 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
|
||||
|
||||
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1252,14 +1169,10 @@
|
||||
|
||||
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
|
||||
|
||||
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
|
||||
|
||||
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
|
||||
|
||||
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
|
||||
|
||||
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
|
||||
@@ -1280,10 +1193,6 @@
|
||||
|
||||
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
|
||||
|
||||
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
|
||||
|
||||
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
|
||||
|
||||
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
|
||||
@@ -1304,8 +1213,6 @@
|
||||
|
||||
"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
|
||||
|
||||
"toml": ["[email protected]", "", {}, "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w=="],
|
||||
|
||||
"tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
|
||||
|
||||
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
|
||||
@@ -1320,8 +1227,6 @@
|
||||
|
||||
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
|
||||
|
||||
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
|
||||
@@ -1372,10 +1277,6 @@
|
||||
|
||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
|
||||
|
||||
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
|
||||
|
||||
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
|
||||
@@ -1404,8 +1305,6 @@
|
||||
|
||||
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||
|
||||
"yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="],
|
||||
|
||||
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
|
||||
|
||||
"yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
|
||||
@@ -1486,8 +1385,6 @@
|
||||
|
||||
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
|
||||
|
||||
"rc/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
|
||||
|
||||
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"recast/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Remote Access Guide (Server on Computer, Client on Phone)
|
||||
|
||||
This guide explains how to run T3 Code on one machine and control it from another device (for example, your phone) over a private network like Tailscale.
|
||||
|
||||
## Goal
|
||||
|
||||
- Run the `apps/server` process on your computer.
|
||||
- Open the web client from another device.
|
||||
- Keep Codex running on the computer while controlling it remotely.
|
||||
|
||||
## Architecture
|
||||
|
||||
T3 Code is already split into backend and frontend roles:
|
||||
|
||||
- Backend (`apps/server`):
|
||||
- Runs on your computer.
|
||||
- Hosts HTTP pages + static assets.
|
||||
- Hosts the WebSocket API.
|
||||
- Spawns and manages Codex app-server sessions.
|
||||
- Reads/writes local state and your local workspace files.
|
||||
- Frontend (`apps/web`):
|
||||
- Runs in the browser on any device.
|
||||
- Connects to backend over WebSocket.
|
||||
- Renders thread state and sends commands.
|
||||
|
||||
Data path:
|
||||
|
||||
1. Phone browser opens `http://<computer-tailnet-host>:<port>`.
|
||||
2. Browser loads the T3 web app from that server.
|
||||
3. Web app opens a WebSocket to the same server.
|
||||
4. Server executes provider/terminal/git/file actions on the computer.
|
||||
5. Server streams updates back to the phone.
|
||||
|
||||
Important: your phone never runs Codex itself. The agent process stays on the computer.
|
||||
|
||||
## Security Model
|
||||
|
||||
- Recommended network boundary: Tailscale tailnet ACLs.
|
||||
- Optional app-layer auth: set `T3CODE_AUTH_TOKEN` on server start.
|
||||
- When `T3CODE_AUTH_TOKEN` is enabled, open the UI with `?token=<token>` in the URL so the browser can authenticate WebSocket requests.
|
||||
|
||||
Example:
|
||||
|
||||
`http://my-macbook.tailnet-name.ts.net:3773/?token=<your-token>`
|
||||
|
||||
## Recommended Setup (Production Build)
|
||||
|
||||
Use this for reliable "control from phone while away from home".
|
||||
|
||||
### 1. Prepare computer
|
||||
|
||||
- Ensure Codex CLI is installed and authenticated on the computer.
|
||||
- Ensure Tailscale is connected on the computer.
|
||||
- Build the app:
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
```
|
||||
|
||||
### 2. Start server
|
||||
|
||||
- Choose a port (default is `3773`).
|
||||
- Create an auth token (recommended).
|
||||
|
||||
```bash
|
||||
export T3CODE_PORT=3773
|
||||
export T3CODE_NO_BROWSER=1
|
||||
export T3CODE_AUTH_TOKEN="$(openssl rand -hex 24)"
|
||||
bun run start
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `T3CODE_NO_BROWSER=1` avoids auto-opening a local browser tab.
|
||||
- Without `T3CODE_AUTH_TOKEN`, anyone with network reachability to your server can open a session.
|
||||
|
||||
### 3. Find Tailscale address of computer
|
||||
|
||||
```bash
|
||||
tailscale ip -4
|
||||
```
|
||||
|
||||
Or use MagicDNS hostname (for example `my-macbook.tailnet-name.ts.net`).
|
||||
|
||||
### 4. Open from phone
|
||||
|
||||
- Ensure your phone is connected to the same Tailscale tailnet.
|
||||
- In phone browser, open:
|
||||
|
||||
```text
|
||||
http://<tailscale-host-or-ip>:3773/?token=<T3CODE_AUTH_TOKEN>
|
||||
```
|
||||
|
||||
You should now control the agent running on your computer.
|
||||
|
||||
## Remote Dev Setup (Hot Reload)
|
||||
|
||||
This repo now supports remote dev host wiring directly.
|
||||
|
||||
### 1. Pick the public host
|
||||
|
||||
Use the computer's Tailscale hostname or IP as `T3CODE_PUBLIC_HOST`.
|
||||
|
||||
### 2. Run dev mode
|
||||
|
||||
```bash
|
||||
T3CODE_PUBLIC_HOST=my-macbook.tailnet-name.ts.net bun run dev
|
||||
```
|
||||
|
||||
What this config does:
|
||||
|
||||
- Vite dev server is reachable off-machine (`0.0.0.0` bind).
|
||||
- Server redirects to the public dev URL instead of localhost.
|
||||
- WebSocket target uses the same public host instead of localhost.
|
||||
- HMR uses the public host for browser reconnects.
|
||||
|
||||
If you also use auth token in dev:
|
||||
|
||||
1. set `T3CODE_AUTH_TOKEN=...` before running `bun run dev`
|
||||
2. open `http://<host>:<web-port>/?token=<token>`
|
||||
|
||||
## Operational Tips
|
||||
|
||||
- Keep the server process running in `tmux`, `screen`, or a service manager.
|
||||
- Use a long, random auth token.
|
||||
- Restrict tailnet access using Tailscale ACLs to only your user/devices.
|
||||
- Prefer production build for lower moving parts when remote.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Page loads but no data:
|
||||
- Most likely missing/incorrect `?token=` when `T3CODE_AUTH_TOKEN` is set.
|
||||
- Phone cannot reach host:
|
||||
- Verify both devices are connected to Tailscale and can ping each other.
|
||||
- Dev mode opens localhost URL:
|
||||
- Ensure `T3CODE_PUBLIC_HOST` is set before `bun run dev`.
|
||||
- Live reload not working in remote dev:
|
||||
- Ensure `T3CODE_PUBLIC_HOST` resolves on the phone and no conflicting port overrides are set.
|
||||
@@ -17,6 +17,8 @@ import type {
|
||||
GitStatusResult,
|
||||
} from "./git";
|
||||
import type {
|
||||
ProviderCatchUpInput,
|
||||
ProviderCatchUpResult,
|
||||
ProviderEvent,
|
||||
ProviderGetCheckpointDiffInput,
|
||||
ProviderGetCheckpointDiffResult,
|
||||
@@ -118,6 +120,7 @@ export interface NativeApi {
|
||||
getCheckpointDiff: (
|
||||
input: ProviderGetCheckpointDiffInput,
|
||||
) => Promise<ProviderGetCheckpointDiffResult>;
|
||||
catchUp: (input: ProviderCatchUpInput) => Promise<ProviderCatchUpResult>;
|
||||
revertToCheckpoint: (
|
||||
input: ProviderRevertToCheckpointInput,
|
||||
) => Promise<ProviderRevertToCheckpointResult>;
|
||||
|
||||
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
providerCatchUpInputSchema,
|
||||
providerCatchUpResultSchema,
|
||||
providerCheckpointSchema,
|
||||
providerEventSchema,
|
||||
providerGetCheckpointDiffInputSchema,
|
||||
@@ -156,6 +158,19 @@ describe("providerEventSchema", () => {
|
||||
expect(parsed.method).toBe("item/agentMessage/delta");
|
||||
});
|
||||
|
||||
it("accepts optional durable sequence metadata", () => {
|
||||
const parsed = providerEventSchema.parse({
|
||||
seq: 42,
|
||||
id: "evt_seq_1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "turn/completed",
|
||||
});
|
||||
expect(parsed.seq).toBe(42);
|
||||
});
|
||||
|
||||
it("accepts request approval metadata", () => {
|
||||
const parsed = providerEventSchema.parse({
|
||||
id: "evt_2",
|
||||
@@ -172,6 +187,33 @@ describe("providerEventSchema", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider catch-up schemas", () => {
|
||||
it("parses catch-up input defaults", () => {
|
||||
const parsed = providerCatchUpInputSchema.parse({});
|
||||
expect(parsed.afterSeq).toBe(0);
|
||||
expect(parsed.limit).toBe(1_000);
|
||||
});
|
||||
|
||||
it("parses catch-up result payload", () => {
|
||||
const parsed = providerCatchUpResultSchema.parse({
|
||||
events: [
|
||||
{
|
||||
seq: 7,
|
||||
id: "evt_7",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "turn/started",
|
||||
},
|
||||
],
|
||||
lastProviderSeq: 9,
|
||||
});
|
||||
expect(parsed.events[0]?.seq).toBe(7);
|
||||
expect(parsed.lastProviderSeq).toBe(9);
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerRespondToRequestInputSchema", () => {
|
||||
it("accepts valid decisions", () => {
|
||||
const parsed = providerRespondToRequestInputSchema.parse({
|
||||
|
||||
@@ -170,6 +170,11 @@ export const providerGetCheckpointDiffResultSchema = z.object({
|
||||
diff: z.string(),
|
||||
});
|
||||
|
||||
export const providerCatchUpInputSchema = z.object({
|
||||
afterSeq: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(5_000).default(1_000),
|
||||
});
|
||||
|
||||
export const providerRespondToRequestInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1),
|
||||
@@ -179,6 +184,7 @@ export const providerRespondToRequestInputSchema = z.object({
|
||||
export const providerEventKindSchema = z.enum(["session", "notification", "request", "error"]);
|
||||
|
||||
export const providerEventSchema = z.object({
|
||||
seq: z.number().int().positive().optional(),
|
||||
id: z.string().min(1),
|
||||
kind: providerEventKindSchema,
|
||||
provider: providerKindSchema,
|
||||
@@ -195,6 +201,11 @@ export const providerEventSchema = z.object({
|
||||
payload: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export const providerCatchUpResultSchema = z.object({
|
||||
events: z.array(providerEventSchema),
|
||||
lastProviderSeq: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export type ProviderKind = z.infer<typeof providerKindSchema>;
|
||||
export type ProviderApprovalPolicy = z.infer<typeof providerApprovalPolicySchema>;
|
||||
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
|
||||
@@ -219,6 +230,8 @@ export type ProviderRevertToCheckpointResult = z.infer<
|
||||
>;
|
||||
export type ProviderGetCheckpointDiffInput = z.input<typeof providerGetCheckpointDiffInputSchema>;
|
||||
export type ProviderGetCheckpointDiffResult = z.infer<typeof providerGetCheckpointDiffResultSchema>;
|
||||
export type ProviderCatchUpInput = z.input<typeof providerCatchUpInputSchema>;
|
||||
export type ProviderCatchUpResult = z.infer<typeof providerCatchUpResultSchema>;
|
||||
export type ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
@@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
stateBootstrapResultSchema,
|
||||
stateCatchUpInputSchema,
|
||||
stateEventSchema,
|
||||
stateListMessagesInputSchema,
|
||||
stateListMessagesResultSchema,
|
||||
stateMessageSchema,
|
||||
@@ -118,28 +117,4 @@ describe("state schemas", () => {
|
||||
const catchUp = stateCatchUpInputSchema.parse({});
|
||||
expect(catchUp.afterSeq).toBe(0);
|
||||
});
|
||||
|
||||
it("validates typed state event payload variants", () => {
|
||||
const event = stateEventSchema.parse({
|
||||
seq: 1,
|
||||
eventType: "project.upsert",
|
||||
entityId: "project-1",
|
||||
payload: {
|
||||
project: {
|
||||
id: "project-1",
|
||||
cwd: "/repo",
|
||||
name: "repo",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
updatedAt: "2026-02-19T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-19T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(event.eventType).toBe("project.upsert");
|
||||
if (event.eventType === "project.upsert") {
|
||||
expect(event.payload.project.id).toBe("project-1");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -103,83 +103,14 @@ export const stateCatchUpInputSchema = z.object({
|
||||
afterSeq: z.number().int().min(0).default(0),
|
||||
});
|
||||
|
||||
const stateEventBaseSchema = z.object({
|
||||
export const stateEventSchema = z.object({
|
||||
seq: z.number().int().positive(),
|
||||
eventType: z.string().min(1),
|
||||
entityId: z.string().min(1),
|
||||
payload: z.unknown(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const stateProjectUpsertPayloadSchema = z.object({
|
||||
project: stateProjectSchema,
|
||||
});
|
||||
|
||||
export const stateProjectDeletePayloadSchema = z.object({
|
||||
projectId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const stateThreadUpsertPayloadSchema = z.object({
|
||||
thread: stateThreadSchema,
|
||||
});
|
||||
|
||||
export const stateThreadDeletePayloadSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const stateMessageUpsertPayloadSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
message: stateMessageSchema,
|
||||
});
|
||||
|
||||
export const stateMessageDeletePayloadSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
messageId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const stateTurnSummaryUpsertPayloadSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnSummary: stateTurnSummarySchema,
|
||||
});
|
||||
|
||||
export const stateTurnSummaryDeletePayloadSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const stateEventSchema = z.discriminatedUnion("eventType", [
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("project.upsert"),
|
||||
payload: stateProjectUpsertPayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("project.delete"),
|
||||
payload: stateProjectDeletePayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("thread.upsert"),
|
||||
payload: stateThreadUpsertPayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("thread.delete"),
|
||||
payload: stateThreadDeletePayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("message.upsert"),
|
||||
payload: stateMessageUpsertPayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("message.delete"),
|
||||
payload: stateMessageDeletePayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("turn_summary.upsert"),
|
||||
payload: stateTurnSummaryUpsertPayloadSchema,
|
||||
}),
|
||||
stateEventBaseSchema.extend({
|
||||
eventType: z.literal("turn_summary.delete"),
|
||||
payload: stateTurnSummaryDeletePayloadSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
export const stateCatchUpResultSchema = z.object({
|
||||
events: z.array(stateEventSchema),
|
||||
lastStateSeq: z.number().int().min(0),
|
||||
@@ -273,14 +204,6 @@ export type StateThread = z.infer<typeof stateThreadSchema>;
|
||||
export type StateBootstrapThread = z.infer<typeof stateBootstrapThreadSchema>;
|
||||
export type StateBootstrapResult = z.infer<typeof stateBootstrapResultSchema>;
|
||||
export type StateCatchUpInput = z.input<typeof stateCatchUpInputSchema>;
|
||||
export type StateProjectUpsertPayload = z.infer<typeof stateProjectUpsertPayloadSchema>;
|
||||
export type StateProjectDeletePayload = z.infer<typeof stateProjectDeletePayloadSchema>;
|
||||
export type StateThreadUpsertPayload = z.infer<typeof stateThreadUpsertPayloadSchema>;
|
||||
export type StateThreadDeletePayload = z.infer<typeof stateThreadDeletePayloadSchema>;
|
||||
export type StateMessageUpsertPayload = z.infer<typeof stateMessageUpsertPayloadSchema>;
|
||||
export type StateMessageDeletePayload = z.infer<typeof stateMessageDeletePayloadSchema>;
|
||||
export type StateTurnSummaryUpsertPayload = z.infer<typeof stateTurnSummaryUpsertPayloadSchema>;
|
||||
export type StateTurnSummaryDeletePayload = z.infer<typeof stateTurnSummaryDeletePayloadSchema>;
|
||||
export type StateEvent = z.infer<typeof stateEventSchema>;
|
||||
export type StateCatchUpResult = z.infer<typeof stateCatchUpResultSchema>;
|
||||
export type StateListMessagesInput = z.input<typeof stateListMessagesInputSchema>;
|
||||
|
||||
@@ -7,4 +7,8 @@ describe("WS thread methods", () => {
|
||||
expect(WS_METHODS.threadsUpdateTerminalState).toBe("threads.updateTerminalState");
|
||||
expect("threadsUpdate" in WS_METHODS).toBe(false);
|
||||
});
|
||||
|
||||
it("includes provider catch-up method for durable stream resume", () => {
|
||||
expect(WS_METHODS.providersCatchUp).toBe("providers.catchUp");
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,7 @@ export const WS_METHODS = {
|
||||
providersListSessions: "providers.listSessions",
|
||||
providersListCheckpoints: "providers.listCheckpoints",
|
||||
providersGetCheckpointDiff: "providers.getCheckpointDiff",
|
||||
providersCatchUp: "providers.catchUp",
|
||||
providersRevertToCheckpoint: "providers.revertToCheckpoint",
|
||||
|
||||
// Project registry methods
|
||||
|
||||
+26
-3
@@ -58,6 +58,19 @@ function resolveOffset() {
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function resolvePublicHost() {
|
||||
const rawHost = process.env.T3CODE_PUBLIC_HOST?.trim();
|
||||
if (!rawHost) return undefined;
|
||||
|
||||
if (rawHost.includes("://") || rawHost.includes("/")) {
|
||||
throw new Error(
|
||||
`Invalid T3CODE_PUBLIC_HOST: ${rawHost}. Use only a host or IP (no protocol/path).`,
|
||||
);
|
||||
}
|
||||
|
||||
return rawHost;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const mode = process.argv[2];
|
||||
const isDryRun = process.argv.includes("--dry-run");
|
||||
@@ -69,6 +82,9 @@ function main() {
|
||||
const { offset, source } = resolveOffset();
|
||||
const serverPort = BASE_SERVER_PORT + offset;
|
||||
const webPort = BASE_WEB_PORT + offset;
|
||||
const publicHost = resolvePublicHost();
|
||||
const wsHost = publicHost ?? "localhost";
|
||||
const webHost = publicHost ?? "localhost";
|
||||
|
||||
if (serverPort > 65535 || webPort > 65535) {
|
||||
throw new Error(
|
||||
@@ -81,15 +97,22 @@ function main() {
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
|
||||
VITE_WS_URL: `ws://${wsHost}:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://${webHost}:${webPort}`,
|
||||
};
|
||||
|
||||
if (publicHost) {
|
||||
env.VITE_DEV_SERVER_HOST = "0.0.0.0";
|
||||
env.VITE_HMR_HOST = publicHost;
|
||||
}
|
||||
|
||||
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
|
||||
env.T3CODE_LOG_WS_EVENTS = "1";
|
||||
}
|
||||
|
||||
console.info(
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
|
||||
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}` +
|
||||
`${publicHost ? ` publicHost=${publicHost}` : ""}`,
|
||||
);
|
||||
|
||||
if (isDryRun) {
|
||||
|
||||
Reference in new issue
Block a user