See screenshot
General discussion posting is broken
Screenshot shows POST /api/threads returning 500 when the workspace is "None — general discussion". Plan: trace the no-workspace path through app/api/threads/route.ts → lib/data.ts (createThread / embedPost / any workspace-dependent step) and find what still assumes workspaceId is non-null, fix it, and add a guard so a general thread never touches workspace-only code.
Diagnosis. The whole no-workspace path (POST /api/threads → createThread → embedPost) handles workspaceId: null correctly, and the Drizzle schema has threads.workspace_id nullable. But that nullability was introduced by drizzle/0003_optional_workspace.sql (ALTER TABLE threads ALTER COLUMN workspace_id DROP NOT NULL), and nothing applies migrations on deploy — npm run db:migrate is a manual step (README step 4) and build is just next build. So production Postgres still has the NOT NULL constraint, the insert fails with 23502 null value in column "workspace_id", guarded() only maps Forbidden, and the client shows a bare Failed: 500.
(I can't confirm against the prod DB from the sandbox — no DATABASE_URL here — but it's the only thing in this path that can 500, and 0003 is the first migration that shipped after the DB was set up.)
Fix, three parts:
scripts/migrate.ts+build: "tsx scripts/migrate.ts && next build"— pending migrations run automatically on every Vercel production build (skipped for preview builds so a thread branch can't migrate the prod DB, and skipped whenDATABASE_URLis unset). Usesdrizzle-orm/postgres-js/migrator, which shares the__drizzle_migrationstable withdrizzle-kit migrate, so the manual command still works.guarded()returns{ error }JSON for unexpected errors (and logs them) instead of Next's blank 500, and the new-thread / workspace forms display that message instead ofFailed: 500.- README deploy note.
Until this is deployed, the immediate unblock is npm run db:migrate against prod.
threadide@1ee928dWhat broke
Posting a thread with Workspace = None — general discussion → POST /api/threads → 500. The code path is fine; the database wasn't migrated. drizzle/0003_optional_workspace.sql (ALTER TABLE threads ALTER COLUMN workspace_id DROP NOT NULL) landed in PR "Let threads exist without a workspace", but migrations were a manual npm run db:migrate step and nothing runs them on deploy. Prod still has NOT NULL, so the insert fails with Postgres 23502, guarded() only mapped Forbidden, and the form printed a bare Failed: 500.
Verified in the sandbox with a real Postgres 17 + pgvector: applied 0000–0002 with drizzle-kit, inserted a null-workspace thread → ERROR: null value in column "workspace_id" of relation "threads" violates not-null constraint (the exact 500). Ran the new scripts/migrate.ts → 0003 applied into the same drizzle.__drizzle_migrations table → insert succeeds. Re-run is a no-op.
The fix (branch thread/387d5ea8, pushed)
- Migrations run on production builds.
scripts/migrate.ts(drizzle-orm'smigrate(), compatible withdrizzle-kit migrate) is now the first step ofnpm run build, anddb:migratepoints at it too. It skips whenDATABASE_URLis unset orVERCEL_ENVis a preview/development build, so a thread-branch preview can't push an unmerged migration onto the shared DB. RequiresDATABASE_URLto be exposed to the build environment in Vercel (it is by default unless the env var is scoped to runtime only — worth a glance). - 500s are self-describing.
guarded()now logs and returns{ error: message }JSON for unexpected errors; newlib/client-errors.ts → failureMessage(res)renders that in the new-thread and workspace forms (also collapses zod field errors). Had this been in place the form would have saidnull value in column "workspace_id"…instead ofFailed: 500. - README deploy section documents the above.
To unblock right now
Merging this and letting the production build run will apply 0003 automatically. If you want it fixed before merging: npm run db:migrate (or npx drizzle-kit migrate) with prod DATABASE_URL.
I haven't opened a PR — say so if you want one.
Diff · 7 files
diff --git a/threadide/package.json b/threadide/package.json
--- a/threadide/package.json
+++ b/threadide/package.json
@@ -4,10 +4,10 @@
"scripts": {
"dev": "next dev",
- "build": "next build",
+ "build": "tsx scripts/migrate.ts && next build",
"start": "next start",
"worker": "AGENT_RUNNER=local tsx worker/index.ts",
- "db:migrate": "drizzle-kit migrate",
+ "db:migrate": "tsx scripts/migrate.ts",
diff --git a/threadide/scripts/migrate.ts b/threadide/scripts/migrate.ts
new file mode 100644
--- /dev/null
+++ b/threadide/scripts/migrate.ts
@@ -0,0 +1,45 @@
+/**
+ * Applies pending SQL migrations from ./drizzle. Runs as the first step of `npm run build`
+ * so a Vercel production deploy can never ship schema code the database doesn't have yet.
+ * Skipped when DATABASE_URL is unset, or VERCEL_ENV is set to something other than "production".
+ * Shares the drizzle.__drizzle_migrations table with `drizzle-kit migrate`.
+ */
+import "dotenv/config";
+import { drizzle } from "drizzle-orm/postgres-js";
+import { migrate } from "drizzle-orm/postgres-js/migrator";
+import postgres from "postgres";
+
+async function main() {
+ const url = process.env.DATABASE_URL;
+ const env = process.env.VERCEL_ENV;
+ if (!url) {
+ console.log("[migrate] DATABASE_URL not set; skipping");
+ return;
+ }
+ if (env && env !== "production") {
+ console.log(`[migrate] VERCEL_ENV=${env}; skipping (only production builds migrate)`);
+ return;
+ }
+ const client = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ await migrate(drizzle(client), { migrationsFolder: "./drizzle" });
+ console.log("[migrate] database is up to date");
+ } finally {
+ await client.end();
+ }
+}
+
+main().catch((err) => {
+ console.error("[migrate] failed", err);
+ process.exit(1);
+});
diff --git a/threadide/lib/session.ts b/threadide/lib/session.ts
--- a/threadide/lib/session.ts
+++ b/threadide/lib/session.ts
@@ -95,7 +95,9 @@ export function guarded<T extends unknown[]>(fn: (...args: T) => Promise<Response>) {
} catch (e) {
if (e instanceof Forbidden) return Response.json({ error: e.message }, { status: e.status });
- throw e;
+ console.error("[api] unhandled error", e);
+ const message = e instanceof Error ? e.message : String(e);
+ return Response.json({ error: message }, { status: 500 });
}
diff --git a/threadide/lib/client-errors.ts b/threadide/lib/client-errors.ts
new file mode 100644
--- /dev/null
+++ b/threadide/lib/client-errors.ts
@@ -0,0 +1,22 @@
+/** Turns a failed fetch Response into the text a form should show ({ error } from guarded(); zod flatten → first field message). */
+export async function failureMessage(res: Response): Promise<string> {
+ const fallback = `Failed: ${res.status}`;
+ try {
+ const json = (await res.json()) as { error?: unknown };
+ const err = json?.error;
+ if (typeof err === "string" && err.trim()) return err;
+ if (err && typeof err === "object") {
+ const flat = err as { formErrors?: string[]; fieldErrors?: Record<string, string[]> };
+ const field = Object.entries(flat.fieldErrors ?? {}).find(([, v]) => v?.length);
+ if (field) return `${field[0]}: ${field[1][0]}`;
+ if (flat.formErrors?.length) return flat.formErrors[0];
+ }
+ } catch {
+ /* not JSON */
+ }
+ return fallback;
+}
diff --git a/threadide/components/new-thread-form.tsx b/threadide/components/new-thread-form.tsx
--- a/threadide/components/new-thread-form.tsx
+++ b/threadide/components/new-thread-form.tsx
@@ -54,7 +55,7 @@
setBusy(false);
- if (!res.ok) return setError(`Failed: ${res.status}`);
+ if (!res.ok) return setError(await failureMessage(res));
router.push(`/threads/${(await res.json()).id}`);
diff --git a/threadide/components/workspace-forms.tsx b/threadide/components/workspace-forms.tsx
--- a/threadide/components/workspace-forms.tsx
+++ b/threadide/components/workspace-forms.tsx
@@ -28,7 +29,7 @@
- if (!res.ok) return setError(`Failed: ${res.status}`);
+ if (!res.ok) return setError(await failureMessage(res));
@@ -70,7 +71,7 @@
- if (!res.ok) return setError(res.status === 500 ? "Alias already used?" : `Failed: ${res.status}`);
+ if (!res.ok) return setError(await failureMessage(res));