Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(daemon): remove watch/unwatch workspace logic, default to all workspaces (#1003)
devv-eve2cbebfc568f7
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 42d11305b9..71dd3e6b7f 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -487,79 +487,6 @@ async function clearToken(): Promise<void> {await removeProfileUserId(active.name);}-interface WatchedWorkspace {- id: string;- name: string;- runtime_count?: number;-}--interface WatchListResponse {- watched: WatchedWorkspace[];- unwatched: string[];-}--async function daemonFetch(- path: string,- init?: RequestInit,-): Promise<Response> {- const active = await ensureActiveProfile();- const url = `http://127.0.0.1:${active.port}${path}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 10_000);- try {- return await fetch(url, { ...init, signal: controller.signal });- } finally {- clearTimeout(timeout);- }-}--async function listWatchedWorkspaces(): Promise<WatchListResponse> {- const empty: WatchListResponse = { watched: [], unwatched: [] };- try {- const res = await daemonFetch("/watch");- if (!res.ok) {- // Older daemon versions don't have /watch. Treat as "nothing watched- // yet" so the UI renders cleanly; the user can take manual action.- if (res.status === 404) return empty;- throw new Error(`list /watch failed: ${res.status} ${res.statusText}`);- }- const data = (await res.json()) as WatchListResponse;- return {- watched: Array.isArray(data.watched) ? data.watched : [],- unwatched: Array.isArray(data.unwatched) ? data.unwatched : [],- };- } catch (err) {- // Network errors (ECONNREFUSED when daemon is still starting, etc.) are- // expected during startup races — return empty instead of throwing so- // we don't spam the main-process error log on every poll.- const msg = err instanceof Error ? err.message : String(err);- console.log(`[daemon] list /watch unreachable: ${msg}`);- return empty;- }-}--async function watchWorkspace(id: string, name: string): Promise<void> {- const res = await daemonFetch("/watch", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: id, name }),- });- if (!res.ok) {- const body = await res.text().catch(() => "");- throw new Error(`watch failed: ${res.status} ${body}`);- }-}--async function unwatchWorkspace(id: string): Promise<void> {- const res = await daemonFetch(`/watch/${encodeURIComponent(id)}`, {- method: "DELETE",- });- if (!res.ok) {- const body = await res.text().catch(() => "");- throw new Error(`unwatch failed: ${res.status} ${body}`);- }-}-async function withGuard<T>(fn: () => Promise<T>): Promise<T | { success: false; error: string }> {if (operationInProgress) {return { success: false, error: "Another daemon operation is in progress" };@@ -804,14 +731,6 @@ export function setupDaemonManager((_event, token: string, userId: string) => syncToken(token, userId),);ipcMain.handle("daemon:clear-token", () => clearToken());- ipcMain.handle("daemon:list-watched", () => listWatchedWorkspaces());- ipcMain.handle(- "daemon:watch-workspace",- (_event, id: string, name: string) => watchWorkspace(id, name),- );- ipcMain.handle("daemon:unwatch-workspace", (_event, id: string) =>- unwatchWorkspace(id),- );ipcMain.handle("daemon:is-cli-installed", async () => {const bin = await resolveCliBinary();return bin !== null;diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex 1d9397e3d8..294bea627c 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -35,12 +35,6 @@ interface DaemonAPI {setTargetApiUrl: (url: string) => Promise<void>;syncToken: (token: string, userId: string) => Promise<void>;clearToken: () => Promise<void>;- listWatched: () => Promise<{- watched: Array<{ id: string; name: string; runtime_count?: number }>;- unwatched: string[];- }>;- watchWorkspace: (id: string, name: string) => Promise<void>;- unwatchWorkspace: (id: string) => Promise<void>;isCliInstalled: () => Promise<boolean>;getPrefs: () => Promise<DaemonPrefs>;setPrefs: (prefs: Partial<DaemonPrefs>) => Promise<DaemonPrefs>;diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex ce08bda751..103f8bf17e 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -50,14 +50,6 @@ const daemonAPI = {ipcRenderer.invoke("daemon:sync-token", token, userId),clearToken: (): Promise<void> =>ipcRenderer.invoke("daemon:clear-token"),- listWatched: (): Promise<{- watched: Array<{ id: string; name: string; runtime_count?: number }>;- unwatched: string[];- }> => ipcRenderer.invoke("daemon:list-watched"),- watchWorkspace: (id: string, name: string): Promise<void> =>- ipcRenderer.invoke("daemon:watch-workspace", id, name),- unwatchWorkspace: (id: string): Promise<void> =>- ipcRenderer.invoke("daemon:unwatch-workspace", id),isCliInstalled: (): Promise<boolean> =>ipcRenderer.invoke("daemon:is-cli-installed"),getPrefs: (): Promise<{ autoStart: boolean; autoStop: boolean }> =>diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex b7e1c77665..c2a1da1704 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -1,8 +1,7 @@-import { useEffect, useRef, useState } from "react";-import { useQuery } from "@tanstack/react-query";+import { useEffect } from "react";import { CoreProvider } from "@multica/core/platform";import { useAuthStore } from "@multica/core/auth";-import { useWorkspaceStore, workspaceListOptions } from "@multica/core/workspace";+import { useWorkspaceStore } from "@multica/core/workspace";import { api } from "@multica/core/api";import { ThemeProvider } from "@multica/ui/components/common/theme-provider";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";@@ -14,7 +13,6 @@ import { UpdateNotification } from "./components/update-notification";function AppContent() {const user = useAuthStore((s) => s.user);const isLoading = useAuthStore((s) => s.isLoading);- const [daemonRunning, setDaemonRunning] = useState(false);// Tell the main process which backend URL we talk to, so daemon-manager// can pick the matching CLI profile (server_url from ~/.multica config).@@ -22,19 +20,6 @@ function AppContent() {window.daemonAPI.setTargetApiUrl(DAEMON_TARGET_API_URL);}, []);- // Track daemon lifecycle so workspace reconciliation only runs when the- // daemon is actually listening — avoids a startup race where the reconcile- // effect fires before autoStart has spawned the child process.- useEffect(() => {- const unsub = window.daemonAPI.onStatusChange((s) => {- setDaemonRunning(s.state === "running");- });- window.daemonAPI.getStatus().then((s) => {- setDaemonRunning(s.state === "running");- });- return unsub;- }, []);-// Listen for auth token delivered via deep link (multica://auth/callback?token=...)useEffect(() => {return window.desktopAPI.onAuthToken(async (token) => {@@ -66,48 +51,6 @@ function AppContent() {})();}, [user]);- // Reconcile the daemon's watched workspaces with what the user is a member- // of. The query already hydrates on login and invalidates on create/delete- // mutations, so this one effect covers both initial sync and incremental- // updates. Opt-outs (unwatched denylist) are respected.- const { data: workspaces } = useQuery({- ...workspaceListOptions(),- enabled: !!user,- });- const lastSyncedIds = useRef<Set<string>>(new Set());- useEffect(() => {- if (!user || !workspaces || !daemonRunning) return;- (async () => {- const state = await window.daemonAPI.listWatched().catch(() => null);- if (!state) return;- const watchedIds = new Set(state.watched.map((w) => w.id));- const unwatchedIds = new Set(state.unwatched);- const currentIds = new Set(workspaces.map((w) => w.id));-- // Add: anything in the API list but not yet watched (and not opted out).- for (const ws of workspaces) {- if (watchedIds.has(ws.id) || unwatchedIds.has(ws.id)) continue;- try {- await window.daemonAPI.watchWorkspace(ws.id, ws.name);- } catch (err) {- console.warn("watch workspace failed", ws.id, err);- }- }- // Remove: anything we previously synced that is no longer in the API- // list (the user left or deleted it).- for (const prevId of lastSyncedIds.current) {- if (!currentIds.has(prevId)) {- try {- await window.daemonAPI.unwatchWorkspace(prevId);- } catch (err) {- console.warn("unwatch workspace failed", prevId, err);- }- }- }- lastSyncedIds.current = currentIds;- })();- }, [user, workspaces, daemonRunning]);-if (isLoading) {return (<div className="flex h-screen items-center justify-center">diff --git a/apps/desktop/src/renderer/src/components/daemon-panel.tsx b/apps/desktop/src/renderer/src/components/daemon-panel.tsxindex ade57c95e7..ed08c8f1f5 100644--- a/apps/desktop/src/renderer/src/components/daemon-panel.tsx+++ b/apps/desktop/src/renderer/src/components/daemon-panel.tsx@@ -7,11 +7,8 @@ import {ChevronDown,X,} from "lucide-react";-import { useQuery } from "@tanstack/react-query";-import { workspaceListOptions } from "@multica/core/workspace";import { cn } from "@multica/ui/lib/utils";import { Button } from "@multica/ui/components/ui/button";-import { Checkbox } from "@multica/ui/components/ui/checkbox";import { toast } from "sonner";import {Sheet,@@ -69,46 +66,6 @@ export function DaemonPanel({ open, onOpenChange, status }: DaemonPanelProps) {const [actionLoading, setActionLoading] = useState(false);const logContainerRef = useRef<HTMLDivElement>(null);- // Watched workspaces — populated from the daemon when the panel opens and- // refreshed after every toggle so the checkbox state reflects reality.- const { data: allWorkspaces } = useQuery({- ...workspaceListOptions(),- enabled: open,- });- const [watchedIds, setWatchedIds] = useState<Set<string>>(new Set());- const [togglingId, setTogglingId] = useState<string | null>(null);-- const refreshWatched = useCallback(async () => {- const state = await window.daemonAPI.listWatched().catch(() => null);- if (state) setWatchedIds(new Set(state.watched.map((w) => w.id)));- }, []);-- useEffect(() => {- if (open && status.state === "running") void refreshWatched();- }, [open, status.state, refreshWatched]);-- const handleToggleWatch = useCallback(- async (id: string, name: string, nextChecked: boolean) => {- setTogglingId(id);- try {- if (nextChecked) {- await window.daemonAPI.watchWorkspace(id, name);- } else {- await window.daemonAPI.unwatchWorkspace(id);- }- await refreshWatched();- } catch (err) {- toast.error(- nextChecked ? "Failed to watch workspace" : "Failed to unwatch workspace",- { description: err instanceof Error ? err.message : String(err) },- );- } finally {- setTogglingId(null);- }- },- [refreshWatched],- );-useEffect(() => {if (!open) return;@@ -304,38 +261,6 @@ export function DaemonPanel({ open, onOpenChange, status }: DaemonPanelProps) {</div>)}- {/* Watched workspaces */}- {status.state === "running" && allWorkspaces && allWorkspaces.length > 0 && (- <div className="space-y-2">- <h3 className="text-sm font-medium">Watched Workspaces</h3>- <div className="rounded-lg border divide-y max-h-48 overflow-y-auto">- {allWorkspaces.map((ws) => {- const checked = watchedIds.has(ws.id);- const disabled = togglingId === ws.id;- return (- <label- key={ws.id}- className={cn(- "flex items-center gap-2.5 px-3 py-2",- disabled- ? "opacity-60 cursor-wait"- : "cursor-pointer hover:bg-muted/40",- )}- >- <Checkbox- checked={checked}- disabled={disabled}- onCheckedChange={(next) =>- handleToggleWatch(ws.id, ws.name, next === true)- }- />- <span className="truncate text-sm">{ws.name}</span>- </label>- );- })}- </div>- </div>- )}</div>{/* Logs — fills remaining vertical space down to the sheet bottom */}diff --git a/server/cmd/multica/cmd_auth.go b/server/cmd/multica/cmd_auth.goindex 889d48c10b..47f794dea6 100644--- a/server/cmd/multica/cmd_auth.go+++ b/server/cmd/multica/cmd_auth.go@@ -218,7 +218,6 @@ func runAuthLoginBrowser(cmd *cobra.Command) error {profile := resolveProfile(cmd)cfg, _ := cli.LoadCLIConfigForProfile(profile)cfg.WorkspaceID = ""- cfg.WatchedWorkspaces = nilcfg.Token = patResp.Tokencfg.ServerURL = serverURLcfg.AppURL = appURL@@ -261,7 +260,6 @@ func runAuthLoginToken(cmd *cobra.Command) error {profile := resolveProfile(cmd)cfg, _ := cli.LoadCLIConfigForProfile(profile)cfg.WorkspaceID = ""- cfg.WatchedWorkspaces = nilcfg.Token = tokencfg.ServerURL = serverURLif err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {diff --git a/server/cmd/multica/cmd_login.go b/server/cmd/multica/cmd_login.goindex 4fea37da71..9930391002 100644--- a/server/cmd/multica/cmd_login.go+++ b/server/cmd/multica/cmd_login.go@@ -93,13 +93,6 @@ func autoWatchWorkspaces(cmd *cobra.Command) error {return err}- var added int- for _, ws := range workspaces {- if cfg.AddWatchedWorkspace(ws.ID, ws.Name) {- added++- }- }-// Set default workspace if not set.if cfg.WorkspaceID == "" {cfg.WorkspaceID = workspaces[0].ID@@ -109,13 +102,9 @@ func autoWatchWorkspaces(cmd *cobra.Command) error {return err}- if added > 0 {- fmt.Fprintf(os.Stderr, "\nWatching %d workspace(s):\n", len(workspaces))- for _, ws := range workspaces {- fmt.Fprintf(os.Stderr, " • %s (%s)\n", ws.Name, ws.ID)- }- } else {- fmt.Fprintf(os.Stderr, "\nAll %d workspace(s) already watched.\n", len(workspaces))+ fmt.Fprintf(os.Stderr, "\nFound %d workspace(s):\n", len(workspaces))+ for _, ws := range workspaces {+ fmt.Fprintf(os.Stderr, " • %s (%s)\n", ws.Name, ws.ID)}return nildiff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.goindex 71cd444a3e..391fbe1e4d 100644--- a/server/cmd/multica/cmd_setup.go+++ b/server/cmd/multica/cmd_setup.go@@ -135,17 +135,11 @@ func runSetupCloud(cmd *cobra.Command, args []string) error {return err}- // Start daemon only if we have workspaces to watch.- if hasWatchedWorkspaces(resolveProfile(cmd)) {- fmt.Fprintln(os.Stderr, "\nStarting daemon...")- if err := runDaemonBackground(cmd); err != nil {- return fmt.Errorf("start daemon: %w", err)- }- fmt.Fprintln(os.Stderr, "\n✓ Setup complete! Your machine is now connected to Multica.")- } else {- fmt.Fprintln(os.Stderr, "\n⚠ Setup incomplete: no workspaces configured.")- fmt.Fprintln(os.Stderr, "Create a workspace at the web dashboard, then run 'multica login' and 'multica daemon start'.")+ fmt.Fprintln(os.Stderr, "\nStarting daemon...")+ if err := runDaemonBackground(cmd); err != nil {+ return fmt.Errorf("start daemon: %w", err)}+ fmt.Fprintln(os.Stderr, "\n✓ Setup complete! Your machine is now connected to Multica.")return nil}@@ -200,30 +194,15 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {return err}- // Start daemon only if we have workspaces to watch.- if hasWatchedWorkspaces(resolveProfile(cmd)) {- fmt.Fprintln(os.Stderr, "\nStarting daemon...")- if err := runDaemonBackground(cmd); err != nil {- return fmt.Errorf("start daemon: %w", err)- }- fmt.Fprintln(os.Stderr, "\n✓ Setup complete! Your machine is now connected to Multica.")- } else {- fmt.Fprintln(os.Stderr, "\n⚠ Setup incomplete: no workspaces configured.")- fmt.Fprintln(os.Stderr, "Create a workspace at the web dashboard, then run 'multica login' and 'multica daemon start'.")+ fmt.Fprintln(os.Stderr, "\nStarting daemon...")+ if err := runDaemonBackground(cmd); err != nil {+ return fmt.Errorf("start daemon: %w", err)}+ fmt.Fprintln(os.Stderr, "\n✓ Setup complete! Your machine is now connected to Multica.")return nil}-// hasWatchedWorkspaces returns true if the CLI config has at least one watched workspace.-func hasWatchedWorkspaces(profile string) bool {- cfg, err := cli.LoadCLIConfigForProfile(profile)- if err != nil {- return false- }- return len(cfg.WatchedWorkspaces) > 0-}-// probeServer checks whether a Multica backend is reachable at the given URL.func probeServer(baseURL string) bool {url := strings.TrimRight(baseURL, "/") + "/health"diff --git a/server/cmd/multica/cmd_workspace.go b/server/cmd/multica/cmd_workspace.goindex 44dc37d859..2dac838370 100644--- a/server/cmd/multica/cmd_workspace.go+++ b/server/cmd/multica/cmd_workspace.go@@ -38,26 +38,10 @@ var workspaceMembersCmd = &cobra.Command{RunE: runWorkspaceMembers,}-var workspaceWatchCmd = &cobra.Command{- Use: "watch <workspace-id>",- Short: "Add a workspace to the daemon watch list",- Args: exactArgs(1),- RunE: runWatch,-}--var workspaceUnwatchCmd = &cobra.Command{- Use: "unwatch <workspace-id>",- Short: "Remove a workspace from the daemon watch list",- Args: exactArgs(1),- RunE: runUnwatch,-}-func init() {workspaceCmd.AddCommand(workspaceListCmd)workspaceCmd.AddCommand(workspaceGetCmd)workspaceCmd.AddCommand(workspaceMembersCmd)- workspaceCmd.AddCommand(workspaceWatchCmd)- workspaceCmd.AddCommand(workspaceUnwatchCmd)workspaceGetCmd.Flags().String("output", "json", "Output format: table or json")workspaceMembersCmd.Flags().String("output", "table", "Output format: table or json")@@ -87,22 +71,10 @@ func runWorkspaceList(cmd *cobra.Command, _ []string) error {return nil}- // Load watched set for marking.- profile := resolveProfile(cmd)- cfg, _ := cli.LoadCLIConfigForProfile(profile)- watched := make(map[string]bool)- for _, w := range cfg.WatchedWorkspaces {- watched[w.ID] = true- }-w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)- fmt.Fprintln(w, "ID\tNAME\tWATCHING")+ fmt.Fprintln(w, "ID\tNAME")for _, ws := range workspaces {- mark := ""- if watched[ws.ID] {- mark = "*"- }- fmt.Fprintf(w, "%s\t%s\t%s\n", ws.ID, ws.Name, mark)+ fmt.Fprintf(w, "%s\t%s\n", ws.ID, ws.Name)}return w.Flush()}@@ -198,68 +170,3 @@ func runWorkspaceMembers(cmd *cobra.Command, args []string) error {return nil}-func runWatch(cmd *cobra.Command, args []string) error {- workspaceID := args[0]-- serverURL := resolveServerURL(cmd)- token := resolveToken(cmd)- if token == "" {- return fmt.Errorf("not authenticated: run 'multica login' first")- }-- client := cli.NewAPIClient(serverURL, "", token)- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)- defer cancel()-- var ws struct {- ID string `json:"id"`- Name string `json:"name"`- }- if err := client.GetJSON(ctx, "/api/workspaces/"+workspaceID, &ws); err != nil {- return fmt.Errorf("workspace not found: %w", err)- }-- profile := resolveProfile(cmd)- cfg, err := cli.LoadCLIConfigForProfile(profile)- if err != nil {- return err- }-- if !cfg.AddWatchedWorkspace(ws.ID, ws.Name) {- fmt.Fprintf(os.Stderr, "Already watching workspace %s (%s)\n", ws.ID, ws.Name)- return nil- }-- if cfg.WorkspaceID == "" {- cfg.WorkspaceID = ws.ID- fmt.Fprintf(os.Stderr, "Set default workspace to %s (%s)\n", ws.ID, ws.Name)- }-- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {- return err- }-- fmt.Fprintf(os.Stderr, "Watching workspace %s (%s)\n", ws.ID, ws.Name)- return nil-}--func runUnwatch(cmd *cobra.Command, args []string) error {- workspaceID := args[0]-- profile := resolveProfile(cmd)- cfg, err := cli.LoadCLIConfigForProfile(profile)- if err != nil {- return err- }-- if !cfg.RemoveWatchedWorkspace(workspaceID) {- return fmt.Errorf("workspace %s is not being watched", workspaceID)- }-- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {- return err- }-- fmt.Fprintf(os.Stderr, "Stopped watching workspace %s\n", workspaceID)- return nil-}diff --git a/server/internal/cli/config.go b/server/internal/cli/config.goindex 0ee73de0a0..5188116ab5 100644--- a/server/internal/cli/config.go+++ b/server/internal/cli/config.go@@ -10,75 +10,12 @@ import (const defaultCLIConfigPath = ".multica/config.json"-// WatchedWorkspace represents a workspace the daemon should monitor for tasks.-type WatchedWorkspace struct {- ID string `json:"id"`- Name string `json:"name,omitempty"`-}-// CLIConfig holds persistent CLI settings.type CLIConfig struct {- ServerURL string `json:"server_url,omitempty"`- AppURL string `json:"app_url,omitempty"`- WorkspaceID string `json:"workspace_id,omitempty"`- Token string `json:"token,omitempty"`- WatchedWorkspaces []WatchedWorkspace `json:"watched_workspaces,omitempty"`- // UnwatchedWorkspaces is a denylist of workspace IDs the user has- // explicitly opted out of. The daemon's periodic sync from the API- // respects this list and won't re-add excluded workspaces.- UnwatchedWorkspaces []string `json:"unwatched_workspaces,omitempty"`-}--// IsUnwatched reports whether the given workspace ID is in the denylist.-func (c *CLIConfig) IsUnwatched(id string) bool {- for _, u := range c.UnwatchedWorkspaces {- if u == id {- return true- }- }- return false-}--// AddUnwatchedWorkspace adds an ID to the denylist. Returns true if added.-func (c *CLIConfig) AddUnwatchedWorkspace(id string) bool {- if c.IsUnwatched(id) {- return false- }- c.UnwatchedWorkspaces = append(c.UnwatchedWorkspaces, id)- return true-}--// RemoveUnwatchedWorkspace removes an ID from the denylist. Returns true if removed.-func (c *CLIConfig) RemoveUnwatchedWorkspace(id string) bool {- for i, u := range c.UnwatchedWorkspaces {- if u == id {- c.UnwatchedWorkspaces = append(c.UnwatchedWorkspaces[:i], c.UnwatchedWorkspaces[i+1:]...)- return true- }- }- return false-}--// AddWatchedWorkspace adds a workspace to the watch list. Returns true if added.-func (c *CLIConfig) AddWatchedWorkspace(id, name string) bool {- for _, w := range c.WatchedWorkspaces {- if w.ID == id {- return false- }- }- c.WatchedWorkspaces = append(c.WatchedWorkspaces, WatchedWorkspace{ID: id, Name: name})- return true-}--// RemoveWatchedWorkspace removes a workspace from the watch list. Returns true if found.-func (c *CLIConfig) RemoveWatchedWorkspace(id string) bool {- for i, w := range c.WatchedWorkspaces {- if w.ID == id {- c.WatchedWorkspaces = append(c.WatchedWorkspaces[:i], c.WatchedWorkspaces[i+1:]...)- return true- }- }- return false+ ServerURL string `json:"server_url,omitempty"`+ AppURL string `json:"app_url,omitempty"`+ WorkspaceID string `json:"workspace_id,omitempty"`+ Token string `json:"token,omitempty"`}// CLIConfigPath returns the default path for the CLI config file.diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 007c126b92..e66f4cecdf 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -16,7 +16,6 @@ const (DefaultHeartbeatInterval = 15 * time.SecondDefaultAgentTimeout = 2 * time.HourDefaultRuntimeName = "Local Agent"- DefaultConfigReloadInterval = 5 * time.SecondDefaultWorkspaceSyncInterval = 30 * time.SecondDefaultHealthPort = 19514DefaultMaxConcurrentTasks = 20diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex acccc327a7..67ed58c026 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -81,33 +81,17 @@ func (d *Daemon) Run(ctx context.Context) error {return err}- // Load and register watched workspaces.- if err := d.loadWatchedWorkspaces(ctx); err != nil {+ // Fetch all user workspaces from the API and register runtimes.+ if err := d.syncWorkspacesFromAPI(ctx); err != nil {return err}-- // If no runtimes yet (empty watched list), run one sync cycle to discover- // workspaces from the API before giving up. workspaceSyncLoop normally- // handles this, but the runtime check below would fail before it runs.if len(d.allRuntimeIDs()) == 0 {- d.syncWorkspacesFromAPI(ctx)- // syncWorkspacesFromAPI writes to config; reload and register.- if err := d.loadWatchedWorkspaces(ctx); err != nil {- return err- }- }-- runtimeIDs := d.allRuntimeIDs()- if len(runtimeIDs) == 0 {return fmt.Errorf("no runtimes registered")}// Deregister runtimes on shutdown (uses a fresh context since ctx will be cancelled).defer d.deregisterRuntimes()- // Start config watcher for hot-reload.- go d.configWatchLoop(ctx)-// Start workspace sync loop to discover newly created workspaces.go d.workspaceSyncLoop(ctx)@@ -160,60 +144,6 @@ func (d *Daemon) resolveAuth() error {return nil}-// loadWatchedWorkspaces reads watched workspaces from CLI config and registers runtimes.-func (d *Daemon) loadWatchedWorkspaces(ctx context.Context) error {- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- return fmt.Errorf("load CLI config: %w", err)- }-- // It's fine to start with an empty watched list — workspaceSyncLoop runs- // immediately on startup and will populate the list from the server. The- // daemon also accepts HTTP POST /watch for explicit adds from clients- // like the Desktop app.- if len(cfg.WatchedWorkspaces) == 0 {- d.logger.Info("no watched workspaces in config; workspaceSyncLoop will populate from API")- return nil- }-- var registered int- for _, ws := range cfg.WatchedWorkspaces {- resp, err := d.registerRuntimesForWorkspace(ctx, ws.ID)- if err != nil {- d.logger.Error("failed to register runtimes", "workspace_id", ws.ID, "name", ws.Name, "error", err)- continue- }- runtimeIDs := make([]string, len(resp.Runtimes))- for i, rt := range resp.Runtimes {- runtimeIDs[i] = rt.ID- d.logger.Info("registered runtime", "workspace_id", ws.ID, "runtime_id", rt.ID, "provider", rt.Provider)- }- d.mu.Lock()- d.workspaces[ws.ID] = &workspaceState{workspaceID: ws.ID, runtimeIDs: runtimeIDs}- for _, rt := range resp.Runtimes {- d.runtimeIndex[rt.ID] = rt- }- d.mu.Unlock()-- // Sync workspace repos to local cache in the background so heartbeat- // and poll loops are not blocked by slow git clone/fetch operations.- if d.repoCache != nil && len(resp.Repos) > 0 {- go func(wsID string, repos []RepoData) {- if err := d.repoCache.Sync(wsID, repoDataToInfo(repos)); err != nil {- d.logger.Warn("repo cache sync failed", "workspace_id", wsID, "error", err)- }- }(ws.ID, resp.Repos)- }-- d.logger.Info("watching workspace", "workspace_id", ws.ID, "name", ws.Name, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos))- registered++- }-- if registered == 0 {- return fmt.Errorf("failed to register runtimes for any of the %d watched workspace(s)", len(cfg.WatchedWorkspaces))- }- return nil-}// allRuntimeIDs returns all runtime IDs across all watched workspaces.func (d *Daemon) allRuntimeIDs() []string {@@ -293,47 +223,9 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID sreturn resp, nil}-// configWatchLoop periodically checks for config file changes and reloads workspaces.-func (d *Daemon) configWatchLoop(ctx context.Context) {- configPath, err := cli.CLIConfigPathForProfile(d.cfg.Profile)- if err != nil {- d.logger.Warn("cannot watch config file", "error", err)- return- }-- var lastModTime time.Time- if info, err := os.Stat(configPath); err == nil {- lastModTime = info.ModTime()- }-- ticker := time.NewTicker(DefaultConfigReloadInterval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- info, err := os.Stat(configPath)- if err != nil {- continue- }- if !info.ModTime().After(lastModTime) {- continue- }- lastModTime = info.ModTime()- d.reloadWorkspaces(ctx)- }- }-}-// workspaceSyncLoop periodically fetches the user's workspaces from the API-// and adds any new ones to the CLI config. The configWatchLoop will then-// detect the config change and register runtimes for the new workspaces.+// and registers runtimes for any new ones.func (d *Daemon) workspaceSyncLoop(ctx context.Context) {- // Run immediately on startup before entering the periodic loop.- d.syncWorkspacesFromAPI(ctx)-ticker := time.NewTicker(DefaultWorkspaceSyncInterval)defer ticker.Stop()@@ -342,113 +234,77 @@ func (d *Daemon) workspaceSyncLoop(ctx context.Context) {case <-ctx.Done():returncase <-ticker.C:- d.syncWorkspacesFromAPI(ctx)+ if err := d.syncWorkspacesFromAPI(ctx); err != nil {+ d.logger.Debug("workspace sync failed", "error", err)+ }}}}-// syncWorkspacesFromAPI fetches all workspaces the user belongs to and adds-// any missing ones to the CLI config's watched list.-func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) {+// syncWorkspacesFromAPI fetches all workspaces the user belongs to and+// registers runtimes for any that aren't already tracked. Workspaces the user+// has left are cleaned up.+func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {+ d.reloading.Lock()+ defer d.reloading.Unlock()+apiCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()workspaces, err := d.client.ListWorkspaces(apiCtx)if err != nil {- d.logger.Debug("workspace sync: failed to list workspaces", "error", err)- return- }-- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- d.logger.Warn("workspace sync: failed to load config", "error", err)- return+ return fmt.Errorf("list workspaces: %w", err)}- var added int+ apiIDs := make(map[string]string, len(workspaces)) // id -> namefor _, ws := range workspaces {- if cfg.IsUnwatched(ws.ID) {- continue // user explicitly opted out- }- if cfg.AddWatchedWorkspace(ws.ID, ws.Name) {- added++- d.logger.Info("workspace sync: discovered new workspace", "workspace_id", ws.ID, "name", ws.Name)- }- }-- if added == 0 {- return- }-- if err := cli.SaveCLIConfigForProfile(cfg, d.cfg.Profile); err != nil {- d.logger.Warn("workspace sync: failed to save config", "error", err)- return- }- d.logger.Info("workspace sync: added new workspace(s) to config", "count", added)-}--// reloadWorkspaces reconciles the active workspace set with the config file.-// NOTE: Token changes (e.g. re-login as a different user) are not picked up;-// the daemon must be restarted for a new auth token to take effect.-func (d *Daemon) reloadWorkspaces(ctx context.Context) {- d.reloading.Lock()- defer d.reloading.Unlock()-- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- d.logger.Warn("reload config failed", "error", err)- return- }-- newIDs := make(map[string]string) // id -> name- for _, ws := range cfg.WatchedWorkspaces {- newIDs[ws.ID] = ws.Name+ apiIDs[ws.ID] = ws.Name}d.mu.Lock()- currentIDs := make(map[string]bool)+ currentIDs := make(map[string]bool, len(d.workspaces))for id := range d.workspaces {currentIDs[id] = true}d.mu.Unlock()- // Register runtimes for newly added workspaces.- for id, name := range newIDs {- if !currentIDs[id] {- resp, err := d.registerRuntimesForWorkspace(ctx, id)- if err != nil {- d.logger.Error("register runtimes for new workspace failed", "workspace_id", id, "error", err)- continue- }- runtimeIDs := make([]string, len(resp.Runtimes))- for i, rt := range resp.Runtimes {- runtimeIDs[i] = rt.ID- }- d.mu.Lock()- d.workspaces[id] = &workspaceState{workspaceID: id, runtimeIDs: runtimeIDs}- for _, rt := range resp.Runtimes {- d.runtimeIndex[rt.ID] = rt- }- d.mu.Unlock()-- // Sync workspace repos to local cache in the background.- if d.repoCache != nil && len(resp.Repos) > 0 {- go func(wsID string, repos []RepoData) {- if err := d.repoCache.Sync(wsID, repoDataToInfo(repos)); err != nil {- d.logger.Warn("repo cache sync failed", "workspace_id", wsID, "error", err)- }- }(id, resp.Repos)- }+ var registered int+ for id, name := range apiIDs {+ if currentIDs[id] {+ continue+ }+ resp, err := d.registerRuntimesForWorkspace(ctx, id)+ if err != nil {+ d.logger.Error("failed to register runtimes", "workspace_id", id, "name", name, "error", err)+ continue+ }+ runtimeIDs := make([]string, len(resp.Runtimes))+ for i, rt := range resp.Runtimes {+ runtimeIDs[i] = rt.ID+ d.logger.Info("registered runtime", "workspace_id", id, "runtime_id", rt.ID, "provider", rt.Provider)+ }+ d.mu.Lock()+ d.workspaces[id] = &workspaceState{workspaceID: id, runtimeIDs: runtimeIDs}+ for _, rt := range resp.Runtimes {+ d.runtimeIndex[rt.ID] = rt+ }+ d.mu.Unlock()- d.logger.Info("now watching workspace", "workspace_id", id, "name", name)+ if d.repoCache != nil && len(resp.Repos) > 0 {+ go func(wsID string, repos []RepoData) {+ if err := d.repoCache.Sync(wsID, repoDataToInfo(repos)); err != nil {+ d.logger.Warn("repo cache sync failed", "workspace_id", wsID, "error", err)+ }+ }(id, resp.Repos)}++ d.logger.Info("watching workspace", "workspace_id", id, "name", name, "runtimes", len(resp.Runtimes))+ registered++}- // Remove workspaces no longer in config.- // NOTE: runtimes are not deregistered server-side; they will go offline- // after heartbeats stop arriving (within HeartbeatInterval).+ // Remove workspaces the user no longer belongs to.for id := range currentIDs {- if _, ok := newIDs[id]; !ok {+ if _, ok := apiIDs[id]; !ok {d.mu.Lock()if ws, exists := d.workspaces[id]; exists {for _, rid := range ws.runtimeIDs {@@ -460,6 +316,11 @@ func (d *Daemon) reloadWorkspaces(ctx context.Context) {d.logger.Info("stopped watching workspace", "workspace_id", id)}}++ if len(d.allRuntimeIDs()) == 0 && registered == 0 && len(workspaces) > 0 {+ return fmt.Errorf("failed to register runtimes for any of the %d workspace(s)", len(workspaces))+ }+ return nil}func (d *Daemon) heartbeatLoop(ctx context.Context) {diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 2f921c802d..55072e7b5c 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -7,10 +7,8 @@ import ("net""net/http""os"- "strings""time"- "github.com/multica-ai/multica/server/internal/cli""github.com/multica-ai/multica/server/internal/daemon/repocache")@@ -51,19 +49,6 @@ type repoCheckoutRequest struct {TaskID string `json:"task_id"`}-// watchWorkspaceRequest is the body of a POST /watch request.-type watchWorkspaceRequest struct {- WorkspaceID string `json:"workspace_id"`- Name string `json:"name"`-}--// watchedWorkspaceItem is one entry in the GET /watch response.-type watchedWorkspaceItem struct {- ID string `json:"id"`- Name string `json:"name"`- Runtime int `json:"runtime_count"`-}-// serveHealth runs the health HTTP server on the given listener.// Blocks until ctx is cancelled.func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt time.Time) {@@ -99,31 +84,6 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timjson.NewEncoder(w).Encode(resp)})- mux.HandleFunc("/watch", func(w http.ResponseWriter, r *http.Request) {- switch r.Method {- case http.MethodGet:- d.handleListWatched(w, r)- case http.MethodPost:- d.handleWatchWorkspace(w, r)- default:- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)- }- })-- // DELETE /watch/{workspace_id}- mux.HandleFunc("/watch/", func(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodDelete {- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)- return- }- id := strings.TrimPrefix(r.URL.Path, "/watch/")- if id == "" {- http.Error(w, "workspace_id is required in path", http.StatusBadRequest)- return- }- d.handleUnwatchWorkspace(w, r, id)- })-mux.HandleFunc("/repo/checkout", func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "method not allowed", http.StatusMethodNotAllowed)@@ -179,134 +139,3 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt tim}}-// handleListWatched returns the daemon's current watched workspaces merged-// with the persisted config so clients can reflect "what is watched" and-// "what has been explicitly opted out".-func (d *Daemon) handleListWatched(w http.ResponseWriter, _ *http.Request) {- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)- return- }-- d.mu.Lock()- items := make([]watchedWorkspaceItem, 0, len(cfg.WatchedWorkspaces))- for _, ws := range cfg.WatchedWorkspaces {- rc := 0- if state, ok := d.workspaces[ws.ID]; ok {- rc = len(state.runtimeIDs)- }- items = append(items, watchedWorkspaceItem{- ID: ws.ID,- Name: ws.Name,- Runtime: rc,- })- }- d.mu.Unlock()-- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(map[string]any{- "watched": items,- "unwatched": cfg.UnwatchedWorkspaces,- })-}--// handleWatchWorkspace registers a new workspace at runtime. Updates config-// (removes from denylist, adds to watched list), registers runtimes via the-// API, and records the result in daemon state. Idempotent.-func (d *Daemon) handleWatchWorkspace(w http.ResponseWriter, r *http.Request) {- var req watchWorkspaceRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)- return- }- if req.WorkspaceID == "" {- http.Error(w, "workspace_id is required", http.StatusBadRequest)- return- }-- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)- return- }- cfg.RemoveUnwatchedWorkspace(req.WorkspaceID)- cfg.AddWatchedWorkspace(req.WorkspaceID, req.Name)- if err := cli.SaveCLIConfigForProfile(cfg, d.cfg.Profile); err != nil {- http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError)- return- }-- // Skip registration if we're already tracking this workspace.- d.mu.Lock()- _, already := d.workspaces[req.WorkspaceID]- d.mu.Unlock()- if already {- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(map[string]any{"status": "already_watching"})- return- }-- resp, err := d.registerRuntimesForWorkspace(r.Context(), req.WorkspaceID)- if err != nil {- d.logger.Error("watch: register failed", "workspace_id", req.WorkspaceID, "error", err)- http.Error(w, "register runtimes: "+err.Error(), http.StatusInternalServerError)- return- }-- runtimeIDs := make([]string, len(resp.Runtimes))- for i, rt := range resp.Runtimes {- runtimeIDs[i] = rt.ID- }- d.mu.Lock()- d.workspaces[req.WorkspaceID] = &workspaceState{workspaceID: req.WorkspaceID, runtimeIDs: runtimeIDs}- for _, rt := range resp.Runtimes {- d.runtimeIndex[rt.ID] = rt- }- d.mu.Unlock()-- if d.repoCache != nil && len(resp.Repos) > 0 {- go func(wsID string, repos []RepoData) {- if err := d.repoCache.Sync(wsID, repoDataToInfo(repos)); err != nil {- d.logger.Warn("repo cache sync failed", "workspace_id", wsID, "error", err)- }- }(req.WorkspaceID, resp.Repos)- }-- d.logger.Info("watch: now watching workspace", "workspace_id", req.WorkspaceID, "name", req.Name, "runtimes", len(resp.Runtimes))- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(map[string]any{- "status": "watching",- "workspace_id": req.WorkspaceID,- "runtime_count": len(runtimeIDs),- })-}--// handleUnwatchWorkspace stops tracking a workspace and records the opt-out-// in the denylist so the periodic API sync won't revive it.-func (d *Daemon) handleUnwatchWorkspace(w http.ResponseWriter, _ *http.Request, id string) {- cfg, err := cli.LoadCLIConfigForProfile(d.cfg.Profile)- if err != nil {- http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)- return- }- cfg.RemoveWatchedWorkspace(id)- cfg.AddUnwatchedWorkspace(id)- if err := cli.SaveCLIConfigForProfile(cfg, d.cfg.Profile); err != nil {- http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError)- return- }-- d.mu.Lock()- if state, ok := d.workspaces[id]; ok {- for _, rid := range state.runtimeIDs {- delete(d.runtimeIndex, rid)- }- delete(d.workspaces, id)- }- d.mu.Unlock()-- d.logger.Info("watch: stopped watching workspace", "workspace_id", id)- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(map[string]any{"status": "unwatched", "workspace_id": id})-}