Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): resolve Better Auth dual module hazard and D1 query timeouts (#83)

Generaa4e56812d5b
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5ab68e3e1..6da7c6bc2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11266,7 +11266,7 @@ snapshots:
'@next/eslint-plugin-next': 16.2.6
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
@@ -11289,7 +11289,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -11304,13 +11304,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -11325,7 +11325,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.3
is-core-module: 2.16.2
is-glob: 4.0.3
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 15d379c44..eae458583 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -223,6 +223,7 @@ export const agentRuntime = sqliteTable(
t.daemonId,
t.provider
),
+ index("idx_agent_runtime_workspace_daemon").on(t.workspaceId, t.daemonId),
]
);
@@ -376,6 +377,7 @@ export const agentTaskQueue = sqliteTable(
.on(t.conversationId, t.status),
index("idx_task_queue_trace").on(t.traceId),
index("idx_task_queue_parent").on(t.parentTaskId),
+ index("idx_task_queue_workspace_type_status").on(t.workspaceId, t.type, t.status),
foreignKey({
columns: [t.agentId, t.workspaceId],
foreignColumns: [agent.id, agent.workspaceId],
diff --git a/src/web/migrations/0028_add_runtime_and_task_indexes.sql b/src/web/migrations/0028_add_runtime_and_task_indexes.sql
new file mode 100644
index 000000000..c95e3d618
--- /dev/null
+++ b/src/web/migrations/0028_add_runtime_and_task_indexes.sql
@@ -0,0 +1,13 @@
+-- Add missing indexes for agent_runtime and agent_task_queue tables
+-- Fixes D1 query timeouts on high-frequency daemon poll and runtime sweep paths
+
+-- agent_runtime: fast lookup by (workspace_id, daemon_id) for daemon task polling
+-- The existing unique constraint on (workspace_id, daemon_id, provider) doesn't
+-- efficiently cover queries filtering only by workspace_id + daemon_id.
+CREATE INDEX IF NOT EXISTS idx_agent_runtime_workspace_daemon
+ ON agent_runtime(workspace_id, daemon_id);
+
+-- agent_task_queue: covers failStaleKillTasks() sweep query filtering by
+-- (workspace_id, type, status) during GET /api/runtimes
+CREATE INDEX IF NOT EXISTS idx_task_queue_workspace_type_status
+ ON agent_task_queue(workspace_id, type, status);
diff --git a/src/web/next.config.ts b/src/web/next.config.ts
index 418e01721..68c9e125a 100644
--- a/src/web/next.config.ts
+++ b/src/web/next.config.ts
@@ -2,6 +2,10 @@ import type { NextConfig } from "next";
import path from "node:path";
const nextConfig: NextConfig = {
+ // Prevent the bundler from creating duplicate copies of @better-auth/core,
+ // which breaks AsyncLocalStorage-based request state (dual module hazard).
+ // See: https://www.better-auth.com/docs/reference/faq#troubleshooting
+ serverExternalPackages: ["better-auth", "@better-auth/core"],
turbopack: {
root: path.resolve(__dirname, "../.."),
},
diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.ts
index 45903ab90..101ea3b4d 100644
--- a/src/web/src/app/api/runtimes/route.test.ts
+++ b/src/web/src/app/api/runtimes/route.test.ts
@@ -12,6 +12,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
+ createLogger: vi.fn(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() })),
queries: {
runtime: {
listAgentRuntimes: (...args: unknown[]) => mockListAgentRuntimes(...args),
diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.ts
index c5b8f0f5b..cf52d92be 100644
--- a/src/web/src/app/api/runtimes/route.ts
+++ b/src/web/src/app/api/runtimes/route.ts
@@ -1,5 +1,5 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries } from "@alook/shared"
+import { queries, createLogger } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
@@ -8,6 +8,8 @@ import { runtimeToResponse } from "@/lib/api/responses";
import { sweepStaleState } from "@/lib/services/sweep";
import { cacheKeys } from "@/lib/cache";
+const log = createLogger({ service: "api:runtimes" })
+
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
@@ -16,7 +18,11 @@ export const GET = withAuth(async (req, ctx) => {
const db = getDb((env as Env).DB)
// Sweep stale state: mark offline runtimes, fail stuck tasks, reconcile agents
- await sweepStaleState(db, ws.workspaceId);
+ try {
+ await sweepStaleState(db, ws.workspaceId);
+ } catch (err) {
+ log.warn("sweepStaleState failed, continuing", { workspaceId: ws.workspaceId, err: String(err) })
+ }
const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId);
diff --git a/src/web/src/lib/db.test.ts b/src/web/src/lib/db.test.ts
index 27dab36b2..268b25312 100644
--- a/src/web/src/lib/db.test.ts
+++ b/src/web/src/lib/db.test.ts
@@ -21,7 +21,7 @@ describe("withD1Retry", () => {
it("throws after all retries exhausted", async () => {
const fn = vi.fn().mockRejectedValue(new Error("D1 down"));
await expect(withD1Retry(fn)).rejects.toThrow("D1 down");
- expect(fn).toHaveBeenCalledTimes(2);
+ expect(fn).toHaveBeenCalledTimes(4);
});
it("respects custom retry count", async () => {
diff --git a/src/web/src/lib/db.ts b/src/web/src/lib/db.ts
index 1070a4ecb..2c04dc40f 100644
--- a/src/web/src/lib/db.ts
+++ b/src/web/src/lib/db.ts
@@ -7,7 +7,7 @@ export function getDb(d1: D1Database): Database {
return createDb(session as unknown as Parameters<typeof createDb>[0])
}
-export async function withD1Retry<T>(fn: () => Promise<T>, retries = 1): Promise<T> {
+export async function withD1Retry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
for (let i = 0; i <= retries; i++) {
try {
return await fn();