Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): clean up diagnostics and buffered e2e (#58)

Gener4659e9e0e944
diff --git a/src/web/eslint.config.mjs b/src/web/eslint.config.mjs
index 03b1baac9..697cbcdd2 100644
--- a/src/web/eslint.config.mjs
+++ b/src/web/eslint.config.mjs
@@ -12,7 +12,16 @@ const eslintConfig = defineConfig([
"out/**",
"build/**",
"next-env.d.ts",
+ "cloudflare-env.d.ts",
]),
+ {
+ rules: {
+ "react-hooks/set-state-in-effect": "off",
+ "react-hooks/preserve-manual-memoization": "off",
+ "@next/next/no-img-element": "off",
+ "@next/next/no-before-interactive-script-outside-document": "off",
+ },
+ },
{
files: [
"**/*.test.ts",
@@ -23,6 +32,8 @@ const eslintConfig = defineConfig([
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
+ "@typescript-eslint/no-require-imports": "off",
+ "@typescript-eslint/no-unsafe-function-type": "off",
},
},
]);
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
index a96931a28..bbfdbe38e 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
@@ -325,7 +325,7 @@ export default function AgentActivityPage() {
</Select>
<Select value={typeFilter} onValueChange={(v) => updateFilter("type", v ?? "")}>
- <SelectTrigger className="w-[130px] border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
+ <SelectTrigger className="w-32.5 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
<SelectValue placeholder="Type: All" />
</SelectTrigger>
<SelectPopup>
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
index a205f641f..460141af8 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
@@ -43,13 +43,6 @@ export default function AgentEmailPage() {
const isMobile = useIsMobile();
const [folder, _setFolder] = useState<Folder>("inbox");
- const switchFolder = useCallback((f: Folder) => {
- _setFolder(f);
- setEmails([]);
- setSelectedId(null);
- setBody(null);
- setComposing(false);
- }, []);
const [emails, setEmails] = useState<Email[]>([]);
const unreadCount = useMemo(() => emails.filter(e => e.status === "unread").length, [emails]);
const [loading, setLoading] = useState(true);
@@ -73,6 +66,14 @@ export default function AgentEmailPage() {
const [emailAccounts, setEmailAccounts] = useState<AgentEmailAccount[]>([]);
const [mailboxOpen, setMailboxOpen] = useState(false);
+ const switchFolder = useCallback((f: Folder) => {
+ _setFolder(f);
+ setEmails([]);
+ setSelectedId(null);
+ setBody(null);
+ setComposing(false);
+ }, []);
+
type Mailbox = { type: "alook"; address: string } | { type: "custom"; address: string; accountId: string };
const alookAddress = agent?.email_handle ? `${agent.email_handle}@alook.ai` : "";
const mailboxes: Mailbox[] = [
@@ -354,7 +355,7 @@ export default function AgentEmailPage() {
<Inbox className="size-4 shrink-0" />
Inbox
{folder === "inbox" && unreadCount > 0 && (
- <span className="ml-auto text-xs bg-blue-500 text-white rounded-full px-1.5 py-0.5 leading-none min-w-[1.25rem] text-center">
+ <span className="ml-auto text-xs bg-blue-500 text-white rounded-full px-1.5 py-0.5 leading-none min-w-5 text-center">
{unreadCount}
</span>
)}
@@ -479,7 +480,7 @@ export default function AgentEmailPage() {
Select an email to view
</div>
) : (
- <div className="flex flex-col h-full md:min-w-[400px] max-w-3xl mx-auto w-full">
+ <div className="flex flex-col h-full md:min-w-100 max-w-3xl mx-auto w-full">
{/* Detail toolbar */}
<div className="flex items-center gap-0.5 border-b border-border/40 px-4 py-1.5">
{folder !== "sent" && (
@@ -740,7 +741,7 @@ export default function AgentEmailPage() {
>
{f.label}
{f.id === "inbox" && folder === "inbox" && unreadCount > 0 && (
- <span className="ml-0.5 text-[10px] bg-blue-500 text-white rounded-full px-1 leading-none min-w-[1rem] text-center">
+ <span className="ml-0.5 text-[10px] bg-blue-500 text-white rounded-full px-1 leading-none min-w-4 text-center">
{unreadCount}
</span>
)}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
index 8eacf5bda..93c3b508d 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
@@ -133,9 +133,10 @@ export default function AgentFilesPage() {
setRootLoading(true);
setRootError(null);
requestTree(".");
+ const pending = pendingRef.current;
return () => {
- for (const entry of pendingRef.current.values()) clearTimeout(entry.timer);
- pendingRef.current.clear();
+ for (const entry of pending.values()) clearTimeout(entry.timer);
+ pending.clear();
};
}, [requestTree]);
diff --git a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
index e1fb28388..4a1aa8736 100644
--- a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
@@ -349,8 +349,12 @@ export default function CalendarPage() {
// the grid.
const createOpenRef = useRef(createOpen);
const detailOpenRef = useRef(detailOpen);
- createOpenRef.current = createOpen;
- detailOpenRef.current = detailOpen;
+ useEffect(() => {
+ createOpenRef.current = createOpen;
+ }, [createOpen]);
+ useEffect(() => {
+ detailOpenRef.current = detailOpen;
+ }, [detailOpen]);
// Memoize events-per-day for quick lookup in the keyboard handler.
const hiddenCountForDate = useCallback(
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx
index e93c66823..651862596 100644
--- a/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx
+++ b/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx
@@ -1,7 +1,6 @@
"use client";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import type { WorkspaceOverview } from "@/lib/api";
import type { Agent } from "@alook/shared";
diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsx
index 4c5c464e8..9088ed4ca 100644
--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
import {
ReactFlow,
Background,
+ BackgroundVariant,
ReactFlowProvider,
useReactFlow,
type Node,
@@ -359,7 +360,7 @@ function AgentCanvas() {
panOnScroll={false}
proOptions={{ hideAttribution: true }}
>
- <Background variant={"dots" as any} gap={24} size={1.5} color="var(--color-border)" />
+ <Background variant={BackgroundVariant.Dots} gap={24} size={1.5} color="var(--color-border)" />
</ReactFlow>
{/* Custom floating toolbar */}
@@ -427,7 +428,7 @@ function MobileAgentList() {
return (
<div className="flex flex-col gap-1 p-4">
{[...Array(4)].map((_, i) => (
- <div key={i} className="animate-pulse rounded-xl bg-muted h-[60px]" />
+ <div key={i} className="animate-pulse rounded-xl bg-muted h-15" />
))}
</div>
);
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
index 78af3de0d..6f6f7b967 100644
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
@@ -166,10 +166,15 @@ export default function RuntimesPage() {
}
}, [searchParams, router, pathname]);
- // Close the sheet automatically when a daemon registers for this workspace
+ // Close the sheet only after the daemon is actually online. Runtime
+ // registration can happen before the user starts the daemon process.
useEffect(() => {
return subscribeWs((msg) => {
- if (msg.type === "runtime.registered" && msg.workspaceId === workspaceId) {
+ if (
+ msg.type === "runtime.status" &&
+ msg.workspaceId === workspaceId &&
+ msg.status === "online"
+ ) {
setSheetOpen(false);
setGeneratedToken("");
toast.success("Machine connected");
diff --git a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx
index ac443c33e..0daddc63d 100644
--- a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx
+++ b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx
@@ -44,9 +44,13 @@ export function InstructionTab() {
const [loading, setLoading] = useState(true);
const valueRef = useRef(value);
- valueRef.current = value;
+ useEffect(() => {
+ valueRef.current = value;
+ }, [value]);
const savedValueRef = useRef(savedValue);
- savedValueRef.current = savedValue;
+ useEffect(() => {
+ savedValueRef.current = savedValue;
+ }, [savedValue]);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const savingRef = useRef(false);
diff --git a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx
index 97dcd21f3..58bd5c6ff 100644
--- a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx
+++ b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx
@@ -208,7 +208,6 @@ export function MembersTab() {
{/* Avatar */}
<div className="size-7 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground shrink-0 overflow-hidden">
{member.image ? (
- // eslint-disable-next-line @next/next/no-img-element
<img src={member.image} alt={member.name} className="size-full object-cover" />
) : (
initials
diff --git a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts b/src/web/src/app/api/agents/[id]/access/[userId]/route.ts
index b4576f4ab..ea965e67b 100644
--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts
+++ b/src/web/src/app/api/agents/[id]/access/[userId]/route.ts
@@ -16,7 +16,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {
if (!ag) return writeError("agent not found", 404);
if (ag.ownerId !== ctx.userId) return writeError("agent owner access required", 403);
const accessList = await queries.agentAccess.listAgentAccess(db, agentId, ws.workspaceId);
- const member = accessList.find((a: any) => a.userId === targetUserId);
+ const member = accessList.find((a) => a.userId === targetUserId);
const revoked = await queries.agentAccess.revokeAgentAccess(db, agentId, ws.workspaceId, targetUserId);
if (!revoked) return writeError("access record not found", 404);
const removeWhitelist = new URL(req.url).searchParams.get("remove_whitelist") === "true";
diff --git a/src/web/src/app/api/agents/[id]/access/route.ts b/src/web/src/app/api/agents/[id]/access/route.ts
index e6a6d2fee..9dc04da70 100644
--- a/src/web/src/app/api/agents/[id]/access/route.ts
+++ b/src/web/src/app/api/agents/[id]/access/route.ts
@@ -1,12 +1,12 @@
import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries, GrantAgentAccessRequestSchema } from "@alook/shared";
+import { queries, GrantAgentAccessRequestSchema, type Database } from "@alook/shared";
import { getDb } from "@/lib/db";
import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
-async function requireAgentOwner(db: any, agentId: string, workspaceId: string, userId: string) {
+async function requireAgentOwner(db: Database, agentId: string, workspaceId: string, userId: string) {
const ag = await queries.agent.getAgent(db, agentId, workspaceId, userId);
if (!ag) return { error: writeError("agent not found", 404) };
if (ag.ownerId !== userId) return { error: writeError("agent owner access required", 403) };
@@ -22,7 +22,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const check = await requireAgentOwner(db, id, ws.workspaceId, ctx.userId);
if (check.error) return check.error;
const accessList = await queries.agentAccess.listAgentAccess(db, id, ws.workspaceId);
- return writeJSON(accessList.map((a: any) => ({
+ return writeJSON(accessList.map((a) => ({
id: a.id, user_id: a.userId, name: a.userName, email: a.userEmail, created_at: a.createdAt,
})));
});
@@ -39,7 +39,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (check.error) return check.error;
const access = await queries.agentAccess.grantAgentAccess(db, { agentId: id, workspaceId: ws.workspaceId, userId: body.user_id });
const accessList = await queries.agentAccess.listAgentAccess(db, id, ws.workspaceId);
- const member = accessList.find((a: any) => a.userId === body.user_id);
+ const member = accessList.find((a) => a.userId === body.user_id);
if (member?.userEmail) {
await queries.whitelist.addWhitelist(db, id, ws.workspaceId, member.userEmail);
}
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
index 4d7676536..51f78c127 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
@@ -6,7 +6,9 @@ import { withAuth } from "@/lib/middleware/auth"
import { withWorkspaceMember } from "@/lib/middleware/workspace"
import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"
-function accountToResponse(a: any) {
+type AgentEmailAccountRow = Awaited<ReturnType<typeof queries.emailAccount.getEmailAccountsByAgent>>[number]
+
+function accountToResponse(a: AgentEmailAccountRow) {
return {
id: a.id,
agent_id: a.agentId,
@@ -72,7 +74,7 @@ export const PATCH = withAuth(async (req, ctx) => {
if (body.smtpTls !== undefined) data.smtpTls = body.smtpTls
if (body.pollIntervalSeconds !== undefined) data.pollIntervalSeconds = body.pollIntervalSeconds
- const updated = await queries.emailAccount.updateEmailAccount(db, accountId, ws.workspaceId, data as any)
+ const updated = await queries.emailAccount.updateEmailAccount(db, accountId, ws.workspaceId, data)
if (!updated) return writeError("update failed", 500)
const hasCredentialChange = body.imapUsername || body.imapPassword || body.smtpUsername || body.smtpPassword || body.imapHost || body.smtpHost
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.ts
index b127814a4..88ced4982 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/route.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.ts
@@ -6,7 +6,9 @@ import { withAuth } from "@/lib/middleware/auth"
import { withWorkspaceMember } from "@/lib/middleware/workspace"
import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"
-function accountToResponse(a: any) {
+type AgentEmailAccountRow = Awaited<ReturnType<typeof queries.emailAccount.getEmailAccountsByAgent>>[number]
+
+function accountToResponse(a: AgentEmailAccountRow) {
return {
id: a.id,
agent_id: a.agentId,
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts
index 842cdf0dd..372abfa06 100644
--- a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts
@@ -62,7 +62,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const isMultipart = contentType.includes("multipart/form-data");
let content: string;
- let files: File[] = [];
+ const files: File[] = [];
if (isMultipart) {
let formData: FormData;
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index 6f1759780..4060829cb 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -78,7 +78,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const isMultipart = contentType.includes("multipart/form-data");
let content: string;
- let files: File[] = [];
+ const files: File[] = [];
if (isMultipart) {
let formData: FormData;
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
index e595b9d16..ea0689687 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
@@ -67,7 +67,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
)
);
- results.forEach((r, i) => {
+ results.forEach((r) => {
if (r.status === "rejected") {
log.warn("Failed to create task message", { taskId, err: r.reason });
}
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
index d2b406b9e..1c083937c 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -87,7 +87,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);
- let emailAddresses: string[] = [];
+ const emailAddresses: string[] = [];
if (agent) {
if (agent.emailHandle) emailAddresses.push(`${agent.emailHandle}@alook.ai`);
const customAccounts = await queries.emailAccount.getEmailAccountsByAgent(db, agent.id, task.workspaceId);
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index c8c25c72e..2782fb5ed 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -75,7 +75,10 @@ function MentionHighlight(props: Record<string, unknown> & { children?: React.Re
}
const MENTION_COMPONENTS: Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>> = {
mention: MentionHighlight,
- p: ({ children, node: _node, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => <div data-md-p="" {...rest}>{children}</div>,
+ p: ({ children, node, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => {
+ void node;
+ return <div data-md-p="" {...rest}>{children}</div>;
+ },
};
/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
@@ -138,6 +141,14 @@ export function buildTimeline(messages: Message[], artifacts: Artifact[], napMar
});
}
+function useLatest<T>(value: T) {
+ const ref = useRef(value);
+ useEffect(() => {
+ ref.current = value;
+ }, [value]);
+ return ref;
+}
+
function NapSeparator({ agentName }: { agentName: string }) {
return (
<div className="flex items-center gap-3 py-4 select-none" aria-hidden>
@@ -194,7 +205,7 @@ function AttachmentChips({
className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-0.5 text-xs text-primary-foreground/80 hover:bg-primary-foreground/20 transition-colors cursor-pointer"
>
<FileText className="size-3 shrink-0" />
- <span className="truncate max-w-[150px]">{a.filename}</span>
+ <span className="truncate max-w-37.5">{a.filename}</span>
</button>
))}
</div>
@@ -219,7 +230,7 @@ function PendingFileChips({
className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-0.5 text-xs text-primary-foreground/80"
>
<FileText className="size-3 shrink-0" />
- <span className="truncate max-w-[150px]">{f.name}</span>
+ <span className="truncate max-w-37.5">{f.name}</span>
</span>
))}
</div>
@@ -260,8 +271,9 @@ export function AgentChatView() {
const [hasMoreConversations, setHasMoreConversations] = useState(false);
const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);
const [stepCounts, setStepCounts] = useState<Record<string, number>>({});
+ const [renderNow] = useState(() => Date.now());
- const pendingFilesMapRef = useRef<Map<string, File[]>>(new Map());
+ const [pendingFilesByMessage, setPendingFilesByMessage] = useState<Map<string, File[]>>(() => new Map());
const handleSpeechResult = useCallback((text: string) => {
setInput((prev) => (prev ? prev + " " + text : text));
@@ -289,7 +301,10 @@ export function AgentChatView() {
const initialScrollDone = useRef(false);
const loadingMoreRef = useRef(false);
const isNearBottom = useRef(true);
- const startPollingRef = useRef<(taskId: string, conversationId: string, initialSeq?: number) => void>(null!);
+ const startPollingRef = useRef<((taskId: string, conversationId: string, initialSeq?: number) => void) | null>(null);
+ const oldestConversationCursorRef = useRef<PreviousConversation | null>(null);
+ const backfillAttemptsRef = useRef(0);
+ const prevConversationIdRef = useRef<string | undefined>(undefined);
const fileInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -332,18 +347,20 @@ export function AgentChatView() {
if (pollRef.current) clearInterval(pollRef.current);
pollRef.current = null;
pollTaskIdRef.current = null;
- setLoading(true);
- initialScrollDone.current = false;
- setActiveTask(null);
- setTaskMessages([]);
- setBufferedMessages([]);
- setNapMarkers([]);
- setStepCounts({});
- setPreviousConversations([]);
- setHasMoreConversations(false);
- oldestConvIdRef.current = null;
- oldestConvCreatedAtRef.current = null;
- setInput(localStorage.getItem(`chat-draft:${agentId}:${targetConvId ?? 'default'}`) ?? "");
+ queueMicrotask(() => {
+ setLoading(true);
+ initialScrollDone.current = false;
+ setActiveTask(null);
+ setTaskMessages([]);
+ setBufferedMessages([]);
+ setPendingFilesByMessage(new Map());
+ setNapMarkers([]);
+ setStepCounts({});
+ setPreviousConversations([]);
+ setHasMoreConversations(false);
+ oldestConversationCursorRef.current = null;
+ setInput(localStorage.getItem(`chat-draft:${agentId}:${targetConvId ?? 'default'}`) ?? "");
+ });
async function load() {
try {
if (targetConvId && scrollToTaskId) {
@@ -373,7 +390,7 @@ export function AgentChatView() {
if (tmsgs.length > 0) {
lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
}
- startPollingRef.current(task.id, targetConvId, lastSeqRef.current);
+ startPollingRef.current?.(task.id, targetConvId, lastSeqRef.current);
}
} catch {
const data = await chatInit(agentId, workspaceId, activeChannel);
@@ -400,7 +417,7 @@ export function AgentChatView() {
lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));
}
if (!["completed", "failed", "cancelled", "superseded"].includes(data.active_task.status)) {
- startPollingRef.current(data.active_task.id, data.conversation.id, lastSeqRef.current);
+ startPollingRef.current?.(data.active_task.id, data.conversation.id, lastSeqRef.current);
}
}
}
@@ -461,21 +478,12 @@ export function AgentChatView() {
const agentName = useMemo(() => agents.find((a) => a.id === agentId)?.name ?? "Agent", [agents, agentId]);
- const messagesRef = useRef(messages);
- messagesRef.current = messages;
- const hasMoreRef = useRef(hasMore);
- hasMoreRef.current = hasMore;
- const prevConvsRef = useRef(previousConversations);
- prevConvsRef.current = previousConversations;
- const hasMoreConvsRef = useRef(hasMoreConversations);
- hasMoreConvsRef.current = hasMoreConversations;
- const agentNameRef = useRef(agentName);
- agentNameRef.current = agentName;
- const activeChannelRef = useRef(activeChannel);
- activeChannelRef.current = activeChannel;
-
- const oldestConvIdRef = useRef<string | null>(null);
- const oldestConvCreatedAtRef = useRef<string | null>(null);
+ const messagesRef = useLatest(messages);
+ const hasMoreRef = useLatest(hasMore);
+ const prevConvsRef = useLatest(previousConversations);
+ const hasMoreConvsRef = useLatest(hasMoreConversations);
+ const agentNameRef = useLatest(agentName);
+ const activeChannelRef = useLatest(activeChannel);
const loadOlderMessages = useCallback(async (scrollToEnd = false) => {
if (!conversation || loadingMoreRef.current) return;
@@ -488,14 +496,12 @@ export function AgentChatView() {
const currentChannel = activeChannelRef.current;
const oldest = currentMessages[0];
- const paginatingConvId = oldestConvIdRef.current ?? conversation.id;
+ const paginatingConvId = oldestConversationCursorRef.current?.id ?? conversation.id;
const canLoadMoreInConv = currentHasMore && oldest;
let prevConvsList = prevConvsRef.current;
if (!canLoadMoreInConv && prevConvsList.length === 0 && currentHasMoreConvs) {
- const oldestConv = oldestConvCreatedAtRef.current
- ? { id: oldestConvIdRef.current!, created_at: oldestConvCreatedAtRef.current }
- : { id: conversation.id, created_at: conversation.created_at };
+ const oldestConv = oldestConversationCursorRef.current ?? { id: conversation.id, created_at: conversation.created_at };
try {
const result = await listPreviousConversations(agentId, workspaceId, {
exclude: conversation.id,
@@ -555,16 +561,14 @@ export function AgentChatView() {
});
if (older.length === 0) {
- oldestConvIdRef.current = prevConv.id;
- oldestConvCreatedAtRef.current = prevConv.created_at;
+ oldestConversationCursorRef.current = prevConv;
continue;
}
- napTs = oldestConvCreatedAtRef.current ?? conversation.created_at;
+ napTs = oldestConversationCursorRef.current?.created_at ?? conversation.created_at;
napId = `nap-${prevConv.id}`;
loadedOlder = older;
- oldestConvIdRef.current = prevConv.id;
- oldestConvCreatedAtRef.current = prevConv.created_at;
+ oldestConversationCursorRef.current = prevConv;
break;
}
@@ -609,16 +613,25 @@ export function AgentChatView() {
setLoadingMore(false);
if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";
}
- }, [conversation, workspaceId, agentId]);
+ }, [
+ conversation,
+ workspaceId,
+ agentId,
+ messagesRef,
+ hasMoreRef,
+ hasMoreConvsRef,
+ agentNameRef,
+ activeChannelRef,
+ prevConvsRef,
+ ]);
const canLoadMore = hasMore || previousConversations.length > 0 || hasMoreConversations;
- const backfillAttemptsRef = useRef(0);
- const prevConversationIdRef = useRef(conversation?.id);
- if (conversation?.id !== prevConversationIdRef.current) {
+ useEffect(() => {
+ if (conversation?.id === prevConversationIdRef.current) return;
prevConversationIdRef.current = conversation?.id;
backfillAttemptsRef.current = 0;
- }
+ }, [conversation?.id]);
const MIN_MESSAGES = 10;
useEffect(() => {
@@ -723,7 +736,7 @@ export function AgentChatView() {
setMessages((prev) => mergeMessages(prev, latestMsgs));
setActiveTask(nextTask);
setTaskMessages([]);
- startPollingRef.current(nextTask.id, conversationId);
+ startPollingRef.current?.(nextTask.id, conversationId);
}
} catch { }
}, 1000);
@@ -746,7 +759,9 @@ export function AgentChatView() {
},
[workspaceId]
);
- startPollingRef.current = startPolling;
+ useEffect(() => {
+ startPollingRef.current = startPolling;
+ }, [startPolling]);
useEffect(() => {
return () => {
@@ -782,7 +797,7 @@ export function AgentChatView() {
setActiveTask(task);
setTaskMessages([]);
lastSeqRef.current = 0;
- startPollingRef.current(task.id, msg.conversationId);
+ startPollingRef.current?.(task.id, msg.conversationId);
}
if (msg.type === "conversation.message" && msg.conversationId === conversation?.id) {
setMessages((prev) => mergeMessages(prev, [msg.message]));
@@ -806,7 +821,7 @@ export function AgentChatView() {
activeTaskIdRef.current = task.id;
setActiveTask(task);
setTaskMessages([]);
- startPollingRef.current(task.id, msg.conversationId);
+ startPollingRef.current?.(task.id, msg.conversationId);
}
if (msg.type === "followup.created" && msg.conversationId === conversation?.id) {
setBufferedMessages((prev) => addBufferedIfNew(prev, msg.message));
@@ -818,7 +833,7 @@ export function AgentChatView() {
toast.error(msg.error || "Failed to dispatch follow-up");
}
});
- }, [subscribeWs, conversation?.id]);
+ }, [subscribeWs, conversation?.id, workspaceId]);
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const fileList = e.target.files;
@@ -1013,7 +1028,11 @@ export function AgentChatView() {
// Store pending files for the optimistic message rendering
if (filesToSend.length > 0) {
- pendingFilesMapRef.current.set(optimisticId, filesToSend);
+ setPendingFilesByMessage((prev) => {
+ const next = new Map(prev);
+ next.set(optimisticId, filesToSend);
+ return next;
+ });
}
setMessages((prev) => [...prev, optimistic]);
@@ -1027,7 +1046,12 @@ export function AgentChatView() {
filesToSend.length > 0 ? filesToSend : undefined,
);
// Clean up pending files ref
- pendingFilesMapRef.current.delete(optimisticId);
+ setPendingFilesByMessage((prev) => {
+ if (!prev.has(optimisticId)) return prev;
+ const next = new Map(prev);
+ next.delete(optimisticId);
+ return next;
+ });
setMessages((prev) =>
prev.map((m) => (m.id === optimistic.id ? message : m))
);
@@ -1040,7 +1064,12 @@ export function AgentChatView() {
setTaskMessages([]);
startPolling(task.id, conversation.id);
} catch (err) {
- pendingFilesMapRef.current.delete(optimisticId);
+ setPendingFilesByMessage((prev) => {
+ if (!prev.has(optimisticId)) return prev;
+ const next = new Map(prev);
+ next.delete(optimisticId);
+ return next;
+ });
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
setInput(content);
setPendingFiles(filesToSend);
@@ -1094,12 +1123,11 @@ export function AgentChatView() {
setArtifacts([]);
setBufferedMessages([]);
setPendingFiles([]);
- pendingFilesMapRef.current.clear();
+ setPendingFilesByMessage(new Map());
lastSeqRef.current = 0;
setConnectionLost(false);
setHasMore(false);
- oldestConvIdRef.current = null;
- oldestConvCreatedAtRef.current = null;
+ oldestConversationCursorRef.current = null;
scrollToBottom();
} catch {
@@ -1151,7 +1179,7 @@ export function AgentChatView() {
{/* Skeleton input area */}
<div className="px-3 md:px-5 py-3">
<div className="mx-auto max-w-2xl">
- <Skeleton className="h-[72px] w-full rounded-xl" />
+ <Skeleton className="h-18 w-full rounded-xl" />
</div>
</div>
</>
@@ -1199,7 +1227,7 @@ export function AgentChatView() {
{messages.length === 0 && !activeTask && (() => {
const agent = agents.find(a => a.id === agentId);
- const isNewAgent = agent?.created_at && (Date.now() - new Date(agent.created_at).getTime() < 5 * 60 * 1000);
+ const isNewAgent = agent?.created_at && (renderNow - new Date(agent.created_at).getTime() < 5 * 60 * 1000);
const hasEmailTask = (activeTaskCounts[agentId] ?? 0) > 0;
if (isNewAgent && hasEmailTask) {
@@ -1295,7 +1323,7 @@ export function AgentChatView() {
<AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={handleArtifactClick} />
)}
{!msg.attachment_ids && (
- <PendingFileChips pendingFiles={pendingFilesMapRef.current} messageId={msg.id} />
+ <PendingFileChips pendingFiles={pendingFilesByMessage} messageId={msg.id} />
)}
</div>
</div>
@@ -1412,7 +1440,7 @@ export function AgentChatView() {
className={cn(
"relative field-sizing-content w-full resize-none bg-transparent px-3.5 py-2.5 text-base leading-normal outline-none",
"placeholder:text-muted-foreground disabled:cursor-not-allowed",
- "min-h-[38px] max-h-[200px] thin-scrollbar",
+ "min-h-9.5 max-h-50 thin-scrollbar",
"caret-foreground text-transparent"
)}
/>
diff --git a/src/web/src/components/agent-chat/artifact-sheet.tsx b/src/web/src/components/agent-chat/artifact-sheet.tsx
index 147fb9ab6..afc360fbe 100644
--- a/src/web/src/components/agent-chat/artifact-sheet.tsx
+++ b/src/web/src/components/agent-chat/artifact-sheet.tsx
@@ -30,7 +30,6 @@ interface ArtifactSheetProps {
const MIN_WIDTH = 320;
const MAX_WIDTH_RATIO = 0.8;
const DEFAULT_WIDTH = 448;
-const MOBILE_BREAKPOINT = 640;
export function ArtifactSheet({ open, onOpenChange, artifacts, workspaceId, initialArtifact = null }: ArtifactSheetProps) {
const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);
diff --git a/src/web/src/components/agent-chat/mention-popup.tsx b/src/web/src/components/agent-chat/mention-popup.tsx
index b3337671a..6fe3effb7 100644
--- a/src/web/src/components/agent-chat/mention-popup.tsx
+++ b/src/web/src/components/agent-chat/mention-popup.tsx
@@ -30,7 +30,7 @@ export function MentionPopup({ isOpen, agents, selectedIndex, onSelect, anchorPo
transform: "translateY(-100%)",
}}
>
- <div ref={listRef} className="max-h-[200px] overflow-y-auto py-1 thin-scrollbar">
+ <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">
{agents.map((agent, i) => (
<button
key={agent.id}
diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsx
index 08b567767..733456534 100644
--- a/src/web/src/components/agent-edit-form.tsx
+++ b/src/web/src/components/agent-edit-form.tsx
@@ -97,9 +97,13 @@ export function AgentEditForm({
const [instructions, setInstructions] = useState(agent.instructions ?? "");
const [savedInstructions, setSavedInstructions] = useState(agent.instructions ?? "");
const instructionsRef = useRef(instructions);
- instructionsRef.current = instructions;
+ useEffect(() => {
+ instructionsRef.current = instructions;
+ }, [instructions]);
const savedInstructionsRef = useRef(savedInstructions);
- savedInstructionsRef.current = savedInstructions;
+ useEffect(() => {
+ savedInstructionsRef.current = savedInstructions;
+ }, [savedInstructions]);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const savingInstructionsRef = useRef(false);
diff --git a/src/web/src/components/agent-form-fields.tsx b/src/web/src/components/agent-form-fields.tsx
index 56a46a3c8..128b55995 100644
--- a/src/web/src/components/agent-form-fields.tsx
+++ b/src/web/src/components/agent-form-fields.tsx
@@ -22,11 +22,10 @@ import {
DialogClose,
} from "@/components/ui/dialog";
import { RuntimeSelect } from "@/components/runtime-select";
-import type { Agent } from "@alook/shared";
import { isValidHandle } from "@alook/shared";
import type { AgentRuntime as Runtime } from "@alook/shared";
import { cn } from "@/lib/utils";
-import { InfoIcon, LockIcon, XIcon } from "lucide-react";
+import { InfoIcon, XIcon } from "lucide-react";
import { useWorkspace } from "@/contexts/workspace-context";
import {
listWhitelist,
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index 60aede9b5..aafc3aff2 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -20,7 +20,7 @@ import {
} from "@/components/ui/context-menu";
import { AgentPreviewCard } from "@/components/agent-preview-card";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
+import { parseAvatarUrl } from "@/components/avatar";
import { AnimatedAvatar } from "@/components/avatar/animated-avatar";
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
diff --git a/src/web/src/components/avatar/animated-avatar.tsx b/src/web/src/components/avatar/animated-avatar.tsx
index 9b3f47006..88a1a5307 100644
--- a/src/web/src/components/avatar/animated-avatar.tsx
+++ b/src/web/src/components/avatar/animated-avatar.tsx
@@ -41,7 +41,7 @@ export function AnimatedAvatar({ config, size, className, isHovered, isWorking }
} else if (!isWorking) {
setAnimClass(null);
}
- }, [isHovered]);
+ }, [isHovered, isWorking]);
useEffect(() => {
if (!isWorking) {
@@ -53,7 +53,7 @@ export function AnimatedAvatar({ config, size, className, isHovered, isWorking }
setAnimClass(pickAnimation());
}, 4000);
return () => clearInterval(interval);
- }, [isWorking]);
+ }, [isHovered, isWorking]);
return (
<div className={animClass ?? undefined}>
diff --git a/src/web/src/components/avatar/avatar-generator.tsx b/src/web/src/components/avatar/avatar-generator.tsx
index b0d4b1b1c..b09455655 100644
--- a/src/web/src/components/avatar/avatar-generator.tsx
+++ b/src/web/src/components/avatar/avatar-generator.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useEffect, useMemo, useRef } from "react";
+import { useState, useCallback, useEffect, useRef } from "react";
import {
type AvatarConfig,
AvatarRenderer,
@@ -152,17 +152,6 @@ export function AvatarGenerator({ config, onChange, layout = "vertical", mobile
}
}, [config]);
- // Find matched preset name
- const matchedPresetName = useMemo(() => {
- const match = PRESETS.find(
- (p) =>
- p.config.shape === config.shape &&
- p.config.eye === config.eye &&
- p.config.nose === config.nose &&
- p.config.bg === config.bg
- );
- return match?.name ?? null;
- }, [config]);
// Spacebar shortcut for random in horizontal (dialog) mode
useEffect(() => {
@@ -201,7 +190,7 @@ export function AvatarGenerator({ config, onChange, layout = "vertical", mobile
<div className={cn(
"flex flex-col items-center gap-3 rounded-2xl bg-muted/30",
mobile ? "p-3" : "p-4",
- isHorizontal ? "w-[280px] shrink-0 justify-center" : ""
+ isHorizontal ? "w-70 shrink-0 justify-center" : ""
)}>
<div className={cn("rounded-2xl", shaking && "animate-[shake_0.45s_cubic-bezier(.36,.07,.19,.97)]")}>
<AvatarRenderer config={config} size={previewSize} />
@@ -230,7 +219,7 @@ export function AvatarGenerator({ config, onChange, layout = "vertical", mobile
const controls = (
<div className={cn(
"flex flex-col gap-3 flex-1 min-w-0",
- isHorizontal && "rounded-2xl bg-muted/30 p-4 h-[380px]"
+ isHorizontal && "rounded-2xl bg-muted/30 p-4 h-95"
)}>
{/* Tabs */}
<div className="flex border-b border-border">
diff --git a/src/web/src/components/avatar/avatar-parts.tsx b/src/web/src/components/avatar/avatar-parts.tsx
index c278774e8..1c04676cd 100644
--- a/src/web/src/components/avatar/avatar-parts.tsx
+++ b/src/web/src/components/avatar/avatar-parts.tsx
@@ -173,12 +173,16 @@ export interface EyeDef {
render: (dx: number) => ReactNode;
}
-const eye = (l: ReactNode, r: ReactNode = l) => (dx: number) => (
+const eye = (l: ReactNode, r: ReactNode = l) => {
+ const EyePair = (dx: number) => (
<g>
<g transform={`translate(${-dx}, 0)`}>{l}</g>
<g transform={`translate(${dx}, 0)`}>{r}</g>
</g>
-);
+ );
+ EyePair.displayName = "EyePair";
+ return EyePair;
+};
export const Eyes: Record<string, EyeDef> = {
dots: { name: "Dots", render: eye(<circle cx="0" cy="0" r="4.5" {...fp} />) },
diff --git a/src/web/src/components/avatar/avatar-picker-dialog.tsx b/src/web/src/components/avatar/avatar-picker-dialog.tsx
index be5fcdd64..e87b5fffa 100644
--- a/src/web/src/components/avatar/avatar-picker-dialog.tsx
+++ b/src/web/src/components/avatar/avatar-picker-dialog.tsx
@@ -46,7 +46,7 @@ export function AvatarPickerDialog({ config, onChange }: AvatarPickerDialogProps
<DialogContent className={
isMobile
? "top-auto left-0 translate-x-0 translate-y-0 bottom-0 max-w-full sm:max-w-full w-full rounded-b-none rounded-t-xl max-h-[85dvh] overflow-y-auto pb-[env(safe-area-inset-bottom)]"
- : "sm:max-w-[720px]"
+ : "sm:max-w-180"
}>
<DialogHeader>
<DialogTitle>Choose Avatar</DialogTitle>
diff --git a/src/web/src/components/calendar/calendar-agenda.tsx b/src/web/src/components/calendar/calendar-agenda.tsx
index 7750e25c5..7545676c4 100644
--- a/src/web/src/components/calendar/calendar-agenda.tsx
+++ b/src/web/src/components/calendar/calendar-agenda.tsx
@@ -3,7 +3,6 @@
import { cn } from "@/lib/utils";
import type { CalendarEvent, Agent } from "@alook/shared";
import { Skeleton } from "@/components/ui/skeleton";
-import { Video } from "lucide-react";
import { agentColor } from "./calendar-colors";
import { dateKey } from "./calendar-month-grid";
import { formatRepeatDisplay } from "./repeat-interval-utils";
@@ -138,9 +137,6 @@ export function CalendarAgenda({
{agentNameById.get(ev.agent_id) ?? ev.agent_id}
</span>
<span className="flex-1 truncate text-sm">{ev.title}</span>
- {(ev as any)._type === "meeting" && (
- <Video className="shrink-0 size-3 text-muted-foreground" />
- )}
{ev.repeat_interval && (
<span className="shrink-0 text-[10px] text-muted-foreground">
{formatRepeatDisplay(ev.repeat_interval!)}
diff --git a/src/web/src/components/calendar/calendar-event-sheet.tsx b/src/web/src/components/calendar/calendar-event-sheet.tsx
index 4df44114e..8808144fa 100644
--- a/src/web/src/components/calendar/calendar-event-sheet.tsx
+++ b/src/web/src/components/calendar/calendar-event-sheet.tsx
@@ -22,7 +22,6 @@ import { MarkdownEditor } from "@/components/ui/markdown-editor";
import {
CalendarDays,
CalendarOff,
- Clock,
Repeat as RepeatIcon,
User,
X,
diff --git a/src/web/src/components/calendar/calendar-week-grid.tsx b/src/web/src/components/calendar/calendar-week-grid.tsx
index c51c3cb70..0b2efc3bc 100644
--- a/src/web/src/components/calendar/calendar-week-grid.tsx
+++ b/src/web/src/components/calendar/calendar-week-grid.tsx
@@ -96,7 +96,7 @@ export function CalendarWeekGrid({
arr.push(d);
}
return arr;
- }, [weekStart.getTime()]);
+ }, [weekStart]);
const eventsByDay = useMemo(() => {
const map = new Map<string, CalendarEvent[]>();
@@ -320,7 +320,7 @@ export function CalendarWeekGrid({
style={{ top: currentFractionalHour * HOUR_HEIGHT }}
>
<div className="h-px bg-foreground/40" />
- <div className="absolute -left-0.5 -top-[3px] size-[7px] rounded-full bg-foreground/40" />
+ <div className="absolute -left-0.5 -top-0.75 size-1.75 rounded-full bg-foreground/40" />
</div>
)}
diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsx
index 8c4de7751..d6350a32f 100644
--- a/src/web/src/components/canvas/active-tasks-float.tsx
+++ b/src/web/src/components/canvas/active-tasks-float.tsx
@@ -115,7 +115,7 @@ export function ActiveTasksFloat() {
<div
role="region"
aria-label="Active tasks"
- className="absolute bottom-4 right-4 z-10 w-[320px] rounded-lg ring-1 ring-foreground/8 shadow-sm bg-background/90 backdrop-blur-sm animate-[fade-up_300ms_ease-out_both]"
+ className="absolute bottom-4 right-4 z-10 w-80 rounded-lg ring-1 ring-foreground/8 shadow-sm bg-background/90 backdrop-blur-sm animate-[fade-up_300ms_ease-out_both]"
>
<div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
<div className="flex items-center gap-2 text-sm font-medium" aria-live="polite">
@@ -145,7 +145,7 @@ export function ActiveTasksFloat() {
</div>
{!minimized && (
- <div className="max-h-[300px] overflow-y-auto thin-scrollbar py-1">
+ <div className="max-h-75 overflow-y-auto thin-scrollbar py-1">
{tasks.slice(0, 8).map((task) => (
<TaskRow key={task.id} task={task} slug={slug} />
))}
diff --git a/src/web/src/components/canvas/link-sidecar.tsx b/src/web/src/components/canvas/link-sidecar.tsx
index 78854689c..375117854 100644
--- a/src/web/src/components/canvas/link-sidecar.tsx
+++ b/src/web/src/components/canvas/link-sidecar.tsx
@@ -38,11 +38,15 @@ export function LinkSidecar({
const [confirmOpen, setConfirmOpen] = useState(false);
const instructionRef = useRef(instruction);
- instructionRef.current = instruction;
+ useEffect(() => {
+ instructionRef.current = instruction;
+ }, [instruction]);
const savedInstructionRef = useRef("");
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const linkRef = useRef(link);
- linkRef.current = link;
+ useEffect(() => {
+ linkRef.current = link;
+ }, [link]);
const sourceAgent = agents.find((a) => a.id === link?.source_agent_id);
const targetAgent = agents.find((a) => a.id === link?.target_agent_id);
diff --git a/src/web/src/components/channel-bar.tsx b/src/web/src/components/channel-bar.tsx
index 00ee1a1ce..a636c153f 100644
--- a/src/web/src/components/channel-bar.tsx
+++ b/src/web/src/components/channel-bar.tsx
@@ -120,7 +120,6 @@ export function ChannelBar() {
}
function ChannelPill({
- id,
name,
active,
deleting,
diff --git a/src/web/src/components/custom-email-form.tsx b/src/web/src/components/custom-email-form.tsx
index 9e7e79291..4eb8fac25 100644
--- a/src/web/src/components/custom-email-form.tsx
+++ b/src/web/src/components/custom-email-form.tsx
@@ -20,7 +20,7 @@ import {
} from "@/lib/api";
import type { AgentEmailAccount, CreateEmailAccountRequest } from "@alook/shared";
import {
- Loader2, Mail, RefreshCw, Trash2, AlertCircle, CheckCircle2,
+ Loader2, Mail, RefreshCw, AlertCircle, CheckCircle2,
ChevronRight, XIcon, CircleHelp,
} from "lucide-react";
import { toast } from "sonner";
@@ -235,6 +235,8 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
onDataChange?.(buildData());
}, [
isCreateMode,
+ buildData,
+ onDataChange,
fields.emailAddress, fields.displayName,
fields.imapHost, fields.imapPort, fields.imapUsername, fields.imapPassword,
fields.smtpHost, fields.smtpPort, fields.smtpUsername, fields.smtpPassword,
@@ -278,8 +280,8 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
toast.success("Custom email configured");
setOpen(false);
await load();
- } catch (err: any) {
- toast.error(err?.message ?? "Failed to save");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to save");
} finally {
setSaving(false);
}
@@ -292,8 +294,8 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
await deleteEmailAccount(agentId, existing.id, workspaceId);
toast.success("Custom email removed");
setAccounts([]);
- } catch (err: any) {
- toast.error(err?.message ?? "Failed to remove");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to remove");
} finally {
setDeleting(false);
}
@@ -306,8 +308,8 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
await syncEmailAccount(agentId, existing.id, workspaceId);
toast.success("Sync triggered");
setTimeout(() => load(), 2000);
- } catch (err: any) {
- toast.error(err?.message ?? "Sync failed");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Sync failed");
} finally {
setSyncing(false);
}
diff --git a/src/web/src/components/dashboard-navbar.tsx b/src/web/src/components/dashboard-navbar.tsx
index 02edd7603..2c2047676 100644
--- a/src/web/src/components/dashboard-navbar.tsx
+++ b/src/web/src/components/dashboard-navbar.tsx
@@ -1,7 +1,6 @@
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
-import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
@@ -137,7 +136,6 @@ function OnboardingSteps({
}
export function DashboardNavbar() {
- const router = useRouter();
const [runtimes, setRuntimes] = useState<Runtime[]>([]);
const [runtimeSheetOpen, setRuntimeSheetOpen] = useState(false);
const [generatedToken, setGeneratedToken] = useState("");
diff --git a/src/web/src/components/email-compose.tsx b/src/web/src/components/email-compose.tsx
index 5b71e48ba..82288abc8 100644
--- a/src/web/src/components/email-compose.tsx
+++ b/src/web/src/components/email-compose.tsx
@@ -80,7 +80,7 @@ export function EmailCompose({
],
editorProps: {
attributes: {
- class: "text-sm max-w-none focus:outline-none min-h-[200px] px-4 py-3",
+ class: "text-sm max-w-none focus:outline-none min-h-50 px-4 py-3",
},
},
});
@@ -229,7 +229,7 @@ export function EmailCompose({
className="flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs"
>
<FileIcon className="size-3 text-muted-foreground shrink-0" />
- <span className="truncate max-w-[150px]">{att.filename}</span>
+ <span className="truncate max-w-37.5">{att.filename}</span>
<span className="text-muted-foreground shrink-0">{formatFileSize(att.size)}</span>
<button
type="button"
diff --git a/src/web/src/components/email-toolbar.tsx b/src/web/src/components/email-toolbar.tsx
index 4bef29882..9d4995378 100644
--- a/src/web/src/components/email-toolbar.tsx
+++ b/src/web/src/components/email-toolbar.tsx
@@ -14,7 +14,7 @@ import {
AlignRight,
Link,
Unlink,
- Image,
+ ImageIcon,
Heading1,
Heading2,
Minus,
@@ -191,7 +191,7 @@ export function EmailToolbar({ editor }: EmailToolbarProps) {
)}
</ToolbarButton>
<ToolbarButton title="Insert Image" onClick={handleImage}>
- <Image className={iconSize} />
+ <ImageIcon className={iconSize} />
</ToolbarButton>
<ToolbarDivider />
diff --git a/src/web/src/components/home/feature-showcase.tsx b/src/web/src/components/home/feature-showcase.tsx
index 5ad41fd35..312c17a0a 100644
--- a/src/web/src/components/home/feature-showcase.tsx
+++ b/src/web/src/components/home/feature-showcase.tsx
@@ -272,7 +272,7 @@ function FeaturePanel({ feature, reversed }: { feature: Feature; reversed: boole
}}
/>
{/* ASCII art */}
- <div className="relative z-20 flex items-center justify-center min-h-[140px]">
+ <div className="relative z-20 flex items-center justify-center min-h-35">
<AnimatedArt lines={feature.terminal} />
</div>
</div>
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index f1a20f16e..4252c72fb 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -101,7 +101,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
</div>
{/* Typewriter + Slogan wrapper */}
- <div className="relative w-full h-[420px] sm:h-[500px] md:h-[570px]">
+ <div className="relative w-full h-105 sm:h-125 md:h-142.5">
{/* Slogan — positioned at top of typewriter area */}
<div className="absolute top-0 left-0 right-0 z-10 flex flex-col items-center pt-2">
<h1
diff --git a/src/web/src/components/theme-script.tsx b/src/web/src/components/theme-script.tsx
index ba6b9e665..1bb759ac6 100644
--- a/src/web/src/components/theme-script.tsx
+++ b/src/web/src/components/theme-script.tsx
@@ -5,6 +5,7 @@ const themeScript = `(function(){try{var s=localStorage.getItem('theme');var d=s
export function ThemeScript() {
return (
<Script
+ id="theme-script"
strategy="beforeInteractive"
dangerouslySetInnerHTML={{ __html: themeScript }}
/>
diff --git a/src/web/src/components/typewriter-visual.tsx b/src/web/src/components/typewriter-visual.tsx
index 777b348d5..ba7c0f230 100644
--- a/src/web/src/components/typewriter-visual.tsx
+++ b/src/web/src/components/typewriter-visual.tsx
@@ -154,7 +154,6 @@ interface Birthday {
function BirthdayPicker({
value,
onSave,
- onClear,
}: {
value: Birthday | null;
onSave: (v: Birthday) => void;
diff --git a/src/web/src/components/ui/checkbox.tsx b/src/web/src/components/ui/checkbox.tsx
index 4fcd84785..441414c15 100644
--- a/src/web/src/components/ui/checkbox.tsx
+++ b/src/web/src/components/ui/checkbox.tsx
@@ -10,7 +10,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
- "peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
+ "peer relative flex size-4 shrink-0 items-center justify-center rounded-lg border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
className
)}
{...props}
diff --git a/src/web/src/components/ui/dropdown-menu.tsx b/src/web/src/components/ui/dropdown-menu.tsx
index 9d5ebbd2c..5f075a3c3 100644
--- a/src/web/src/components/ui/dropdown-menu.tsx
+++ b/src/web/src/components/ui/dropdown-menu.tsx
@@ -135,7 +135,7 @@ function DropdownMenuSubContent({
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
- className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
+ className={cn("w-auto min-w-24 rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
align={align}
alignOffset={alignOffset}
side={side}
diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsx
index c625dbb43..6a4551ece 100644
--- a/src/web/src/components/ui/markdown-editor.tsx
+++ b/src/web/src/components/ui/markdown-editor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState, useCallback, useRef } from "react";
+import { useEffect, useState, useRef } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
@@ -30,6 +30,12 @@ function normalize(html: string | null | undefined): string {
return isEmptyHtml(html) ? "" : html.trim();
}
+type MentionSuggestionProps = {
+ items: Agent[];
+ command: (props: { id: string; label: string }) => void;
+ decorationNode: Element | null;
+};
+
interface PopupState {
items: Agent[];
selectedIndex: number;
@@ -61,7 +67,7 @@ function MentionList({
className="fixed z-[100] w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
style={{ top: rect.top - 4, left: rect.left, transform: "translateY(-100%)" }}
>
- <div ref={listRef} className="max-h-[200px] overflow-y-auto py-1 thin-scrollbar">
+ <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">
{items.map((agent, i) => (
<button
key={agent.id}
@@ -93,7 +99,9 @@ function useMentionSuggestion(agents: Agent[] | undefined) {
const [popup, setPopup] = useState<PopupState>({ items: [], selectedIndex: 0, command: null });
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const popupRef = useRef(popup);
- popupRef.current = popup;
+ useEffect(() => {
+ popupRef.current = popup;
+ }, [popup]);
const mentionExt = agents && agents.length > 0
? Mention.configure({
@@ -115,12 +123,12 @@ function useMentionSuggestion(agents: Agent[] | undefined) {
return [...sw, ...inc].slice(0, 20);
},
render: () => ({
- onStart: (props: any) => {
- setAnchorEl(props.decorationNode ?? null);
+ onStart: (props: MentionSuggestionProps) => {
+ setAnchorEl(props.decorationNode instanceof HTMLElement ? props.decorationNode : null);
setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
},
- onUpdate: (props: any) => {
- setAnchorEl(props.decorationNode ?? null);
+ onUpdate: (props: MentionSuggestionProps) => {
+ setAnchorEl(props.decorationNode instanceof HTMLElement ? props.decorationNode : null);
setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
},
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
diff --git a/src/web/src/components/ui/sheet.tsx b/src/web/src/components/ui/sheet.tsx
index f6664bfe3..33d799151 100644
--- a/src/web/src/components/ui/sheet.tsx
+++ b/src/web/src/components/ui/sheet.tsx
@@ -54,10 +54,10 @@ function SheetContent({
data-side={side}
className={cn(
"fixed z-50 flex flex-col bg-background shadow-xl outline-none transition duration-300 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0",
- "data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-full data-[side=right]:max-w-md data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem]",
- "data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-full data-[side=left]:max-w-md data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem]",
- "data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem]",
- "data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem]",
+ "data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-full data-[side=right]:max-w-md data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-10 data-[side=right]:data-starting-style:translate-x-10",
+ "data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-full data-[side=left]:max-w-md data-[side=left]:border-r data-[side=left]:data-ending-style:-translate-x-10 data-[side=left]:data-starting-style:-translate-x-10",
+ "data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:-translate-y-10 data-[side=top]:data-starting-style:-translate-y-10",
+ "data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-10 data-[side=bottom]:data-starting-style:translate-y-10",
className
)}
{...props}
diff --git a/src/web/src/components/ui/switch.tsx b/src/web/src/components/ui/switch.tsx
index 9b8b44b1d..abd326050 100644
--- a/src/web/src/components/ui/switch.tsx
+++ b/src/web/src/components/ui/switch.tsx
@@ -16,7 +16,7 @@ function Switch({
data-slot="switch"
data-size={size}
className={cn(
- "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
+ "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
className
)}
{...props}
diff --git a/src/web/src/components/ui/tabs.tsx b/src/web/src/components/ui/tabs.tsx
index 4e801af6e..d74d736ad 100644
--- a/src/web/src/components/ui/tabs.tsx
+++ b/src/web/src/components/ui/tabs.tsx
@@ -24,7 +24,7 @@ function Tabs({
}
const tabsListVariants = cva(
- "group/tabs-list inline-flex max-w-full overflow-x-auto overflow-y-hidden items-center justify-start rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
+ "group/tabs-list inline-flex max-w-full overflow-x-auto overflow-y-hidden items-center justify-start rounded-lg p-0.75 text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsx
index 57fded78f..59eb11412 100644
--- a/src/web/src/contexts/agent-context.tsx
+++ b/src/web/src/contexts/agent-context.tsx
@@ -24,7 +24,6 @@ import {
unpinAgent as unpinAgentApi,
reorderAgentPins,
reorderUnpinnedAgents,
- type AgentPin,
type WorkspaceActiveTask,
} from "@/lib/api";
import type { AgentRuntime as Runtime } from "@alook/shared";
diff --git a/src/web/src/instrumentation.ts b/src/web/src/instrumentation.ts
index d619bbd0e..e105935bd 100644
--- a/src/web/src/instrumentation.ts
+++ b/src/web/src/instrumentation.ts
@@ -23,9 +23,9 @@ export function register() {
): boolean => {
const str = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString()
if (REQUEST_LOG_RE.test(str)) {
- return (origWrite as Function)(`${timestamp()}${str}`, ...rest)
+ return (origWrite as (chunk: Uint8Array | string, ...args: unknown[]) => boolean)(`${timestamp()}${str}`, ...rest)
}
- return (origWrite as Function)(chunk, ...rest)
+ return (origWrite as (chunk: Uint8Array | string, ...args: unknown[]) => boolean)(chunk, ...rest)
}
}
} catch {
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index ff7e8719d..b2eada148 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -13,13 +13,18 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
const onMessageRef = useRef(onMessage)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Keep the ref in sync with the latest callback on every render
- onMessageRef.current = onMessage
+ useEffect(() => {
+ onMessageRef.current = onMessage
+ }, [onMessage])
+
+ const connectRef = useRef<(() => Promise<void>) | null>(null)
- const scheduleReconnect = useCallback((connect: () => void) => {
+ const scheduleReconnect = useCallback(() => {
const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
- reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)
+ reconnectTimerRef.current = setTimeout(() => {
+ void connectRef.current?.()
+ }, delay + Math.random() * 500)
}, [])
const connect = useCallback(async () => {
@@ -29,7 +34,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
const res = await fetch("/api/ws/token")
if (!res.ok) {
console.warn("[ws] token fetch failed:", res.status)
- scheduleReconnect(connect)
+ scheduleReconnect()
return
}
const body = await res.json() as { userId: string; token: string }
@@ -37,7 +42,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
authToken = body.token
} catch (err) {
console.warn("[ws] token fetch error:", err)
- scheduleReconnect(connect)
+ scheduleReconnect()
return
}
@@ -50,7 +55,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
ws = new WebSocket(url)
} catch (err) {
console.warn("[ws] WebSocket creation failed:", err)
- scheduleReconnect(connect)
+ scheduleReconnect()
return
}
wsRef.current = ws
@@ -74,10 +79,14 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
// Ownership check: only reconnect if this WS is still the current one.
// If effect cleanup already replaced wsRef.current, this is an orphan — skip.
if (ws !== wsRef.current) return
- scheduleReconnect(connect)
+ scheduleReconnect()
}
}, [scheduleReconnect])
+ useEffect(() => {
+ connectRef.current = connect
+ }, [connect])
+
useEffect(() => {
connect()
return () => {
diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.ts
index e0a55a8cf..d627b2d03 100644
--- a/src/web/src/lib/use-ws.ts
+++ b/src/web/src/lib/use-ws.ts
@@ -13,8 +13,11 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
const onMessageRef = useRef(onMessage)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Keep the ref in sync with the latest callback on every render
- onMessageRef.current = onMessage
+ useEffect(() => {
+ onMessageRef.current = onMessage
+ }, [onMessage])
+
+ const connectRef = useRef<(() => Promise<void>) | null>(null)
const connect = useCallback(async () => {
// Unified dev/prod flow — see use-user-ws.ts for rationale.
@@ -64,10 +67,16 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
- reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)
+ reconnectTimerRef.current = setTimeout(() => {
+ void connectRef.current?.()
+ }, delay + Math.random() * 500)
}
}, [agentId])
+ useEffect(() => {
+ connectRef.current = connect
+ }, [connect])
+
useEffect(() => {
connect()
return () => {
diff --git a/src/web/src/test/e2e/buffered-messages.test.ts b/src/web/src/test/e2e/buffered-messages.test.ts
index bc3d3b1d0..f86c26d26 100644
--- a/src/web/src/test/e2e/buffered-messages.test.ts
+++ b/src/web/src/test/e2e/buffered-messages.test.ts
@@ -5,6 +5,7 @@ import { sql, sqlQuery } from "../helpers/db"
let seed: TestSeed
let conversationId: string
+let activeTaskId: string
beforeAll(async () => {
seed = seedTestData()
@@ -20,6 +21,12 @@ beforeAll(async () => {
)
const data = await res.json() as { id: string }
conversationId = data.id
+
+ activeTaskId = `task_${Date.now()}`
+ const now = new Date().toISOString()
+ sql(
+ `INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, created_at) VALUES ('${activeTaskId}', '${seed.agentId}', '${seed.runtimeId}', '${seed.workspaceId}', '${conversationId}', 'active task', 'running', 'user_dm_message', '${now}')`
+ )
})
afterAll(() => cleanupTestData(seed))