Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

chore: separate dev/prod config paths and extract all hardcoded env vars

Gener78f08f5afde8
diff --git a/.env.example b/.env.example
new file mode 100644
index 000000000..07324f49e
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,159 @@
+# =============================================================================
+# Alook — Environment Variables
+# =============================================================================
+# Copy this file to .env and customize for your local development setup.
+# All variables are optional — sensible defaults are built in.
+#
+# The dev:cli script auto-sets ALOOK_SERVER_URL and ALOOK_PROJECT_ROOT,
+# so you typically only need .env overrides for non-default agent paths or
+# tuning daemon behavior.
+#
+# For auth secrets (Better Auth, OAuth), see src/web/.dev.vars.example.
+# =============================================================================
+
+
+# =============================================================================
+# Server & Project
+# =============================================================================
+
+# API server URL. Set automatically by `pnpm dev:cli`.
+# Production default: https://alook.ai
+# ALOOK_SERVER_URL=http://localhost:3000
+
+# Project root directory. Set automatically by `pnpm dev:cli`.
+# Used to locate .alook/ config dir in dev mode.
+# ALOOK_PROJECT_ROOT=/path/to/alook
+
+# Email domain suffix for agent handles (e.g. [email protected])
+# ALOOK_DOMAIN=alook.ai
+
+
+# =============================================================================
+# Local Dev Service URLs & Ports
+# =============================================================================
+# Used for service-binding fallbacks during local development.
+
+# WebSocket Durable Object worker URL (must match src/ws-do/wrangler.toml port)
+# DEV_WS_DO_URL=http://localhost:8789
+
+# Email worker URL (must match src/email-worker/wrangler.toml port)
+# DEV_EMAIL_WORKER_URL=http://localhost:8788
+
+# Daemon health check server port
+# ALOOK_HEALTH_PORT=19514
+
+
+# =============================================================================
+# Daemon — Identity
+# =============================================================================
+
+# Unique daemon identifier (defaults to hostname, suffixed with profile if set)
+# ALOOK_DAEMON_ID=my-machine
+
+# Human-readable device name shown in the web UI
+# ALOOK_DAEMON_DEVICE_NAME=My MacBook
+
+# Display name for the agent runtime
+# ALOOK_AGENT_RUNTIME_NAME=Local Agent
+
+
+# =============================================================================
+# Daemon — Storage
+# =============================================================================
+
+# Directory where the daemon stores workspace checkouts
+# Dev default: <project-root>/.alook/workspaces/
+# Prod default: ~/alook_workspaces
+# ALOOK_WORKSPACES_ROOT=~/alook_workspaces
+
+
+# =============================================================================
+# Daemon — Timing
+# =============================================================================
+
+# How often the daemon polls for new tasks (duration string: e.g. 3s, 500ms)
+# ALOOK_DAEMON_POLL_INTERVAL=3s
+
+# How often the daemon sends heartbeats to the server
+# ALOOK_DAEMON_HEARTBEAT_INTERVAL=15s
+
+# Maximum time a single agent task can run before being killed
+# ALOOK_AGENT_TIMEOUT=2h
+
+# Maximum number of tasks the daemon runs concurrently
+# ALOOK_DAEMON_MAX_CONCURRENT_TASKS=20
+
+# Keep shell environment variables across tasks
+# ALOOK_KEEP_ENV_AFTER_TASK=false
+
+# Graceful shutdown timeout before force-exit (ms)
+# ALOOK_SHUTDOWN_TIMEOUT_MS=5000
+
+# Message batch size — how many messages to buffer before flushing to server
+# ALOOK_MESSAGE_BATCH_SIZE=20
+
+# Message flush interval — max time before a partial batch is sent (ms)
+# ALOOK_MESSAGE_FLUSH_INTERVAL_MS=2000
+
+# Time (seconds) before a dispatched task is considered stale and failed
+# ALOOK_STALE_DISPATCH_TIMEOUT_S=20
+
+
+# =============================================================================
+# Shared Timing Constants
+# =============================================================================
+# Used by both web and CLI for real-time status tracking.
+
+# Client-side heartbeat interval (ms)
+# HEARTBEAT_INTERVAL_MS=3000
+
+# Time (ms) without heartbeat before a runtime is considered offline
+# OFFLINE_THRESHOLD_MS=9000
+
+# How often the web UI polls for new events (ms)
+# EVENT_POLL_INTERVAL_MS=2000
+
+
+# =============================================================================
+# Web Client (browser-side, requires NEXT_PUBLIC_ prefix)
+# =============================================================================
+
+# App URL used by auth client (defaults to http://localhost:3000)
+# NEXT_PUBLIC_APP_URL=http://localhost:3000
+
+# WebSocket Durable Object port (dev only, must match src/ws-do/wrangler.toml)
+# NEXT_PUBLIC_WS_DO_PORT=8789
+
+# Initial reconnect delay (ms), doubles on each retry
+# NEXT_PUBLIC_WS_RECONNECT_DELAY_MS=1000
+
+# Maximum reconnect delay cap (ms)
+# NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS=30000
+
+
+# =============================================================================
+# Agent Paths
+# =============================================================================
+# Paths to CLI agent binaries. Override if not on $PATH.
+
+# ALOOK_CLAUDE_PATH=claude
+# ALOOK_CODEX_PATH=codex
+# ALOOK_OPENCODE_PATH=opencode
+
+
+# =============================================================================
+# Agent Models
+# =============================================================================
+# Override the default model for each agent runtime.
+
+# ALOOK_CLAUDE_MODEL=
+# ALOOK_CODEX_MODEL=
+# ALOOK_OPENCODE_MODEL=
+
+
+# =============================================================================
+# Logging
+# =============================================================================
+
+# Log level: error | warn | info | debug
+# ALOOK_LOG_LEVEL=info
diff --git a/.gitignore b/.gitignore
index da71f75cb..619c85bcb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,4 +10,6 @@ dist/
temp/
docs/
.DS_Store
+.alook/
+.dev.vars
plans/
diff --git a/package.json b/package.json
index bec9dc65a..c1af65e86 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
"reinstall": "pnpm run clean && pnpm install",
"typecheck": "turbo run typecheck",
"dev:web": "pnpm --filter @alook/web dev",
- "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 pnpm --filter @alook/cli dev",
+ "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD pnpm --filter @alook/cli dev",
"dev:email": "pnpm --filter @alook/email-worker dev",
"dev:send": "node -e \"const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}fetch('http://localhost:8788/simulate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({from:f,to:t,subject:s,body:b})}).then(r=>r.json()).then(console.log).catch(e=>console.error('Email worker not running?',e.message))\"",
"test:shared": "pnpm --filter @alook/shared test",
diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts
index 9b1e303b0..8ad07ab0f 100644
--- a/src/cli/commands/daemon.ts
+++ b/src/cli/commands/daemon.ts
@@ -30,7 +30,8 @@ export function daemonCommand(): Command {
.command("status")
.description("Show daemon status")
.action(() => {
- console.log("check http://localhost:19514/health");
+ const port = process.env.ALOOK_HEALTH_PORT || "19514";
+ console.log(`check http://localhost:${port}/health`);
});
return cmd;
diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.ts
index 042498f0f..09f269e10 100644
--- a/src/cli/daemon/config.test.ts
+++ b/src/cli/daemon/config.test.ts
@@ -6,6 +6,7 @@ import { loadDaemonConfig, normalizeServerBaseURL } from "./config.js";
const DAEMON_ENV_KEYS = [
"ALOOK_SERVER_URL",
+ "ALOOK_PROJECT_ROOT",
"ALOOK_DAEMON_POLL_INTERVAL",
"ALOOK_DAEMON_HEARTBEAT_INTERVAL",
"ALOOK_AGENT_TIMEOUT",
@@ -105,15 +106,32 @@ describe("daemonId profile suffix", () => {
});
describe("workspacesRoot profile handling", () => {
- it("defaults to ~/alook_workspaces without profile", () => {
+ it("defaults to ~/alook_workspaces without profile in production", () => {
const cfg = loadDaemonConfig();
expect(cfg.workspacesRoot).toBe(join(homedir(), "alook_workspaces"));
});
- it("uses ~/alook_workspaces_{profile} with profile", () => {
+ it("uses ~/alook_workspaces_{profile} with profile in production", () => {
const cfg = loadDaemonConfig("dev");
expect(cfg.workspacesRoot).toBe(
join(homedir(), "alook_workspaces_dev"),
);
});
+
+ it("defaults to <project-root>/.alook/workspaces in dev mode", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
+ const cfg = loadDaemonConfig();
+ expect(cfg.workspacesRoot).toBe(
+ join("/tmp/my-project", ".alook", "workspaces"),
+ );
+ });
+
+ it("ALOOK_WORKSPACES_ROOT overrides dev mode default", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
+ process.env.ALOOK_WORKSPACES_ROOT = "/custom/path";
+ const cfg = loadDaemonConfig();
+ expect(cfg.workspacesRoot).toBe("/custom/path");
+ });
});
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.ts
index 7782013bc..d4d916f29 100644
--- a/src/cli/daemon/config.ts
+++ b/src/cli/daemon/config.ts
@@ -1,6 +1,6 @@
-import { hostname } from "os";
+import { hostname, homedir } from "os";
import { join } from "path";
-import { homedir } from "os";
+import { isDev } from "../lib/env.js";
function parseDuration(s: string): number {
if (!s) return 0;
@@ -61,12 +61,16 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {
daemonId = `${daemonId}-${profile}`;
}
- const workspacesRoot =
- process.env.ALOOK_WORKSPACES_ROOT ||
- join(
+ let defaultRoot: string;
+ if (isDev() && process.env.ALOOK_PROJECT_ROOT) {
+ defaultRoot = join(process.env.ALOOK_PROJECT_ROOT, ".alook", "workspaces");
+ } else {
+ defaultRoot = join(
homedir(),
profile ? `alook_workspaces_${profile}` : "alook_workspaces",
);
+ }
+ const workspacesRoot = process.env.ALOOK_WORKSPACES_ROOT || defaultRoot;
return {
serverURL: normalizeServerBaseURL(
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index dcea9229f..f96a71807 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -150,7 +150,8 @@ export async function startDaemon(
log.info("Shutting down...");
clearInterval(heartbeatTimer);
clearInterval(pollTimer);
- const timeout = setTimeout(() => process.exit(1), 5000);
+ const shutdownMs = Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;
+ const timeout = setTimeout(() => process.exit(1), shutdownMs);
try {
await client.deregister(allRuntimeIds);
} catch {
@@ -256,8 +257,8 @@ async function runTask(
output?: string;
}[] = [];
let seq = 0;
- const BATCH_SIZE = 20;
- const FLUSH_INTERVAL_MS = 2000;
+ const BATCH_SIZE = Number(process.env.ALOOK_MESSAGE_BATCH_SIZE) || 20;
+ const FLUSH_INTERVAL_MS = Number(process.env.ALOOK_MESSAGE_FLUSH_INTERVAL_MS) || 2000;
const flushMessages = async () => {
if (pendingMessages.length === 0) return;
diff --git a/src/cli/daemon/health.ts b/src/cli/daemon/health.ts
index 0926b506a..7064cd22f 100644
--- a/src/cli/daemon/health.ts
+++ b/src/cli/daemon/health.ts
@@ -1,6 +1,8 @@
import { createServer, type Server, type IncomingMessage, type ServerResponse } from "http";
-export function startHealthServer(port: number = 19514): Server {
+const DEFAULT_HEALTH_PORT = Number(process.env.ALOOK_HEALTH_PORT) || 19514;
+
+export function startHealthServer(port: number = DEFAULT_HEALTH_PORT): Server {
const startTime = Date.now();
const runtimeCount = 0;
@@ -25,7 +27,7 @@ export function startHealthServer(port: number = 19514): Server {
return server;
}
-export function createHealthServer(port: number = 19514) {
+export function createHealthServer(port: number = DEFAULT_HEALTH_PORT) {
let runtimeCount = 0;
const startTime = Date.now();
diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.ts
index 3e554af98..1432ae1c0 100644
--- a/src/cli/lib/config.test.ts
+++ b/src/cli/lib/config.test.ts
@@ -1,4 +1,4 @@
-import { vi, describe, it, expect, beforeEach } from "vitest";
+import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { join } from "path";
import { homedir } from "os";
@@ -10,6 +10,7 @@ vi.mock("fs", () => ({
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import {
+ configDir,
configPath,
loadCLIConfig,
loadCLIConfigForProfile,
@@ -25,10 +26,38 @@ beforeEach(() => {
vi.clearAllMocks();
});
+afterEach(() => {
+ delete process.env.ALOOK_SERVER_URL;
+ delete process.env.ALOOK_PROJECT_ROOT;
+});
+
+describe("configDir", () => {
+ it("returns ~/.alook in production", () => {
+ expect(configDir()).toBe(join(homedir(), ".alook"));
+ });
+
+ it("returns <project-root>/.alook in dev mode", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
+ expect(configDir()).toBe(join("/tmp/my-project", ".alook"));
+ });
+
+ it("falls back to ~/.alook in dev mode without ALOOK_PROJECT_ROOT", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ expect(configDir()).toBe(join(homedir(), ".alook"));
+ });
+});
+
describe("configPath", () => {
- it("returns ~/.alook/config.json", () => {
+ it("returns ~/.alook/config.json in production", () => {
expect(configPath()).toBe(join(homedir(), ".alook", "config.json"));
});
+
+ it("returns <project-root>/.alook/config.json in dev mode", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
+ expect(configPath()).toBe(join("/tmp/my-project", ".alook", "config.json"));
+ });
});
describe("loadCLIConfig", () => {
@@ -100,7 +129,7 @@ describe("loadCLIConfigForProfile", () => {
});
describe("saveCLIConfig", () => {
- it("writes valid JSON with mode 0600", () => {
+ it("writes valid JSON with mode 0600 to ~/.alook in production", () => {
const cfg = { token: "abc", server_url: "http://example.com" };
saveCLIConfig(cfg);
@@ -109,7 +138,25 @@ describe("saveCLIConfig", () => {
{ recursive: true, mode: 0o700 },
);
expect(mockedWriteFileSync).toHaveBeenCalledWith(
- configPath(),
+ join(homedir(), ".alook", "config.json"),
+ JSON.stringify(cfg, null, 2),
+ { mode: 0o600 },
+ );
+ });
+
+ it("writes to <project-root>/.alook in dev mode", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
+
+ const cfg = { token: "dev-token", server_url: "http://localhost:3000" };
+ saveCLIConfig(cfg);
+
+ expect(mockedMkdirSync).toHaveBeenCalledWith(
+ join("/tmp/my-project", ".alook"),
+ { recursive: true, mode: 0o700 },
+ );
+ expect(mockedWriteFileSync).toHaveBeenCalledWith(
+ join("/tmp/my-project", ".alook", "config.json"),
JSON.stringify(cfg, null, 2),
{ mode: 0o600 },
);
diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.ts
index be1004801..3fb320066 100644
--- a/src/cli/lib/config.ts
+++ b/src/cli/lib/config.ts
@@ -1,6 +1,7 @@
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
+import { isDev } from "./env.js";
interface WatchedWorkspace {
id: string;
@@ -23,8 +24,15 @@ interface CLIConfig {
export type { CLIConfig, ProfileConfig, WatchedWorkspace };
+export function configDir(): string {
+ if (isDev() && process.env.ALOOK_PROJECT_ROOT) {
+ return join(process.env.ALOOK_PROJECT_ROOT, ".alook");
+ }
+ return join(homedir(), ".alook");
+}
+
export function configPath(): string {
- return join(homedir(), ".alook", "config.json");
+ return join(configDir(), "config.json");
}
export function loadCLIConfig(): CLIConfig {
@@ -49,8 +57,7 @@ export function loadCLIConfigForProfile(profile?: string): ProfileConfig {
}
export function saveCLIConfig(cfg: CLIConfig): void {
- const dir = join(homedir(), ".alook");
- mkdirSync(dir, { recursive: true, mode: 0o700 });
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
writeFileSync(configPath(), JSON.stringify(cfg, null, 2), { mode: 0o600 });
}
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 2d5d149c4..3ca67cfe9 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -34,12 +34,12 @@ export const MessageRole = {
export type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole];
// Timing constants
-export const HEARTBEAT_INTERVAL_MS = 3_000;
-export const OFFLINE_THRESHOLD_MS = 9_000;
-export const EVENT_POLL_INTERVAL_MS = 2_000;
+export const HEARTBEAT_INTERVAL_MS = Number(process.env.HEARTBEAT_INTERVAL_MS) || 3_000;
+export const OFFLINE_THRESHOLD_MS = Number(process.env.OFFLINE_THRESHOLD_MS) || 9_000;
+export const EVENT_POLL_INTERVAL_MS = Number(process.env.EVENT_POLL_INTERVAL_MS) || 2_000;
export const AGENT_HANDLE_MIN_LENGTH = 4;
// Local dev URLs (used for service-binding fallbacks)
-export const DEV_WEB_URL = "http://localhost:3000";
-export const DEV_WS_DO_URL = "http://localhost:8789";
-export const DEV_EMAIL_WORKER_URL = "http://localhost:8788";
+export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000";
+export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789";
+export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8788";
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index ecfb44892..835031161 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -215,7 +215,9 @@ export async function cancelTask(db: Database, id: string) {
return rows[0] ?? null;
}
-export async function failStaleDispatchedTasks(db: Database, staleSeconds = 20) {
+const DEFAULT_STALE_SECONDS = Number(process.env.ALOOK_STALE_DISPATCH_TIMEOUT_S) || 20;
+
+export async function failStaleDispatchedTasks(db: Database, staleSeconds = DEFAULT_STALE_SECONDS) {
const threshold = new Date(Date.now() - staleSeconds * 1000).toISOString();
const rows = await db
.update(agentTaskQueue)
diff --git a/src/shared/src/utils/email.ts b/src/shared/src/utils/email.ts
index f3086677b..0efe43879 100644
--- a/src/shared/src/utils/email.ts
+++ b/src/shared/src/utils/email.ts
@@ -1,4 +1,4 @@
-const DOMAIN = "@alook.ai"
+const DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`
const HANDLE_RE = /^[a-zA-Z0-9-]{4,}$/
export function parseEmailHandle(a: string) { return a.endsWith(DOMAIN) ? a.slice(0, -DOMAIN.length) : "" }
export function toAlookAddress(h: string) { return `${h}${DOMAIN}` }
diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.example
new file mode 100644
index 000000000..8da61919e
--- /dev/null
+++ b/src/web/.dev.vars.example
@@ -0,0 +1,22 @@
+# =============================================================================
+# Cloudflare Worker Bindings — Local Development
+# =============================================================================
+# Copy this file to .dev.vars and fill in your values.
+# Wrangler reads .dev.vars automatically for local dev secrets.
+# NEVER commit .dev.vars — it contains real secrets.
+# =============================================================================
+
+# Session signing secret (generate with: openssl rand -base64 32)
+BETTER_AUTH_SECRET=
+BETTER_AUTH_URL=http://localhost:3000
+
+# GitHub OAuth App (https://github.com/settings/developers)
+GITHUB_CLIENT_ID=
+GITHUB_CLIENT_SECRET=
+
+# Google OAuth (https://console.cloud.google.com/apis/credentials)
+GOOGLE_CLIENT_ID=
+GOOGLE_CLIENT_SECRET=
+
+# Set to "production" to enable email OTP and disable password auth
+# NEXTJS_ENV=development
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 246076710..b1f1b7915 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -3,11 +3,13 @@ import { useEffect, useRef, useCallback } from "react"
import type { WsMessage } from "@alook/shared"
const isDev = process.env.NODE_ENV === "development"
-const WS_DO_PORT = 8789
+const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
+const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
+const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
export function useUserWs(onMessage: (msg: WsMessage) => void) {
const wsRef = useRef<WebSocket | null>(null)
- const reconnectDelay = useRef(1000)
+ const reconnectDelay = useRef(WS_RECONNECT_INIT)
const connect = useCallback(async () => {
let url: string
@@ -38,7 +40,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
wsRef.current = ws
ws.onopen = () => {
- reconnectDelay.current = 1000
+ reconnectDelay.current = WS_RECONNECT_INIT
if (authToken) {
ws.send(JSON.stringify({ type: "auth", token: authToken }))
}
@@ -55,8 +57,8 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
ws.onerror = () => {}
ws.onclose = () => {
- const delay = Math.min(reconnectDelay.current, 30_000)
- reconnectDelay.current = Math.min(delay * 2, 30_000)
+ const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
+ reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
setTimeout(connect, delay + Math.random() * 500)
}
}, [onMessage])
diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.ts
index 8329a549c..4e920712d 100644
--- a/src/web/src/lib/use-ws.ts
+++ b/src/web/src/lib/use-ws.ts
@@ -3,11 +3,13 @@ import { useEffect, useRef, useCallback } from "react"
import type { WsMessage } from "@alook/shared"
const isDev = process.env.NODE_ENV === "development"
-const WS_DO_PORT = 8789
+const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
+const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
+const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void) {
const wsRef = useRef<WebSocket | null>(null)
- const reconnectDelay = useRef(1000)
+ const reconnectDelay = useRef(WS_RECONNECT_INIT)
const connect = useCallback(async () => {
let url: string
@@ -38,7 +40,7 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
wsRef.current = ws
ws.onopen = () => {
- reconnectDelay.current = 1000
+ reconnectDelay.current = WS_RECONNECT_INIT
if (authToken) {
ws.send(JSON.stringify({ type: "auth", token: authToken }))
}
@@ -55,8 +57,8 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
ws.onerror = () => {}
ws.onclose = () => {
- const delay = Math.min(reconnectDelay.current, 30_000)
- reconnectDelay.current = Math.min(delay * 2, 30_000)
+ const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
+ reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
setTimeout(connect, delay + Math.random() * 500)
}
}, [agentId, onMessage])