Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions apps/desktop/src/components/layout/recent-chats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { AgentAvatar, colorGradient } from "@/components/common";
import { useArchiveChat, useDeleteChat } from "@/components/chat/chat-actions";
import { followupWhen } from "@/components/chat/followup";
import { api } from "@/lib/api";
import { useAllAgents, useConversations, useWorkspaces } from "@/lib/hooks";
import { useAllAgents, useScopeWorkspace, useScopedConversations, useWorkspaces } from "@/lib/hooks";
import { qk } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
import { useLive } from "@/stores/live";
Expand All @@ -29,10 +29,13 @@ const ROW_ACTION =
"top-1/2! size-6 -translate-y-1/2 text-muted-foreground after:inset-x-0 hover:bg-background hover:text-foreground hover:shadow-card [&>svg]:size-3.5";

export function RecentChats() {
const { data: conversations = [] } = useConversations();
const scope = useUi((s) => s.workspace);
const scopeWorkspace = useScopeWorkspace();
const scopeName = scope === "all" ? null : scope === "global" ? "Global" : (scopeWorkspace?.name ?? null);
const { data: conversations = [] } = useScopedConversations();
const { data: hasArchived = false } = useQuery({
queryKey: [...qk.conversationsAll, "has-archived"],
queryFn: async () => (await api.conversations.list({ archived: true, limit: 1 })).length > 0,
queryKey: [...qk.conversationsAll, "has-archived", scope],
queryFn: async () => (await api.conversations.list({ archived: true, limit: 1, workspaceId: scope })).length > 0,
});
const { data: agents = [] } = useAllAgents();
const { data: workspaces = [] } = useWorkspaces();
Expand Down Expand Up @@ -65,15 +68,17 @@ export function RecentChats() {
)
.slice(0, 30);

if (visible.length === 0 && !hasArchived) return deleteDialog;
if (visible.length === 0 && !hasArchived && !scopeName) return deleteDialog;

return (
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel className="eyebrow text-[10.5px]">Recent</SidebarGroupLabel>
{visible.some((c) => c.unread) && (
<button
type="button"
onClick={() => void api.conversations.read("all").catch(() => undefined)}
onClick={() =>
void api.conversations.read(scope === "all" ? "all" : visible.flatMap((c) => (c.unread ? [c.id] : []))).catch(() => undefined)
}
className="absolute top-3.5 right-3 text-[11px] text-muted-foreground transition hover:text-foreground"
>
Mark all read
Expand All @@ -82,11 +87,11 @@ export function RecentChats() {
<RecentTabs value={recentTab} onChange={setRecentTab} counts={counts} needsYou={needsYou} />
<SidebarGroupContent id="recent-chats-panel" role="tabpanel" aria-labelledby={`recent-tab-${recentTab}`}>
<SidebarMenu>
{items.length === 0 && <EmptyTab tab={recentTab} />}
{items.length === 0 && <EmptyTab tab={recentTab} scopeName={scopeName} hasArchived={hasArchived} />}
{items.map((c) => {
const agent = agents.find((a) => a.id === c.agentId);
const workspaceId = c.workspaceId ?? agent?.workspaceId;
const workspace = workspaceId ? workspaces.find((w) => w.id === workspaceId) : undefined;
const workspace = scope === "all" && workspaceId ? workspaces.find((w) => w.id === workspaceId) : undefined;
const running = runningConversations.has(c.id) || (c.running && !queuedConversations.has(c.id));
const queued = !running && queuedConversations.has(c.id);
return (
Expand Down Expand Up @@ -350,8 +355,11 @@ const EMPTY: Record<RecentTab, { icon: typeof Zap; title: string; text: string }
done: { icon: CircleCheck, title: "Nothing finished yet", text: "Finished chats land here." },
};

function EmptyTab({ tab }: { tab: RecentTab }) {
const { icon: Icon, title, text } = EMPTY[tab];
function EmptyTab({ tab, scopeName, hasArchived }: { tab: RecentTab; scopeName: string | null; hasArchived: boolean }) {
const { icon: Icon, title, text } =
tab === "all" && scopeName
? { ...EMPTY.all, title: `No chats in ${scopeName} yet`, text: hasArchived ? "Its archived chats are below." : "New chats you start here land in this list." }
: EMPTY[tab];
return (
<li className="flex flex-col items-center gap-1 rounded-lg border border-dashed px-4 py-5 text-center">
<Icon className="mb-0.5 size-4 text-muted-foreground/70" aria-hidden />
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ export const api = {
conversations: {
/** The human has seen these chats ("all" = every chat). */
read: (ids: string[] | "all") => post<{ read: number }>("/api/conversations/read", { ids }),
list: (q: { agentId?: string; search?: string; limit?: number; archived?: boolean } = {}) =>
list: (q: { agentId?: string; workspaceId?: ScopeFilter; search?: string; limit?: number; archived?: boolean } = {}) =>
get<Conversation[]>("/api/conversations", q),
get: (id: string) => get<ConversationWithMessages>(`/api/conversations/${id}`),
create: (input: { agentId: string; title?: string; workspaceId?: string | null }) => post<Conversation>("/api/conversations", input),
Expand Down
27 changes: 21 additions & 6 deletions apps/desktop/src/lib/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,32 @@ export function useAgent(id: string | undefined) {
return useQuery({ queryKey: qk.agent(id ?? ""), queryFn: () => api.agents.get(id!), enabled: !!id });
}

export function useConversations(agentId?: string, search = "") {
export function useConversations(agentId?: string, search = "", workspaceId: ScopeFilter = "all") {
return useQuery({
queryKey: qk.conversations(agentId ?? "all", search),
queryFn: () => api.conversations.list({ agentId, search, limit: 100 }),
queryKey: qk.conversations(agentId ?? "all", search, workspaceId),
queryFn: () => api.conversations.list({ agentId, search, limit: 100, workspaceId }),
});
}

export function useArchivedConversations(agentId?: string, search = "", { enabled = true, limit = 200 } = {}) {
/** Chats of the workspace picked in the sidebar. */
export function useScopedConversations() {
return useConversations(undefined, "", useUi((s) => s.workspace));
}

/** Whether a run belongs to the workspace picked in the sidebar: its chat is listed there, or its agent works there. */
export function useInScope() {
const scope = useUi((s) => s.workspace);
const { data: conversations } = useScopedConversations();
const { data: agents } = useAllAgents();
const ids = new Set(conversations?.map((c) => c.id));
return ({ conversationId, agentId }: { conversationId: string; agentId: string }) =>
scope === "all" || ids.has(conversationId) || (scope !== "global" && agents?.find((a) => a.id === agentId)?.workspaceId === scope);
}

export function useArchivedConversations(agentId?: string, search = "", { enabled = true, limit = 200, workspaceId = "all" } = {}) {
return useQuery({
queryKey: [...qk.archivedConversations(agentId ?? "all", search), limit],
queryFn: () => api.conversations.list({ agentId, search, limit, archived: true }),
queryKey: [...qk.archivedConversations(agentId ?? "all", search, workspaceId), limit],
queryFn: () => api.conversations.list({ agentId, search, limit, archived: true, workspaceId }),
enabled,
});
}
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/lib/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ export const qk = {
automationEventList: (routineId: string, limit: number) => ["automation-events", "list", routineId, limit],
conversationsAll: ["conversations"] as unknown[],
conversationLists: ["conversations", "list"] as unknown[],
conversations: (agentId: string, search: string) => ["conversations", "list", agentId, search],
conversations: (agentId: string, search: string, workspace: string = "all") => ["conversations", "list", agentId, search, workspace],
archivedConversationLists: ["conversations", "archived"] as unknown[],
archivedConversations: (agentId: string, search: string) => ["conversations", "archived", agentId, search],
archivedConversations: (agentId: string, search: string, workspace: string = "all") => ["conversations", "archived", agentId, search, workspace],
conversation: (id: string) => ["conversations", "detail", id],
/** Times agents set to continue their chats on their own. */
followups: ["followups"] as unknown[],
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/pages/chat/archived-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { useDebouncedValue } from "@/components/vault/use-debounced-value";
import { errorMessage } from "@/lib/api";
import { useAllAgents, useArchivedConversations } from "@/lib/hooks";
import { useUi } from "@/stores/ui";

const LIMIT = 200;

Expand All @@ -30,7 +31,8 @@ export default function ArchivedPage() {
const [search, setSearch] = useState("");
const [agentFilter, setAgentFilter] = useState("all");
const q = useDebouncedValue(search.trim());
const archived = useArchivedConversations(agentFilter === "all" ? undefined : agentFilter, q, { limit: LIMIT });
const scope = useUi((s) => s.workspace);
const archived = useArchivedConversations(agentFilter === "all" ? undefined : agentFilter, q, { limit: LIMIT, workspaceId: scope });
const { data: agents = [] } = useAllAgents();
const agentById = useMemo(() => new Map(agents.map((a) => [a.id, a])), [agents]);
const { setArchived } = useArchiveChat();
Expand Down
11 changes: 6 additions & 5 deletions apps/desktop/src/pages/chat/chat-home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { VoiceMode } from "@/components/chat/voice-mode";
import { formatElapsed } from "@/components/runs/run-status";
import { api, errorMessage, isLicenseRequired } from "@/lib/api";
import { qk } from "@/lib/queryKeys";
import { useAllAgents, useBootstrap, useConversations, useRunners, useScopeWorkspace, useWorkspaces, useAttention } from "@/lib/hooks";
import { useAllAgents, useBootstrap, useInScope, useRunners, useScopedConversations, useScopeWorkspace, useWorkspaces, useAttention } from "@/lib/hooks";
import { modKey } from "@/lib/desktop";
import { useVoiceSession } from "@/lib/voice";
import { useDraft } from "@/lib/drafts";
Expand Down Expand Up @@ -334,9 +334,10 @@ function NeedsYou({ agents }: { agents: Agent[] }) {
}

function RunningNow({ agents }: { agents: Agent[] }) {
const runs = useLive((s) => s.runs);
const list = Object.values(runs).filter((r) => r.status === "running");
const queued = Object.values(runs).length - list.length;
const inScope = useInScope();
const runs = Object.values(useLive((s) => s.runs)).filter(inScope);
const list = runs.filter((r) => r.status === "running");
const queued = runs.length - list.length;
if (list.length === 0) return null;
return (
<section aria-label="Working now">
Expand Down Expand Up @@ -381,7 +382,7 @@ function RunningCard({ run, agent, index }: { run: LiveRun; agent?: Agent; index
}

function RecentChats({ agents }: { agents: Agent[] }) {
const { data: conversations = [], isLoading } = useConversations();
const { data: conversations = [], isLoading } = useScopedConversations();
const liveRuns = useLive((s) => s.runs);
const running = useMemo(() => new Set(Object.values(liveRuns).flatMap((r) => (r.status === "running" ? [r.conversationId] : []))), [liveRuns]);
const recent = useMemo(
Expand Down
5 changes: 2 additions & 3 deletions apps/mobile/src/app/(tabs)/(home)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ import { reconnectNow } from "@/lib/realtime";
import { isLive, useLiveScreens } from "@/lib/screens";
import { useSession } from "@/lib/session";
import { usePullRefresh } from "@/lib/use-pull-refresh";
import { useWorkspace } from "@/lib/workspace";
import { useWorkspace, useWorkspaceRuns } from "@/lib/workspace";
import { radius, space, useColors } from "@/lib/theme";

export default function Home() {
const c = useColors();
const computer = useSession((s) => s.connection?.instance.name ?? "Your computer");
const status = useLive((s) => s.status);
const offlineReason = useLive((s) => s.offlineReason);
const runs = useLive((s) => s.runs);
const { byId: agents } = useAgents();
const boot = useQuery({ queryKey: qk.bootstrap, queryFn: api.bootstrap });
const { id: workspaceId, workspace } = useWorkspace();
Expand All @@ -41,7 +40,7 @@ export default function Home() {
await queryClient.invalidateQueries();
});

const working = Object.values(runs).sort((a, b) => (a.run.createdAt < b.run.createdAt ? 1 : -1));
const working = useWorkspaceRuns();
const liveScreens = screens.filter(isLive);
const runningConversations = new Set(working.map((w) => w.run.conversationId));
const chats = (recent.data ?? []).filter((conv) => conv.origin !== "dream").slice(0, 5);
Expand Down
4 changes: 2 additions & 2 deletions apps/mobile/src/components/live-accessory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import { useLive } from "@/lib/live";
import { qk } from "@/lib/query";
import { reconnectNow } from "@/lib/realtime";
import { useSession } from "@/lib/session";
import { useWorkspaceRuns } from "@/lib/workspace";
import { space, useColors } from "@/lib/theme";

/** Floats above the tab bar: what the agents are doing right now, or that the computer can't be reached. */
export function LiveAccessory() {
const placement = NativeTabs.BottomAccessory.usePlacement();
const c = useColors();
const runs = useLive((s) => s.runs);
const offline = useLive((s) => s.status === "offline");
const computer = useSession((s) => s.connection?.instance.name ?? "your computer");
const { data: agents } = useQuery({ queryKey: qk.agents, queryFn: api.agents.list });
const list = Object.values(runs).sort((a, b) => (a.run.createdAt < b.run.createdAt ? 1 : -1));
const list = useWorkspaceRuns();
const first = list[0];
const agent = first ? agents?.find((a) => a.id === first.run.agentId) : undefined;
const inline = placement === "inline";
Expand Down
20 changes: 20 additions & 0 deletions apps/mobile/src/lib/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useEffect, useMemo } from "react";
import { create } from "zustand";
import type { Agent, Workspace } from "@godmode/shared";
import { api } from "./api";
import { useAgents } from "./hooks";
import { type LiveRun, useLive } from "./live";
import { qk } from "./query";

const KEY = "godmode.workspace";
Expand Down Expand Up @@ -58,3 +60,21 @@ export function agentsFor(agents: Agent[], workspaceId: string | null): Agent[]
if (!workspaceId) return agents;
return [...agents.filter((a) => a.workspaceId === workspaceId), ...agents.filter((a) => !a.workspaceId)];
}

/** Live runs of the picked workspace, newest first: its chats', and its agents' anywhere. All runs when none is picked. */
export function useWorkspaceRuns(): LiveRun[] {
const { id } = useWorkspace();
const runs = useLive((s) => s.runs);
const { byId } = useAgents();
const chats = useQuery({
queryKey: qk.conversationList("", id),
queryFn: () => api.conversations.list({ limit: 100, workspaceId: id }),
enabled: !!id,
});
return useMemo(() => {
const ids = new Set(chats.data?.map((c) => c.id));
return Object.values(runs)
.filter(({ run }) => !id || ids.has(run.conversationId) || byId.get(run.agentId)?.workspaceId === id)
.sort((a, b) => (a.run.createdAt < b.run.createdAt ? 1 : -1));
}, [runs, id, chats.data, byId]);
}
9 changes: 7 additions & 2 deletions packages/core/src/services/conversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,10 @@ export function getConversation(id: string): ConversationWithMessages {
return { ...conversation, messages: listMessages(id), activeRunId, queue: listQueue(id) };
}

/** `workspaceId`: chats of the workspace's agents, and global agents' chats started in it. */
/**
* `workspaceId`: "all"/undefined = every chat; "global" = global agents' chats started outside any workspace;
* a workspace id = chats of the workspace's agents, and global agents' chats started in it.
*/
export function listConversations(
opts: { agentId?: string; workspaceId?: string; search?: string; limit?: number; archived?: boolean } = {},
): Conversation[] {
Expand All @@ -358,7 +361,9 @@ export function listConversations(
where.push("c.agent_id = ?");
params.push(opts.agentId);
}
if (opts.workspaceId) {
if (opts.workspaceId === "global") {
where.push("c.workspace_id IS NULL AND c.agent_id IN (SELECT id FROM agents WHERE workspace_id IS NULL)");
} else if (opts.workspaceId && opts.workspaceId !== "all") {
where.push("(c.workspace_id = ? OR c.agent_id IN (SELECT id FROM agents WHERE workspace_id = ?))");
params.push(opts.workspaceId, opts.workspaceId);
}
Expand Down
6 changes: 6 additions & 0 deletions packages/core/test/conversations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ describe("conversation list", () => {
expect(ids).not.toContain(elsewhere.id);
expect(ids).not.toContain(unscoped.id);
expect(listConversations({ workspaceId: other.id }).map((x) => x.id)).toEqual([elsewhere.id]);

const global = listConversations({ workspaceId: "global" }).map((x) => x.id);
expect(global).toContain(unscoped.id);
expect(global).not.toContain(own.id);
expect(global).not.toContain(started.id);
expect(listConversations({ workspaceId: "all" }).map((x) => x.id)).toEqual(expect.arrayContaining([own.id, started.id, elsewhere.id, unscoped.id]));
});

test("archived chats are listed by last activity, pinned or not", () => {
Expand Down
Loading