TypeScript
fix: database errors show actionable recovery guidance (#20748)
Alex Southwell38c662508caf
diff --git a/apps/server/src/orchestration-v2/UserFacingErrors.test.ts b/apps/server/src/orchestration-v2/UserFacingErrors.test.tsindex ecb57bdc4c6..6eb75f31fbb 100644--- a/apps/server/src/orchestration-v2/UserFacingErrors.test.ts+++ b/apps/server/src/orchestration-v2/UserFacingErrors.test.ts@@ -1,5 +1,13 @@import { assert, describe, it } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";+import * as SqlClient from "effect/sql/SqlClient";+import { SqlError, classifySqliteError } from "effect/sql/SqlError";+import { toPersistenceSqlError } from "../persistence/Errors.ts";import { userFacingDispatchErrorMessage } from "./UserFacingErrors.ts";describe("userFacingDispatchErrorMessage", () => {@@ -65,4 +73,91 @@ describe("userFacingDispatchErrorMessage", () => {"Claude provider thread provider-thread-1 has no live query.",);});++ it.effect("explains a real database open failure through dispatch and persistence wrappers", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-database-error-" });+ const cause = yield* Effect.void.pipe(+ Effect.provide(+ NodeSqliteClient.layer({ filename: path.join(directory, "missing", "state.sqlite") }),+ ),+ Effect.flip,+ );+ const message = userFacingDispatchErrorMessage({+ message: "Failed to dispatch orchestration command message.dispatch (command-1).",+ cause: toPersistenceSqlError("OrchestrationEventStore.append:query")(cause),+ });++ assert.include(message, "server could not open a database file (SQLITE_CANTOPEN)");+ assert.include(message, "machine running the server");+ assert.include(message, "free disk space");+ assert.include(message, "data and temporary directories exist and are writable");+ assert.include(message, "then retry");+ assert.notInclude(message, directory);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("explains a full database and allows a retry after capacity is restored", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* sql`CREATE TABLE entries (payload BLOB)`;+ yield* sql`PRAGMA max_page_count = 2`;+ const cause = yield* sql`INSERT INTO entries VALUES (zeroblob(16384))`.pipe(Effect.flip);+ const message = userFacingDispatchErrorMessage({ cause });++ assert.include(message, "database or disk is full (SQLITE_FULL)");+ assert.include(message, "Free space on the machine running the server, then retry");+ assert.include(message, "database size limit");++ yield* sql`PRAGMA max_page_count = 100`;+ yield* sql`INSERT INTO entries VALUES (zeroblob(16384))`;+ const rows = yield* sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`;+ assert.equal(rows[0]?.count, 1);+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),+ );++ it.effect("gives server permission guidance for a real read-only failure", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* sql`CREATE TABLE entries (payload TEXT)`;+ yield* sql`PRAGMA query_only = ON`;+ const cause = yield* sql`INSERT INTO entries VALUES ('private-message')`.pipe(Effect.flip);+ const message = userFacingDispatchErrorMessage(cause);++ assert.include(message, "server database is read-only (SQLITE_READONLY)");+ assert.include(message, "data directory is writable");+ assert.notInclude(message, "private-message");+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),+ );++ it.each([+ [5, "SQLITE_BUSY", "Wait a moment, then retry"],+ [6, "SQLITE_LOCKED", "Wait a moment, then retry"],+ [10 | (3 << 8), "SQLITE_IOERR", "free disk space and disk health"],+ [14 | (6 << 8), "SQLITE_CANTOPEN", "exist and are writable"],+ [11, "SQLITE_CORRUPT", "Preserve the server data directory"],+ [26, "SQLITE_NOTADB", "configured database path"],+ ] as const)("maps SQLite code %i to %s with recovery guidance", (errcode, code, guidance) => {+ const cause = Object.assign(new Error("private-query-data"), { errcode, errno: errcode });+ const error = new SqlError({ reason: classifySqliteError(cause) });+ const message = userFacingDispatchErrorMessage({ cause: error });++ assert.include(message, code);+ assert.include(message, guidance);+ assert.notInclude(message, "private-query-data");+ });++ it("keeps unknown SQL failures contextual without exposing driver text or parameters", () => {+ const cause = Object.assign(new Error("private-query-data"), { errcode: 1 });+ const error = new SqlError({ reason: classifySqliteError(cause) });+ const message = userFacingDispatchErrorMessage({+ cause: toPersistenceSqlError("OrchestrationEventStore.append:query")(error),+ });++ assert.include(message, "server could not complete this database request");+ assert.include(message, "server logs");+ assert.notInclude(message, "private-query-data");+ });});diff --git a/apps/server/src/orchestration-v2/UserFacingErrors.ts b/apps/server/src/orchestration-v2/UserFacingErrors.tsindex 7e4c92d9c15..36356be265d 100644--- a/apps/server/src/orchestration-v2/UserFacingErrors.ts+++ b/apps/server/src/orchestration-v2/UserFacingErrors.ts@@ -1,5 +1,6 @@import { PROVIDER_DISPLAY_NAMES, type ProviderDriverKind } from "@t3tools/contracts";import * as Predicate from "effect/Predicate";+import * as SqlError from "effect/sql/SqlError";const GENERIC_ERROR_PREFIXES = ["Failed to dispatch orchestration V2 command",@@ -7,6 +8,35 @@ const GENERIC_ERROR_PREFIXES = ["Provider adapter failed while dispatching orchestration command ",];+const SQLITE_RECOVERY_MESSAGES: Readonly<Record<number, string>> = {+ 5: "The T3 Code server database is busy (SQLITE_BUSY). Wait a moment, then retry. If this keeps happening, check for another T3 Code process using the same data directory on the server.",+ 6: "The T3 Code server database is locked (SQLITE_LOCKED). Wait a moment, then retry. If this keeps happening, check the server logs for the process holding the database lock.",+ 8: "The T3 Code server database is read-only (SQLITE_READONLY). On the machine running the server, check that its data directory is writable and its disk is mounted read-write, then retry.",+ 10: "The T3 Code server could not read or write its database (SQLITE_IOERR). On the machine running the server, check free disk space and disk health, then retry. If it still fails, check the server logs.",+ 11: "The T3 Code server database appears damaged (SQLITE_CORRUPT). Preserve the server data directory and check the server logs before restoring a database backup.",+ 13: "The T3 Code server could not save this change because its database or disk is full (SQLITE_FULL). Free space on the machine running the server, then retry. If space is available, check the server logs for a database size limit.",+ 14: "The T3 Code server could not open a database file (SQLITE_CANTOPEN). On the machine running the server, check free disk space and that its data and temporary directories exist and are writable, then retry. If it still fails, check the server logs.",+ 26: "The T3 Code server could not read its database file (SQLITE_NOTADB). Preserve the server data directory and check the configured database path and server logs before restoring a database backup.",+};++function databaseErrorMessage(value: unknown): string | undefined {+ if (!SqlError.isSqlError(value)) return undefined;++ let cause: unknown = value.cause;+ const seen = new Set<unknown>();+ while (Predicate.isObject(cause) && !seen.has(cause)) {+ seen.add(cause);+ // node:sqlite uses extended result codes; their low byte is the primary code.+ if (typeof cause.errcode === "number" && Number.isInteger(cause.errcode) && cause.errcode > 0) {+ const message = SQLITE_RECOVERY_MESSAGES[cause.errcode & 0xff];+ if (message !== undefined) return message;+ }+ cause = cause.cause;+ }++ return "The T3 Code server could not complete this database request. Retry once; if it still fails, check the server logs for the database error.";+}+const CAPABILITY_REJECTION_MESSAGES: Record<string, (provider: string) => string> = {queued_messages: (p) => `${p} cannot queue messages behind an active run.`,active_steering: (p) =>@@ -81,6 +111,9 @@ function collectErrorMessages(value: unknown, seen: Set<unknown>): ReadonlyArrayreturn value.flatMap((item) => collectErrorMessages(item, seen));}+ const databaseMessage = databaseErrorMessage(value);+ if (databaseMessage !== undefined) return [databaseMessage];+const message = messageFrom(value);if (!Predicate.isObject(value)) {return message === undefined ? [] : [message];diff --git a/apps/web/src/components/chat/ThreadErrorBanner.tsx b/apps/web/src/components/chat/ThreadErrorBanner.tsxindex 4fa718dba94..54f65238687 100644--- a/apps/web/src/components/chat/ThreadErrorBanner.tsx+++ b/apps/web/src/components/chat/ThreadErrorBanner.tsx@@ -3,9 +3,9 @@ import { memo } from "react";import { Alert, AlertAction, AlertDescription } from "../ui/alert";import { Button } from "../ui/button";import { CircleAlertIcon, XIcon } from "lucide-react";-import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { OpenAI } from "../Icons";import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";+import { ExpandableText } from "../settings/ExpandableText";export function getThreadErrorBannerKey(threadKey: string, error: string | null): string | null {return error === null ? null : `${threadKey}\u0000${error}`;@@ -59,12 +59,7 @@ export const ThreadErrorBanner = memo(function ThreadErrorBanner({<p>Review your usage settings in ChatGPT to continue.</p></div>) : (- <Tooltip>- <TooltipTrigger render={<div className="line-clamp-3" />}>{error}</TooltipTrigger>- <TooltipPopup side="top" className="whitespace-pre-wrap">- {error}- </TooltipPopup>- </Tooltip>+ <ExpandableText text={error} />)}</AlertDescription>{(chatGptUsageLimit || onDismiss) && (