Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4480: make daemon workspace sync event-driven (#5354)
Multica Eveac62f72c2a1c
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex 4eb6bbed5b..0358dc5bdb 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -324,9 +324,12 @@ describe("applyWorkspaceUpdatedToCache", () => {expect(invalidate).toHaveBeenCalledWith({queryKey: issueKeys.all(wsId),});- expect(invalidate).toHaveBeenCalledWith({+ expect(invalidate).not.toHaveBeenCalledWith({queryKey: workspaceKeys.list(),});+ expect(+ qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.issue_prefix,+ ).toBe("NEW");});it("does not invalidate issue cache when only non-prefix fields change", () => {@@ -343,9 +346,12 @@ describe("applyWorkspaceUpdatedToCache", () => {expect(invalidate).not.toHaveBeenCalledWith({queryKey: issueKeys.all(wsId),});- expect(invalidate).toHaveBeenCalledWith({+ expect(invalidate).not.toHaveBeenCalledWith({queryKey: workspaceKeys.list(),});+ expect(qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.name).toBe(+ "New name",+ );});it("invalidates issue cache when the workspace isn't in the cached list yet", () => {@@ -363,6 +369,9 @@ describe("applyWorkspaceUpdatedToCache", () => {expect(invalidate).toHaveBeenCalledWith({queryKey: issueKeys.all(wsId),});+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: workspaceKeys.list(),+ });});});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 3586b65003..8dd5c0878c 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -237,12 +237,10 @@ export function applyChatSessionUpdatedToCache(}/**- * Apply a workspace:updated event to the cache. Always refreshes the- * workspace list. If the incoming `issue_prefix` differs from what's- * currently cached, also invalidates issueKeys.all for that workspace,- * since every issue's rendered identifier (`MUL-123`) is recomputed from- * the workspace prefix at read time. Without this, the UI keeps showing- * the old `OLD-N` keys until the next hard refresh.+ * Apply a workspace:updated event directly to the cached workspace list.+ * If the incoming `issue_prefix` differs from what's currently cached, also+ * invalidates issueKeys.all for that workspace, since every issue's rendered+ * identifier (`MUL-123`) is recomputed from the workspace prefix at read time.** If the workspace isn't in the cached list (first observation), we* conservatively invalidate — the prefix is effectively "new" relative to@@ -255,13 +253,21 @@ export function applyWorkspaceUpdatedToCache(): void {const next = payload.workspace;if (next?.id) {- const cached =- qc- .getQueryData<Workspace[]>(workspaceKeys.list())- ?.find((w) => w.id === next.id) ?? null;- if (!cached || cached.issue_prefix !== next.issue_prefix) {+ const list = qc.getQueryData<Workspace[]>(workspaceKeys.list());+ const cached = list?.find((w) => w.id === next.id) ?? null;+ if (cached && cached.issue_prefix !== next.issue_prefix) {qc.invalidateQueries({ queryKey: issueKeys.all(next.id) });}+ if (cached && list) {+ qc.setQueryData<Workspace[]>(+ workspaceKeys.list(),+ list.map((workspace) => (workspace.id === next.id ? next : workspace)),+ );+ return;+ }+ // Do not seed an absent list with one workspace: staleTime is Infinity,+ // so doing so would hide every other membership until a hard refresh.+ qc.invalidateQueries({ queryKey: issueKeys.all(next.id) });}qc.invalidateQueries({ queryKey: workspaceKeys.list() });}diff --git a/packages/core/workspace/mutations.test.tsx b/packages/core/workspace/mutations.test.tsxindex 371f598c48..2618c88798 100644--- a/packages/core/workspace/mutations.test.tsx+++ b/packages/core/workspace/mutations.test.tsx@@ -9,7 +9,7 @@ import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import { defaultStorage } from "../platform/storage";import type { Workspace } from "../types";-import { useDeleteWorkspace } from "./mutations";+import { useCreateWorkspace, useDeleteWorkspace } from "./mutations";import { workspaceKeys } from "./queries";import {isWorkspaceDeletePending,@@ -36,6 +36,66 @@ const makeWorkspace = (id: string, slug: string): Workspace => ({updated_at: "2026-01-01T00:00:00Z",});+describe("useCreateWorkspace", () => {+ let qc: QueryClient;+ let createWorkspace: ReturnType<+ typeof vi.fn<(data: { name: string; slug: string }) => Promise<Workspace>>+ >;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ createWorkspace = vi.fn();+ setApiInstance({ createWorkspace } as unknown as ApiClient);+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [+ makeWorkspace("ws-1", "existing"),+ ]);+ });++ afterEach(() => {+ qc.clear();+ vi.restoreAllMocks();+ });++ it("seeds the successful response without invalidating the workspace list", async () => {+ const created = makeWorkspace("ws-2", "created");+ createWorkspace.mockResolvedValue(created);+ const { result } = renderHook(() => useCreateWorkspace(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current.mutateAsync({ name: "Created", slug: "created" });+ });++ expect(+ qc+ .getQueryData<Workspace[]>(workspaceKeys.list())+ ?.map((workspace) => workspace.id),+ ).toEqual(["ws-1", "ws-2"]);+ expect(qc.getQueryState(workspaceKeys.list())?.isInvalidated).toBe(false);+ });++ it("invalidates the workspace list when create fails", async () => {+ createWorkspace.mockRejectedValue(new Error("response lost"));+ const { result } = renderHook(() => useCreateWorkspace(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await expect(+ result.current.mutateAsync({ name: "Created", slug: "created" }),+ ).rejects.toThrow("response lost");+ });++ expect(qc.getQueryState(workspaceKeys.list())?.isInvalidated).toBe(true);+ expect(+ qc+ .getQueryData<Workspace[]>(workspaceKeys.list())+ ?.map((workspace) => workspace.id),+ ).toEqual(["ws-1"]);+ });+});+describe("useDeleteWorkspace", () => {let qc: QueryClient;let deleteWorkspace: ReturnType<typeof vi.fn<(id: string) => Promise<void>>>;diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.tsindex 84487d4572..0c2ed6261c 100644--- a/packages/core/workspace/mutations.ts+++ b/packages/core/workspace/mutations.ts@@ -25,7 +25,11 @@ export function useCreateWorkspace() {onSuccess: (newWs) => {qc.setQueryData(workspaceKeys.list(), (old: Workspace[] = []) => [...old, newWs]);},- onSettled: () => {+ // A failed create should not have changed server state, but invalidate the+ // list once to reconcile ambiguous transport failures where the server may+ // have committed before the client lost the response. Keep this off the+ // success path so the canonical response seeded above is not fetched again.+ onError: () => {qc.invalidateQueries({ queryKey: workspaceKeys.list() });},});diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 10795cce9c..5596e602c6 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -198,6 +198,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busif notifier, ok := opts.DaemonWakeup.(handler.RuntimeProfileRefreshNotifier); ok {h.DaemonProfileRefresh = notifier}+ if notifier, ok := opts.DaemonWakeup.(handler.WorkspaceSetRefreshNotifier); ok {+ h.DaemonWorkspaceRefresh = notifier+ }}if rdb != nil {h.UpdateStore = handler.NewRedisUpdateStore(rdb)@@ -729,6 +732,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/deregister", h.DaemonDeregister)r.Post("/heartbeat", h.DaemonHeartbeat)r.Get("/ws", h.DaemonWebSocket)+ r.Get("/workspaces", h.ListDaemonWorkspaces)r.Get("/workspaces/{workspaceId}/repos", h.GetDaemonWorkspaceRepos)r.Get("/workspaces/{workspaceId}/runtime-profiles", h.DaemonListRuntimeProfiles)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex d71d351acf..a10d83db43 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -10,6 +10,7 @@ import ("net/http""runtime""strings"+ "sync""time""github.com/multica-ai/multica/server/pkg/protocol"@@ -104,6 +105,12 @@ type Client struct {platform stringversion stringos string++ workspaceMu sync.Mutex+ workspaceETag string+ workspaceCache []WorkspaceInfo+ workspaceCacheValid bool+ legacyWorkspaceEndpointEnabled bool}// NewClient creates a new daemon API client.@@ -494,8 +501,67 @@ func (c *Client) RenewToken(ctx context.Context) (*RenewTokenResponse, error) {return &resp, nil}-// ListWorkspaces fetches all workspaces the authenticated user belongs to.+// ListWorkspaces fetches the minimal workspace membership set used by the+// daemon. New servers expose a daemon-specific endpoint with ETag support;+// when an installed daemon talks to an older server, the first 404 switches+// this process to the legacy full-workspace endpoint for compatibility.func (c *Client) ListWorkspaces(ctx context.Context) ([]WorkspaceInfo, error) {+ c.workspaceMu.Lock()+ defer c.workspaceMu.Unlock()++ if c.legacyWorkspaceEndpointEnabled {+ return c.listLegacyWorkspaces(ctx)+ }++ const path = "/api/daemon/workspaces"+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)+ if err != nil {+ return nil, err+ }+ if c.token != "" {+ req.Header.Set("Authorization", "Bearer "+c.token)+ }+ c.setIdentityHeaders(req)+ if c.workspaceETag != "" {+ req.Header.Set("If-None-Match", c.workspaceETag)+ }++ resp, err := c.client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ if resp.StatusCode == http.StatusNotFound {+ _, _ = io.Copy(io.Discard, resp.Body)+ c.legacyWorkspaceEndpointEnabled = true+ c.workspaceETag = ""+ c.workspaceCache = nil+ c.workspaceCacheValid = false+ return c.listLegacyWorkspaces(ctx)+ }+ if resp.StatusCode == http.StatusNotModified {+ if !c.workspaceCacheValid {+ return nil, fmt.Errorf("GET %s returned 304 without a cached workspace set", path)+ }+ return append([]WorkspaceInfo(nil), c.workspaceCache...), nil+ }+ if resp.StatusCode >= 400 {+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ return nil, &requestError{Method: http.MethodGet, Path: path, StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(data))}+ }++ var workspaces []WorkspaceInfo+ if err := json.NewDecoder(resp.Body).Decode(&workspaces); err != nil {+ return nil, err+ }+ c.workspaceETag = resp.Header.Get("ETag")+ c.workspaceCache = append([]WorkspaceInfo(nil), workspaces...)+ c.workspaceCacheValid = true+ return append([]WorkspaceInfo(nil), workspaces...), nil+}++func (c *Client) listLegacyWorkspaces(ctx context.Context) ([]WorkspaceInfo, error) {var workspaces []WorkspaceInfoif err := c.getJSON(ctx, "/api/workspaces", &workspaces); err != nil {return nil, err@@ -503,6 +569,12 @@ func (c *Client) ListWorkspaces(ctx context.Context) ([]WorkspaceInfo, error) {return workspaces, nil}+func (c *Client) usesLegacyWorkspaceEndpoint() bool {+ c.workspaceMu.Lock()+ defer c.workspaceMu.Unlock()+ return c.legacyWorkspaceEndpointEnabled+}+// IssueGCStatus holds the minimal issue info returned by the GC check endpoint.type IssueGCStatus struct {Status string `json:"status"`diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.goindex 7878d09b22..936f1c0cad 100644--- a/server/internal/daemon/client_test.go+++ b/server/internal/daemon/client_test.go@@ -100,6 +100,81 @@ func TestClient_VersionOmittedWhenUnset(t *testing.T) {}}+func TestClient_ListWorkspacesUsesDaemonEndpointAndETag(t *testing.T) {+ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/daemon/workspaces" {+ t.Errorf("path = %q, want /api/daemon/workspaces", r.URL.Path)+ http.NotFound(w, r)+ return+ }+ call := calls.Add(1)+ if call == 1 {+ if got := r.Header.Get("If-None-Match"); got != "" {+ t.Errorf("first If-None-Match = %q, want empty", got)+ }+ w.Header().Set("ETag", `W/"workspace-v1"`)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`[{"id":"ws-1","name":"One"}]`))+ return+ }+ if got := r.Header.Get("If-None-Match"); got != `W/"workspace-v1"` {+ t.Errorf("If-None-Match = %q, want cached ETag", got)+ }+ w.WriteHeader(http.StatusNotModified)+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ first, err := c.ListWorkspaces(context.Background())+ if err != nil {+ t.Fatalf("first ListWorkspaces: %v", err)+ }+ second, err := c.ListWorkspaces(context.Background())+ if err != nil {+ t.Fatalf("second ListWorkspaces: %v", err)+ }+ if len(first) != 1 || len(second) != 1 || second[0] != first[0] {+ t.Fatalf("cached workspaces mismatch: first=%+v second=%+v", first, second)+ }+}++func TestClient_ListWorkspacesFallsBackToLegacyEndpointOnce(t *testing.T) {+ var daemonCalls atomic.Int32+ var legacyCalls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/daemon/workspaces":+ daemonCalls.Add(1)+ http.NotFound(w, r)+ case "/api/workspaces":+ legacyCalls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`[{"id":"ws-legacy","name":"Legacy"}]`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ for i := 0; i < 2; i++ {+ workspaces, err := c.ListWorkspaces(context.Background())+ if err != nil {+ t.Fatalf("ListWorkspaces call %d: %v", i+1, err)+ }+ if len(workspaces) != 1 || workspaces[0].ID != "ws-legacy" {+ t.Fatalf("workspaces = %+v, want legacy response", workspaces)+ }+ }+ if got := daemonCalls.Load(); got != 1 {+ t.Fatalf("daemon endpoint calls = %d, want 1", got)+ }+ if got := legacyCalls.Load(); got != 2 {+ t.Fatalf("legacy endpoint calls = %d, want 2", got)+ }+}+// noSleepRetry replaces retrySleep with an immediate no-op so tests don't// actually wait the 4s/8s/16s/... backoffs. Returns a restore func.func noSleepRetry(t *testing.T) func() {diff --git a/server/internal/daemon/coauthor_enabled_test.go b/server/internal/daemon/coauthor_enabled_test.goindex bac0bf3f91..175858f77d 100644--- a/server/internal/daemon/coauthor_enabled_test.go+++ b/server/internal/daemon/coauthor_enabled_test.go@@ -75,7 +75,7 @@ func TestSyncWorkspacesSkipsReposRefreshOnExistingWorkspace(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {- case "/api/workspaces":+ case "/api/daemon/workspaces":json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})case "/api/daemon/workspaces/" + workspaceID + "/repos":repoCalls.Add(1)diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex fa48bdfe77..3e35f88987 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -51,16 +51,19 @@ const (// matching tool_result would otherwise run forever. This is the backstop for// that stuck-tool case (MUL-3064). Set MULTICA_AGENT_TOOL_WATCHDOG=0 to// disable, in which case an in-flight tool never force-stops the run.- DefaultAgentToolWatchdog = 2 * time.Hour- DefaultRuntimeName = "Local Agent"- DefaultWorkspaceSyncInterval = 30 * time.Second- DefaultHealthPort = 19514- DefaultMaxConcurrentTasks = 20- DefaultGCInterval = 1 * time.Hour- DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long- DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)- DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues- DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release+ DefaultAgentToolWatchdog = 2 * time.Hour+ DefaultRuntimeName = "Local Agent"+ DefaultWorkspaceBootstrapSyncInterval = 30 * time.Second+ DefaultWorkspaceLegacySyncInterval = 5 * time.Minute+ DefaultWorkspaceSyncInterval = 30 * time.Minute+ DefaultWorkspaceSyncMaxBackoff = 30 * time.Minute+ DefaultHealthPort = 19514+ DefaultMaxConcurrentTasks = 20+ DefaultGCInterval = 1 * time.Hour+ DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long+ DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)+ DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues+ DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release)// DefaultGCArtifactPatterns lists basename matches that the GC loop treats asdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 4813c3b6ca..71883f9335 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -177,9 +177,14 @@ type Daemon struct {// reconcile fans out a "re-check server state now" signal to subscribers// (watchTaskCancellation, workspaceSyncLoop) so the WS connect/reconnect- // path can shrink the 5s / 30s reconciliation gap to sub-second. See+ // path can shrink coarse fallback reconciliation gaps to sub-second. See// reconcile.go and runTaskWakeupConnection.reconcile *reconcileBroadcaster+ // workspaceChanges is the account-scoped server hint for membership-set+ // changes. It stays separate from reconcile because a membership hint only+ // needs the minimal workspace list, while a WS reconnect also reconciles+ // runtime profiles that may have changed during the gap.+ workspaceChanges *workspaceChangeSignal// wsRPC carries generic request/response RPCs (e.g. tasks.claim, MUL-4257)// over the task-wakeup WS connection. It is attached to the live@@ -284,6 +289,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {reregisterLastCompletedAt: make(map[string]time.Time),cancelPollInterval: 5 * time.Second,reconcile: newReconcileBroadcaster(),+ workspaceChanges: newWorkspaceChangeSignal(),wsRPC: newWSRPCClient(wsRPCResponseGrace),}d.runner = taskRunnerFunc(d.runTask)@@ -1711,25 +1717,46 @@ func (d *Daemon) tryRenewToken(ctx context.Context) {}}-// workspaceSyncLoop periodically fetches the user's workspaces from the API-// and registers runtimes for any new ones. A WS connect/reconnect broadcast-// triggers an immediate sync and one runtime-profile reconciliation so changes-// made during the WS gap are picked up sub-second without putting profile-// fetches back on the 30s ticker. Repository bindings and workspace settings-// refresh on demand when a checkout needs them.+// workspaceSyncLoop reconciles the user's workspace membership set. Daemons+// with runtimes and account-scoped WS support use a thirty-minute jittered+// consistency check; daemons talking to older servers retain a five-minute+// fallback. Bootstrap daemons without runtimes keep the shorter interval needed+// to discover their first workspace. Account-scoped WS hints trigger an+// immediate minimal sync, while a WS reconnect also reconciles runtime profiles+// changed during the connection gap.func (d *Daemon) workspaceSyncLoop(ctx context.Context) {- ticker := time.NewTicker(DefaultWorkspaceSyncInterval)- defer ticker.Stop()+ timer := time.NewTimer(jitterDuration(d.workspaceSyncBaseInterval()))+ defer timer.Stop()var reconcileCh <-chan struct{}if d.reconcile != nil {reconcileCh = d.reconcile.notify()}+ var workspaceChangesCh <-chan struct{}+ if d.workspaceChanges != nil {+ workspaceChangesCh = d.workspaceChanges.notify()+ }- sync := func(reconcileProfiles bool) {+ var consecutiveFailures int+ resetTimer := func() {+ interval := workspaceSyncBackoff(d.workspaceSyncBaseInterval(), consecutiveFailures)+ if !timer.Stop() {+ select {+ case <-timer.C:+ default:+ }+ }+ timer.Reset(jitterDuration(interval))+ }++ syncNow := func(reconcileProfiles bool) {if err := d.syncWorkspacesFromAPI(ctx, reconcileProfiles); err != nil {+ consecutiveFailures++d.logger.Debug("workspace sync failed", "error", err)+ } else {+ consecutiveFailures = 0}+ resetTimer()}for {@@ -1740,19 +1767,50 @@ func (d *Daemon) workspaceSyncLoop(ctx context.Context) {if d.reconcile != nil {reconcileCh = d.reconcile.notify()}- sync(true)- case <-ticker.C:- sync(false)+ syncNow(true)+ case <-workspaceChangesCh:+ syncNow(false)+ case <-timer.C:+ syncNow(false)}}}+func (d *Daemon) workspaceSyncBaseInterval() time.Duration {+ if len(d.allRuntimeIDs()) == 0 {+ return DefaultWorkspaceBootstrapSyncInterval+ }+ if d.client.usesLegacyWorkspaceEndpoint() {+ return DefaultWorkspaceLegacySyncInterval+ }+ return DefaultWorkspaceSyncInterval+}++func workspaceSyncBackoff(base time.Duration, consecutiveFailures int) time.Duration {+ maxInterval := DefaultWorkspaceSyncMaxBackoff+ if base == DefaultWorkspaceBootstrapSyncInterval {+ maxInterval = DefaultWorkspaceLegacySyncInterval+ }+ interval := base+ for i := 0; i < consecutiveFailures; i++ {+ if interval >= maxInterval/2 {+ return maxInterval+ }+ interval *= 2+ }+ if interval > maxInterval {+ return maxInterval+ }+ return interval+}+// syncWorkspacesFromAPI fetches all workspaces the user belongs to and// registers runtimes for any that aren't already tracked. When// reconcileProfiles is true (after a daemon WS connect/reconnect), tracked// workspaces reconcile custom runtime profiles once so a change made while the-// WS was unavailable is not lost. The normal 30s ticker passes false and makes-// no runtime-profile requests. Workspaces the user has left are cleaned up.+// WS was unavailable is not lost. Normal timers and workspace-change hints+// pass false and make no runtime-profile requests. Workspaces the user has+// left are cleaned up.func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bool) error {d.reloading.Lock()defer d.reloading.Unlock()diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 836fd153e8..dd8ae756c6 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -2620,21 +2620,21 @@ func TestWatchTaskCancellation_ReconcileWithRunningTaskStaysAlive(t *testing.T)}// TestWorkspaceSyncLoop_ReconcileBroadcastTriggersImmediateSync pins that the-// 30s workspace sync ticker is also short-circuited by reconcile broadcasts.-// Without this, runtime/repo changes the server made during a WS disconnect-// stay invisible to the daemon for up to 30 seconds.+// long-period workspace consistency timer is short-circuited by reconnect+// broadcasts. Without this, changes made during a WS disconnect stay invisible+// until the next fallback sync.func TestWorkspaceSyncLoop_ReconcileBroadcastTriggersImmediateSync(t *testing.T) {t.Parallel()var calls atomic.Int32srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/api/workspaces" {+ if r.URL.Path != "/api/daemon/workspaces" {http.NotFound(w, r)return}calls.Add(1)w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"workspaces":[]}`))+ _, _ = w.Write([]byte(`[]`))}))t.Cleanup(srv.Close)@@ -2687,6 +2687,132 @@ func TestWorkspaceSyncLoop_ReconcileBroadcastTriggersImmediateSync(t *testing.T)}}+func TestWorkspaceSyncLoop_WorkspaceChangeTriggersImmediateSync(t *testing.T) {+ t.Parallel()++ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/daemon/workspaces" {+ http.NotFound(w, r)+ return+ }+ calls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`[]`))+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.Default(),+ workspaces: make(map[string]*workspaceState),+ workspaceChanges: newWorkspaceChangeSignal(),+ }++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ loopDone := make(chan struct{})+ go func() {+ defer close(loopDone)+ d.workspaceSyncLoop(ctx)+ }()++ d.workspaceChanges.broadcast()+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) && calls.Load() < 1 {+ time.Sleep(10 * time.Millisecond)+ }+ if calls.Load() < 1 {+ cancel()+ <-loopDone+ t.Fatal("workspace change did not trigger an immediate sync")+ }++ cancel()+ <-loopDone+}++// TestWorkspaceSyncLoop_DoesNotDropChangeAfterSuccessfulSync covers the+// request-changes race from MUL-4480: a real membership hint arriving within+// one second of a completed sync must trigger another sync, not be treated as+// a duplicate of the earlier read and deferred to the 30-minute fallback.+func TestWorkspaceSyncLoop_DoesNotDropChangeAfterSuccessfulSync(t *testing.T) {+ t.Parallel()++ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/daemon/workspaces" {+ http.NotFound(w, r)+ return+ }+ calls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`[]`))+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.Default(),+ workspaces: make(map[string]*workspaceState),+ workspaceChanges: newWorkspaceChangeSignal(),+ }++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ loopDone := make(chan struct{})+ go func() {+ defer close(loopDone)+ d.workspaceSyncLoop(ctx)+ }()++ waitForCalls := func(want int32) {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) && calls.Load() < want {+ time.Sleep(10 * time.Millisecond)+ }+ if got := calls.Load(); got < want {+ t.Fatalf("workspace sync calls = %d, want at least %d", got, want)+ }+ }++ d.workspaceChanges.broadcast()+ waitForCalls(1)+ deadline := time.Now().Add(time.Second)+ for !d.reloading.TryLock() {+ if time.Now().After(deadline) {+ t.Fatal("first workspace sync did not finish")+ }+ time.Sleep(time.Millisecond)+ }+ d.reloading.Unlock()+ // The second edge lands immediately after a successful API read. It+ // represents a later commit and therefore cannot be coalesced backward.+ d.workspaceChanges.broadcast()+ waitForCalls(2)++ cancel()+ <-loopDone+}++func TestWorkspaceSyncBackoff(t *testing.T) {+ tests := []struct {+ failures int+ want time.Duration+ }{+ {failures: 0, want: 30 * time.Second},+ {failures: 1, want: time.Minute},+ {failures: 2, want: 2 * time.Minute},+ {failures: 10, want: DefaultWorkspaceLegacySyncInterval},+ }+ for _, tt := range tests {+ if got := workspaceSyncBackoff(30*time.Second, tt.failures); got != tt.want {+ t.Fatalf("workspaceSyncBackoff(30s, %d) = %s, want %s", tt.failures, got, tt.want)+ }+ }+}+// TestWorkspaceSyncLoop_ReplaysBroadcastFromBeforeStart pins the daemon-// startup race fix: broadcast() that fired while no one was subscribed// MUST still wake the loop on its first subscription. Without the@@ -2698,13 +2824,13 @@ func TestWorkspaceSyncLoop_ReplaysBroadcastFromBeforeStart(t *testing.T) {var calls atomic.Int32srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/api/workspaces" {+ if r.URL.Path != "/api/daemon/workspaces" {http.NotFound(w, r)return}calls.Add(1)w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"workspaces":[]}`))+ _, _ = w.Write([]byte(`[]`))}))t.Cleanup(srv.Close)diff --git a/server/internal/daemon/reconcile.go b/server/internal/daemon/reconcile.goindex 3bf2c18b60..0f2e7fe46f 100644--- a/server/internal/daemon/reconcile.go+++ b/server/internal/daemon/reconcile.go@@ -96,3 +96,34 @@ func (b *reconcileBroadcaster) broadcast() bool {b.ch = make(chan struct{})return true}++// workspaceChangeSignal is a single-consumer dirty flag for workspace-set+// changes. The one-slot buffer preserves an event that arrives before the sync+// loop starts or while an API read is in flight, while coalescing any larger+// burst into one trailing reconciliation of the latest server state.+type workspaceChangeSignal struct {+ ch chan struct{}+}++func newWorkspaceChangeSignal() *workspaceChangeSignal {+ return &workspaceChangeSignal{ch: make(chan struct{}, 1)}+}++func (s *workspaceChangeSignal) notify() <-chan struct{} {+ if s == nil {+ return nil+ }+ return s.ch+}++func (s *workspaceChangeSignal) broadcast() bool {+ if s == nil {+ return false+ }+ select {+ case s.ch <- struct{}{}:+ return true+ default:+ return false+ }+}diff --git a/server/internal/daemon/reconcile_test.go b/server/internal/daemon/reconcile_test.goindex 2ae15dfe61..07487d04eb 100644--- a/server/internal/daemon/reconcile_test.go+++ b/server/internal/daemon/reconcile_test.go@@ -179,6 +179,25 @@ func TestReconcileBroadcaster_ReSubscribesEachWake(t *testing.T) {}}+func TestWorkspaceChangeSignalCoalescesUntilConsumed(t *testing.T) {+ s := newWorkspaceChangeSignal()+ if !s.broadcast() {+ t.Fatal("first workspace change was not recorded")+ }+ if s.broadcast() {+ t.Fatal("duplicate workspace change should coalesce while dirty")+ }++ select {+ case <-s.notify():+ case <-time.After(time.Second):+ t.Fatal("recorded workspace change was not delivered")+ }+ if !s.broadcast() {+ t.Fatal("workspace change after consumption was not recorded")+ }+}+// TestReconcileBroadcaster_ConcurrentBroadcastAndNotify exercises the lock// boundary: heavy concurrent notify/broadcast traffic must not panic, dead-// lock, or fail under the race detector. Run with `go test -race`.diff --git a/server/internal/daemon/runtime_profile_drift_test.go b/server/internal/daemon/runtime_profile_drift_test.goindex 0339826d80..f0a772ad98 100644--- a/server/internal/daemon/runtime_profile_drift_test.go+++ b/server/internal/daemon/runtime_profile_drift_test.go@@ -218,7 +218,7 @@ func TestSyncWorkspacesSkipsRuntimeProfileRefreshOnExistingWorkspace(t *testing.srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {- case "/api/workspaces":+ case "/api/daemon/workspaces":w.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})case "/api/daemon/workspaces/" + workspaceID + "/runtime-profiles":@@ -258,7 +258,7 @@ func TestSyncWorkspacesRefreshesRuntimeProfilesOnReconcile(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {- case "/api/workspaces":+ case "/api/daemon/workspaces":w.Header().Set("Content-Type", "application/json")_ = json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})case "/api/daemon/workspaces/" + workspaceID + "/runtime-profiles":diff --git a/server/internal/daemon/token_renewal_test.go b/server/internal/daemon/token_renewal_test.goindex fdc8a54198..e31c744546 100644--- a/server/internal/daemon/token_renewal_test.go+++ b/server/internal/daemon/token_renewal_test.go@@ -212,7 +212,7 @@ func TestPreflightAuth_RenewsBeforeWorkspaceSyncOnExpiredToken(t *testing.T) {if seen[0] != "/api/tokens/current/renew" {t.Fatalf("renew must be the first API call so the WARN fires before the sync 401s; got order %v", seen)}- if seen[1] != "/api/workspaces" {+ if seen[1] != "/api/daemon/workspaces" {t.Fatalf("workspace sync should follow renew; got order %v", seen)}out := buf.String()@@ -238,7 +238,7 @@ func TestPreflightAuth_SyncProceedsWhenRenewIsNoOp(t *testing.T) {"expires_at": "2099-01-02T03:04:05Z","renewed": false,})- case "/api/workspaces":+ case "/api/daemon/workspaces":syncCalled.Store(true)w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`[]`))@@ -271,7 +271,7 @@ func TestPreflightAuth_TransientRenewFailureDoesNotBlockStartup(t *testing.T) {case "/api/tokens/current/renew":w.WriteHeader(http.StatusInternalServerError)_, _ = w.Write([]byte(`{"error":"db down"}`))- case "/api/workspaces":+ case "/api/daemon/workspaces":syncCalled.Store(true)w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`[]`))diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex b7219290e2..ff09b8e3b7 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -38,13 +38,6 @@ func (d *Daemon) taskWakeupLoop(ctx context.Context, taskWakeups chan<- taskWakefor {runtimeIDs := d.allRuntimeIDs()- if len(runtimeIDs) == 0 {- if err := sleepWithContextOrRuntimeChange(ctx, 5*time.Second, runtimeSetCh); err != nil {- return- }- continue- }-connectedFor, err := d.runTaskWakeupConnection(ctx, runtimeIDs, taskWakeups, runtimeSetCh)if ctx.Err() != nil {return@@ -379,6 +372,10 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-continue}go d.handleRuntimeProfilesChanged(payload)+ case protocol.EventDaemonWorkspacesChanged:+ if d.workspaceChanges != nil {+ d.workspaceChanges.broadcast()+ }case protocol.EventDaemonHeartbeatAck:var ack HeartbeatResponseif err := json.Unmarshal(msg.Payload, &ack); err != nil {@@ -456,7 +453,9 @@ func taskWakeupURL(baseURL string, runtimeIDs []string) (string, error) {q := u.Query()ids := append([]string(nil), runtimeIDs...)sort.Strings(ids)- q.Set("runtime_ids", strings.Join(ids, ","))+ if len(ids) > 0 {+ q.Set("runtime_ids", strings.Join(ids, ","))+ }u.RawQuery = q.Encode()u.Fragment = ""return u.String(), nildiff --git a/server/internal/daemon/wakeup_test.go b/server/internal/daemon/wakeup_test.goindex 70d44231db..4cf9b4131f 100644--- a/server/internal/daemon/wakeup_test.go+++ b/server/internal/daemon/wakeup_test.go@@ -42,6 +42,12 @@ func TestTaskWakeupURL(t *testing.T) {runtimeIDs: []string{"runtime-1"},want: "wss://api.example.com/multica/api/daemon/ws?runtime_ids=runtime-1",},+ {+ name: "account-only connection",+ baseURL: "https://api.example.com",+ runtimeIDs: nil,+ want: "wss://api.example.com/api/daemon/ws",+ },}for _, tt := range tests {diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex aed9ae1567..d5b20f32a1 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -190,6 +190,7 @@ type Hub struct {clients map[*client]boolbyRuntime map[string]map[*client]boolbyWorkspace map[string]map[*client]bool+ byUser map[string]map[*client]boolhbMu sync.RWMutexonHeartbeat HeartbeatHandler@@ -214,6 +215,7 @@ func NewHub() *Hub {clients: make(map[*client]bool),byRuntime: make(map[string]map[*client]bool),byWorkspace: make(map[string]map[*client]bool),+ byUser: make(map[string]map[*client]bool),}}@@ -277,8 +279,8 @@ func (h *Hub) messageKindRecorder() MessageKindRecorder {}func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity ClientIdentity) {- if len(identity.RuntimeIDs) == 0 {- http.Error(w, `{"error":"runtime_ids required"}`, http.StatusBadRequest)+ if len(identity.RuntimeIDs) == 0 && identity.UserID == "" {+ http.Error(w, `{"error":"runtime_ids or user identity required"}`, http.StatusBadRequest)return}@@ -294,12 +296,6 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity Cruntimes[runtimeID] = struct{}{}}}- if len(runtimes) == 0 {- conn.WriteMessage(websocket.TextMessage, []byte(`{"error":"runtime_ids required"}`))- conn.Close()- return- }-c := &client{hub: h,conn: conn,@@ -326,6 +322,12 @@ func (h *Hub) NotifyRuntimeProfilesChanged(workspaceID, profileID string) {h.notifyRuntimeProfilesChanged(workspaceID, profileID, "")}+// NotifyWorkspacesChanged asks every connected daemon authenticated as userID+// to reconcile its workspace membership set.+func (h *Hub) NotifyWorkspacesChanged(userID string) {+ h.notifyWorkspacesChanged(userID, "")+}+func (h *Hub) notifyTaskAvailable(runtimeID, taskID, eventID string) {if h == nil || runtimeID == "" {return@@ -353,6 +355,17 @@ func (h *Hub) notifyRuntimeProfilesChanged(workspaceID, profileID, eventID strinh.notifyWorkspaceFrame(workspaceID, data, eventID)}+func (h *Hub) notifyWorkspacesChanged(userID, eventID string) {+ if h == nil || userID == "" {+ return+ }+ data, err := workspacesChangedFrame()+ if err != nil {+ return+ }+ h.notifyUserFrame(userID, data, eventID)+}+func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string) {if h == nil {return@@ -391,6 +404,13 @@ func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)} else if !deduped {M.WakeupDeliveredMiss.Add(1)}+ case protocol.EventDaemonWorkspacesChanged:+ delivered, deduped := h.notifyUserFrame(scopeID, frame, eventID)+ if delivered {+ M.WakeupDeliveredHit.Add(1)+ } else if !deduped {+ M.WakeupDeliveredMiss.Add(1)+ }default:M.WakeupDeliveredMiss.Add(1)return@@ -453,6 +473,34 @@ func (h *Hub) notifyWorkspaceFrame(workspaceID string, data []byte, eventID strireturn delivered, deduped}+func (h *Hub) notifyUserFrame(userID string, data []byte, eventID string) (delivered bool, deduped bool) {+ h.mu.RLock()+ clients := h.byUser[userID]+ slow := make([]*client, 0)+ for c := range clients {+ if !c.markSeen(eventID) {+ deduped = true+ continue+ }+ select {+ case c.send <- data:+ delivered = true+ default:+ slow = append(slow, c)+ }+ }+ h.mu.RUnlock()++ for _, c := range slow {+ h.unregister(c)+ c.conn.Close()+ }+ if len(slow) > 0 {+ M.SlowEvictionsTotal.Add(int64(len(slow)))+ }+ return delivered, deduped+}+func taskAvailableFrame(runtimeID, taskID string) ([]byte, error) {return json.Marshal(protocol.Message{Type: protocol.EventDaemonTaskAvailable,@@ -473,6 +521,13 @@ func runtimeProfilesChangedFrame(workspaceID, profileID string) ([]byte, error)})}+func workspacesChangedFrame() ([]byte, error) {+ return json.Marshal(protocol.Message{+ Type: protocol.EventDaemonWorkspacesChanged,+ Payload: mustMarshalRaw(protocol.WorkspacesChangedPayload{}),+ })+}+func mustMarshalRaw(v any) json.RawMessage {data, err := json.Marshal(v)if err != nil {@@ -493,6 +548,12 @@ func (h *Hub) WorkspaceConnectionCount(workspaceID string) int {return len(h.byWorkspace[workspaceID])}+func (h *Hub) UserConnectionCount(userID string) int {+ h.mu.RLock()+ defer h.mu.RUnlock()+ return len(h.byUser[userID])+}+func (h *Hub) register(c *client) {h.mu.Lock()h.clients[c] = true@@ -513,6 +574,14 @@ func (h *Hub) register(c *client) {}conns[c] = true}+ if userID := c.identity.UserID; userID != "" {+ conns := h.byUser[userID]+ if conns == nil {+ conns = make(map[*client]bool)+ h.byUser[userID] = conns+ }+ conns[c] = true+ }total := len(h.clients)h.mu.Unlock()@@ -553,6 +622,14 @@ func (h *Hub) unregister(c *client) {}}}+ if userID := c.identity.UserID; userID != "" {+ if conns := h.byUser[userID]; conns != nil {+ delete(conns, c)+ if len(conns) == 0 {+ delete(h.byUser, userID)+ }+ }+ }c.sendMu.Lock()c.sendClosed = trueclose(c.send)diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.goindex a9160f92c1..00349a8d91 100644--- a/server/internal/daemonws/hub_test.go+++ b/server/internal/daemonws/hub_test.go@@ -122,6 +122,49 @@ func TestNotifyRuntimeProfilesChanged(t *testing.T) {}}+func TestNotifyWorkspacesChangedSupportsAccountOnlyConnection(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hub.HandleWebSocket(w, r, ClientIdentity{UserID: "user-1"})+ }))+ defer server.Close()++ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("Dial: %v", err)+ }+ defer conn.Close()++ deadline := time.Now().Add(time.Second)+ for hub.UserConnectionCount("user-1") == 0 {+ if time.Now().After(deadline) {+ t.Fatal("user connection was not registered")+ }+ time.Sleep(10 * time.Millisecond)+ }++ hub.NotifyWorkspacesChanged("user-1")++ if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("ReadMessage: %v", err)+ }+ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal message: %v", err)+ }+ if msg.Type != protocol.EventDaemonWorkspacesChanged {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonWorkspacesChanged)+ }+}+func TestNotifyRuntimeProfilesChangedIndexesAllAuthorizedWorkspaces(t *testing.T) {M.Reset()defer M.Reset()@@ -261,6 +304,33 @@ func TestRelayNotifierPublishesRuntimeProfilesChanged(t *testing.T) {}}+func TestRelayNotifierPublishesWorkspacesChanged(t *testing.T) {+ M.Reset()+ defer M.Reset()++ relay := &recordingRelayPublisher{}+ notifier := NewRelayNotifier(nil, relay)++ notifier.NotifyWorkspacesChanged("user-1")++ if relay.scopeType != realtime.ScopeDaemonRuntime {+ t.Fatalf("scopeType = %q, want %q", relay.scopeType, realtime.ScopeDaemonRuntime)+ }+ if relay.scopeID != "user-1" {+ t.Fatalf("scopeID = %q, want user shard key", relay.scopeID)+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ var msg protocol.Message+ if err := json.Unmarshal(relay.frame, &msg); err != nil {+ t.Fatalf("unmarshal frame: %v", err)+ }+ if msg.Type != protocol.EventDaemonWorkspacesChanged {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonWorkspacesChanged)+ }+}+func TestRelayNotifierDedupsLocalRedisLoopback(t *testing.T) {M.Reset()defer M.Reset()@@ -333,6 +403,28 @@ func TestRelayNotifierDedupsRuntimeProfilesChangedLoopback(t *testing.T) {}}+func TestRelayNotifierDedupsWorkspacesChangedLoopback(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ client := attachDaemonUserTestClient(hub, "user-1")+ relay := &localFirstDaemonRelayPublisher{t: t, client: client}+ notifier := NewRelayNotifier(hub, relay)++ notifier.NotifyWorkspacesChanged("user-1")+ if !relay.called || relay.eventID == "" {+ t.Fatal("expected local delivery followed by relay publish")+ }++ hub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)+ select {+ case duplicate := <-client.send:+ t.Fatalf("expected redis loopback to be deduped, got duplicate %s", duplicate)+ case <-time.After(20 * time.Millisecond):+ }+}+// TestHeartbeatRoundTrip pins the WS heartbeat contract: a daemon:heartbeat// frame invokes the registered HeartbeatHandler with the runtime ID, and the// hub serializes the returned ack as a daemon:heartbeat_ack on the wire.@@ -553,6 +645,21 @@ func attachDaemonWorkspaceTestClient(hub *Hub, workspaceID string) *client {return c}+func attachDaemonUserTestClient(hub *Hub, userID string) *client {+ c := &client{+ send: make(chan []byte, 2),+ identity: ClientIdentity{UserID: userID},+ runtimes: map[string]struct{}{},+ }++ hub.mu.Lock()+ hub.clients[c] = true+ hub.byUser[userID] = map[*client]bool{c: true}+ hub.mu.Unlock()++ return c+}+type recordingRelayPublisher struct {scopeType stringscopeID stringdiff --git a/server/internal/daemonws/notifier.go b/server/internal/daemonws/notifier.goindex f66f4b623d..f3910ad320 100644--- a/server/internal/daemonws/notifier.go+++ b/server/internal/daemonws/notifier.go@@ -71,3 +71,31 @@ func (n *RelayNotifier) NotifyRuntimeProfilesChanged(workspaceID, profileID stri}M.WakeupPublishedTotal.Add(1)}++func (n *RelayNotifier) NotifyWorkspacesChanged(userID string) {+ if userID == "" {+ return+ }+ eventID := ulid.Make().String()+ if n.local != nil {+ n.local.notifyWorkspacesChanged(userID, eventID)+ }+ if n.relay == nil {+ return+ }+ frame, err := workspacesChangedFrame()+ if err != nil {+ M.WakeupPublishErrors.Add(1)+ return+ }+ // ScopeDaemonRuntime is the relay's daemon-only transport scope; the frame+ // type tells Hub.DeliverDaemonRuntime whether scopeID is a runtime,+ // workspace, or user key. Keeping one transport scope preserves compatibility+ // with existing relay consumers while the hub enforces user-scoped delivery.+ if err := n.relay.PublishWithID(realtime.ScopeDaemonRuntime, userID, "", frame, eventID); err != nil {+ M.WakeupPublishErrors.Add(1)+ slog.Warn("daemon websocket workspace refresh publish failed", "error", err, "user_id", userID)+ return+ }+ M.WakeupPublishedTotal.Add(1)+}diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 1f665dca5a..ed75819655 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -120,6 +120,58 @@ func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonIDreturn req.WithContext(ctx)}+func TestListDaemonWorkspaces_UserScopedAndConditional(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest(http.MethodGet, "/api/daemon/workspaces", nil)+ testHandler.ListDaemonWorkspaces(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ListDaemonWorkspaces: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var workspaces []DaemonWorkspaceResponse+ if err := json.NewDecoder(w.Body).Decode(&workspaces); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(workspaces) == 0 {+ t.Fatal("expected at least one daemon workspace")+ }+ if workspaces[0].ID == "" || workspaces[0].Name == "" {+ t.Fatalf("expected minimal id/name projection, got %+v", workspaces[0])+ }+ etag := w.Header().Get("ETag")+ if etag == "" {+ t.Fatal("expected ETag")+ }++ w = httptest.NewRecorder()+ req = newRequest(http.MethodGet, "/api/daemon/workspaces", nil)+ req.Header.Set("If-None-Match", etag)+ testHandler.ListDaemonWorkspaces(w, req)+ if w.Code != http.StatusNotModified {+ t.Fatalf("conditional ListDaemonWorkspaces: expected 304, got %d: %s", w.Code, w.Body.String())+ }+ if w.Body.Len() != 0 {+ t.Fatalf("expected empty 304 body, got %q", w.Body.String())+ }+}++func TestListDaemonWorkspaces_DaemonTokenIsWorkspaceScoped(t *testing.T) {+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/workspaces", nil, testWorkspaceID, "daemon-test")+ testHandler.ListDaemonWorkspaces(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ListDaemonWorkspaces: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var workspaces []DaemonWorkspaceResponse+ if err := json.NewDecoder(w.Body).Decode(&workspaces); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(workspaces) != 1 || workspaces[0].ID != testWorkspaceID {+ t.Fatalf("daemon-token workspaces = %+v, want only %s", workspaces, testWorkspaceID)+ }+}+func createClaimReclaimRuntime(t *testing.T, ctx context.Context, name string) string {t.Helper()diff --git a/server/internal/handler/daemon_workspace.go b/server/internal/handler/daemon_workspace.gonew file mode 100644index 0000000000..52093ccf31--- /dev/null+++ b/server/internal/handler/daemon_workspace.go@@ -0,0 +1,66 @@+package handler++import (+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/middleware"+)++type DaemonWorkspaceResponse struct {+ ID string `json:"id"`+ Name string `json:"name"`+}++// ListDaemonWorkspaces returns the minimal workspace membership projection+// needed by local daemons. User-scoped PAT/JWT callers receive every workspace+// they belong to; workspace-scoped daemon tokens receive only their bound+// workspace.+func (h *Handler) ListDaemonWorkspaces(w http.ResponseWriter, r *http.Request) {+ var resp []DaemonWorkspaceResponse+ if userID := requestUserID(r); userID != "" {+ rows, err := h.Queries.ListDaemonWorkspaces(r.Context(), parseUUID(userID))+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list daemon workspaces")+ return+ }+ resp = make([]DaemonWorkspaceResponse, len(rows))+ for i, row := range rows {+ resp[i] = daemonWorkspaceToResponse(row.ID, row.Name)+ }+ } else {+ workspaceID := middleware.DaemonWorkspaceIDFromContext(r.Context())+ if workspaceID == "" {+ writeError(w, http.StatusUnauthorized, "daemon workspace identity required")+ return+ }+ row, err := h.Queries.GetDaemonWorkspace(r.Context(), parseUUID(workspaceID))+ if err != nil {+ writeError(w, http.StatusNotFound, "workspace not found")+ return+ }+ resp = []DaemonWorkspaceResponse{daemonWorkspaceToResponse(row.ID, row.Name)}+ }++ etag := daemonWorkspacesETag(resp)+ w.Header().Set("Cache-Control", "private, no-cache")+ w.Header().Set("ETag", etag)+ if r.Header.Get("If-None-Match") == etag {+ w.WriteHeader(http.StatusNotModified)+ return+ }+ writeJSON(w, http.StatusOK, resp)+}++func daemonWorkspaceToResponse(id pgtype.UUID, name string) DaemonWorkspaceResponse {+ return DaemonWorkspaceResponse{ID: uuidToString(id), Name: name}+}++func daemonWorkspacesETag(workspaces []DaemonWorkspaceResponse) string {+ data, _ := json.Marshal(workspaces)+ sum := sha256.Sum256(data)+ return fmt.Sprintf(`W/"%x"`, sum)+}diff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.goindex 11e8c9f23f..89d78f5f31 100644--- a/server/internal/handler/daemon_ws.go+++ b/server/internal/handler/daemon_ws.go@@ -15,8 +15,9 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {}runtimeIDs := parseRuntimeIDs(r)- if len(runtimeIDs) == 0 {- writeError(w, http.StatusBadRequest, "runtime_ids required")+ userID := requestUserID(r)+ if len(runtimeIDs) == 0 && userID == "" {+ writeError(w, http.StatusBadRequest, "runtime_ids or user identity required")return}@@ -47,7 +48,7 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {h.DaemonHub.HandleWebSocket(w, r, daemonws.ClientIdentity{DaemonID: middleware.DaemonIDFromContext(r.Context()),- UserID: requestUserID(r),+ UserID: userID,WorkspaceID: primaryWorkspaceID,WorkspaceIDs: workspaceIDs,RuntimeIDs: runtimeIDs,diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex b31e71d88d..9dd8a1a8bd 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -118,28 +118,33 @@ type RuntimeProfileRefreshNotifier interface {NotifyRuntimeProfilesChanged(workspaceID, profileID string)}+type WorkspaceSetRefreshNotifier interface {+ NotifyWorkspacesChanged(userID string)+}+type Handler struct {- Queries *db.Queries- DB dbExecutor- TxStarter txStarter- Hub *realtime.Hub- DaemonHub *daemonws.Hub- DaemonProfileRefresh RuntimeProfileRefreshNotifier- Bus *events.Bus- TaskService *service.TaskService- IssueService *service.IssueService- AutopilotService *service.AutopilotService- EmailService *service.EmailService- UpdateStore UpdateStore- ModelListStore ModelListStore- LocalSkillListStore LocalSkillListStore- LocalSkillImportStore LocalSkillImportStore- FeatureFlags *featureflag.Service- LivenessStore LivenessStore- HeartbeatScheduler HeartbeatScheduler- Storage storage.Storage- CFSigner *auth.CloudFrontSigner- Analytics analytics.Client+ Queries *db.Queries+ DB dbExecutor+ TxStarter txStarter+ Hub *realtime.Hub+ DaemonHub *daemonws.Hub+ DaemonProfileRefresh RuntimeProfileRefreshNotifier+ DaemonWorkspaceRefresh WorkspaceSetRefreshNotifier+ Bus *events.Bus+ TaskService *service.TaskService+ IssueService *service.IssueService+ AutopilotService *service.AutopilotService+ EmailService *service.EmailService+ UpdateStore UpdateStore+ ModelListStore ModelListStore+ LocalSkillListStore LocalSkillListStore+ LocalSkillImportStore LocalSkillImportStore+ FeatureFlags *featureflag.Service+ LivenessStore LivenessStore+ HeartbeatScheduler HeartbeatScheduler+ Storage storage.Storage+ CFSigner *auth.CloudFrontSigner+ Analytics analytics.Client// Metrics is the shared business-metrics collector built by main.go.// May be nil in tests / self-hosted with the metrics listener disabled;// every Record* method is nil-safe and obsmetrics.RecordEvent treats a@@ -243,35 +248,38 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventdaemonHub = daemonHubs[0]}var daemonProfileRefresh RuntimeProfileRefreshNotifier+ var daemonWorkspaceRefresh WorkspaceSetRefreshNotifierif daemonHub != nil {daemonProfileRefresh = daemonHub+ daemonWorkspaceRefresh = daemonHub}taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)taskSvc.Analytics = analyticsClientreturn &Handler{- Queries: queries,- DB: executor,- TxStarter: txStarter,- Hub: hub,- DaemonHub: daemonHub,- DaemonProfileRefresh: daemonProfileRefresh,- Bus: bus,- TaskService: taskSvc,- IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),- AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),- EmailService: emailService,- UpdateStore: NewInMemoryUpdateStore(),- ModelListStore: NewInMemoryModelListStore(),- LocalSkillListStore: NewInMemoryLocalSkillListStore(),- LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),- LivenessStore: NewNoopLivenessStore(),- HeartbeatScheduler: NewPassthroughHeartbeatScheduler(queries),- Storage: store,- CFSigner: cfSigner,- Analytics: analyticsClient,- WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),- WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),+ Queries: queries,+ DB: executor,+ TxStarter: txStarter,+ Hub: hub,+ DaemonHub: daemonHub,+ DaemonProfileRefresh: daemonProfileRefresh,+ DaemonWorkspaceRefresh: daemonWorkspaceRefresh,+ Bus: bus,+ TaskService: taskSvc,+ IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),+ AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),+ EmailService: emailService,+ UpdateStore: NewInMemoryUpdateStore(),+ ModelListStore: NewInMemoryModelListStore(),+ LocalSkillListStore: NewInMemoryLocalSkillListStore(),+ LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),+ LivenessStore: NewNoopLivenessStore(),+ HeartbeatScheduler: NewPassthroughHeartbeatScheduler(queries),+ Storage: store,+ CFSigner: cfSigner,+ Analytics: analyticsClient,+ WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),+ WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),CloudRuntime: cloudruntime.NewClient(cloudruntime.Config{BaseURL: cfg.CloudRuntimeFleetURL,Timeout: cfg.CloudRuntimeFleetTimeout,@@ -425,6 +433,23 @@ func (h *Handler) publish(eventType, workspaceID, actorType, actorID string, pay})}+func (h *Handler) notifyDaemonWorkspacesChanged(userIDs ...string) {+ if h.DaemonWorkspaceRefresh == nil {+ return+ }+ seen := make(map[string]struct{}, len(userIDs))+ for _, userID := range userIDs {+ if userID == "" {+ continue+ }+ if _, ok := seen[userID]; ok {+ continue+ }+ seen[userID] = struct{}{}+ h.DaemonWorkspaceRefresh.NotifyWorkspacesChanged(userID)+ }+}+// publishTask is publish() plus a TaskID hint so the realtime layer can route// the event to the per-task scope rather than the whole workspace.func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID string, payload any) {diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex aaa13518ae..c020ffb72b 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -465,6 +465,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {"invitation_id": uuidToString(accepted.ID),"member": memberResp,})+ h.notifyDaemonWorkspacesChanged(userID)// days_since_invite rounds down to whole days so the funnel segments// "accepted same day" cleanly from "accepted later". inv.CreatedAt isdiff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 2496087b5e..7176ced75f 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -235,6 +235,7 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {// emit time. Stamping here would race under concurrent creates without// a schema change, and the event stream answers the question exactly.obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.WorkspaceCreated(userID, wsID))+ h.notifyDaemonWorkspacesChanged(userID)slog.Info("workspace created", append(logger.RequestAttrs(r), "workspace_id", wsID, "name", ws.Name, "slug", ws.Slug)...)writeJSON(w, http.StatusCreated, workspaceToResponse(ws))@@ -353,6 +354,15 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {slog.Info("workspace updated", append(logger.RequestAttrs(r), "workspace_id", id)...)userID := requestUserID(r)h.publish(protocol.EventWorkspaceUpdated, uuidToString(ws.ID), "member", userID, map[string]any{"workspace": workspaceToResponse(ws)})+ if req.Name != nil {+ if members, err := h.Queries.ListMembers(r.Context(), ws.ID); err == nil {+ userIDs := make([]string, 0, len(members))+ for _, member := range members {+ userIDs = append(userIDs, uuidToString(member.UserID))+ }+ h.notifyDaemonWorkspacesChanged(userIDs...)+ }+ }writeJSON(w, http.StatusOK, workspaceToResponse(ws))}@@ -520,6 +530,7 @@ func (h *Handler) CreateMember(w http.ResponseWriter, r *http.Request) {eventPayload["workspace_name"] = ws.Name}h.publish(protocol.EventMemberAdded, uuidToString(requester.WorkspaceID), "member", userID, eventPayload)+ h.notifyDaemonWorkspacesChanged(uuidToString(user.ID))writeJSON(w, http.StatusCreated, memberWithUserResponse(member, user))}@@ -659,6 +670,7 @@ func (h *Handler) DeleteMember(w http.ResponseWriter, r *http.Request) {"workspace_id": wsIDStr,"user_id": uuidToString(target.UserID),})+ h.notifyDaemonWorkspacesChanged(uuidToString(target.UserID))w.WriteHeader(http.StatusNoContent)}@@ -701,6 +713,7 @@ func (h *Handler) LeaveWorkspace(w http.ResponseWriter, r *http.Request) {"workspace_id": workspaceID,"user_id": uuidToString(member.UserID),})+ h.notifyDaemonWorkspacesChanged(uuidToString(member.UserID))w.WriteHeader(http.StatusNoContent)}@@ -725,9 +738,13 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {// After CASCADE deletes the member rows, cache entries become harmless// orphans (downstream lookups for the deleted workspace will fail), but// proactive invalidation prevents any stale-access window up to TTL.+ var affectedUserIDs []stringif members, err := h.Queries.ListMembers(r.Context(), requester.WorkspaceID); err == nil {+ affectedUserIDs = make([]string, 0, len(members))for _, m := range members {- h.MembershipCache.Invalidate(r.Context(), uuidToString(m.UserID), workspaceID)+ userID := uuidToString(m.UserID)+ h.MembershipCache.Invalidate(r.Context(), userID, workspaceID)+ affectedUserIDs = append(affectedUserIDs, userID)}}@@ -749,6 +766,7 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {h.publish(protocol.EventWorkspaceDeleted, workspaceID, "member", requestUserID(r), map[string]any{"workspace_id": workspaceID,})+ h.notifyDaemonWorkspacesChanged(affectedUserIDs...)w.WriteHeader(http.StatusNoContent)}diff --git a/server/internal/metrics/http.go b/server/internal/metrics/http.goindex 5e957f2eb9..91902d6b5d 100644--- a/server/internal/metrics/http.go+++ b/server/internal/metrics/http.go@@ -11,11 +11,14 @@ import ()type HTTPMetrics struct {- requests *prometheus.CounterVec- duration *prometheus.HistogramVec- inFlight prometheus.Gauge+ requests *prometheus.CounterVec+ duration *prometheus.HistogramVec+ daemonWorkspaceResponseSize *prometheus.HistogramVec+ inFlight prometheus.Gauge}+const daemonWorkspaceRoutePattern = "/api/daemon/workspaces"+func NewHTTPMetrics() *HTTPMetrics {return &HTTPMetrics{requests: prometheus.NewCounterVec(prometheus.CounterOpts{@@ -31,6 +34,13 @@ func NewHTTPMetrics() *HTTPMetrics {Help: "HTTP request duration observed by the API server.",Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},}, []string{"method", "route", "status"}),+ daemonWorkspaceResponseSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Namespace: "multica",+ Subsystem: "http",+ Name: "daemon_workspace_response_size_bytes",+ Help: "Response bytes written by the daemon workspace-set endpoint.",+ Buckets: prometheus.ExponentialBuckets(128, 4, 9),+ }, []string{"status"}),inFlight: prometheus.NewGauge(prometheus.GaugeOpts{Namespace: "multica",Subsystem: "http",@@ -41,7 +51,7 @@ func NewHTTPMetrics() *HTTPMetrics {}func (m *HTTPMetrics) Collectors() []prometheus.Collector {- return []prometheus.Collector{m.requests, m.duration, m.inFlight}+ return []prometheus.Collector{m.requests, m.duration, m.daemonWorkspaceResponseSize, m.inFlight}}func (m *HTTPMetrics) Middleware(next http.Handler) http.Handler {@@ -65,13 +75,18 @@ func (m *HTTPMetrics) Middleware(next http.Handler) http.Handler {if status == 0 {status = http.StatusOK}+ route := routePattern(r)+ statusLabel := strconv.Itoa(status)labels := prometheus.Labels{"method": r.Method,- "route": routePattern(r),- "status": strconv.Itoa(status),+ "route": route,+ "status": statusLabel,}m.requests.With(labels).Inc()m.duration.With(labels).Observe(time.Since(start).Seconds())+ if route == daemonWorkspaceRoutePattern {+ m.daemonWorkspaceResponseSize.WithLabelValues(statusLabel).Observe(float64(ww.BytesWritten()))+ }})}diff --git a/server/internal/metrics/http_test.go b/server/internal/metrics/http_test.goindex e57d332fbf..51bbf10055 100644--- a/server/internal/metrics/http_test.go+++ b/server/internal/metrics/http_test.go@@ -49,6 +49,40 @@ func TestHTTPMiddlewareUsesRoutePatternLabels(t *testing.T) {}}+func TestHTTPMiddlewareRecordsDaemonWorkspaceResponseSizeByStatus(t *testing.T) {+ registry := NewRegistry(RegistryOptions{})++ r := chi.NewRouter()+ r.Use(registry.HTTP.Middleware)+ r.Get(daemonWorkspaceRoutePattern, func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("If-None-Match") != "" {+ w.WriteHeader(http.StatusNotModified)+ return+ }+ _, _ = w.Write([]byte(`[]`))+ })++ for _, etag := range []string{"", `W/"workspace-v1"`} {+ req := httptest.NewRequest(http.MethodGet, daemonWorkspaceRoutePattern, nil)+ req.Header.Set("If-None-Match", etag)+ r.ServeHTTP(httptest.NewRecorder(), req)+ }++ metricsRec := httptest.NewRecorder()+ NewHandler(registry.Gatherer).ServeHTTP(metricsRec, httptest.NewRequest(http.MethodGet, "/metrics", nil))+ body := metricsRec.Body.String()+ for _, want := range []string{+ `multica_http_daemon_workspace_response_size_bytes_count{status="200"} 1`,+ `multica_http_daemon_workspace_response_size_bytes_sum{status="200"} 2`,+ `multica_http_daemon_workspace_response_size_bytes_count{status="304"} 1`,+ `multica_http_daemon_workspace_response_size_bytes_sum{status="304"} 0`,+ } {+ if !strings.Contains(body, want) {+ t.Fatalf("metrics body missing %q\n%s", want, body)+ }+ }+}+func TestMetricsHandlerOnlyServesMetricsPath(t *testing.T) {registry := NewRegistry(RegistryOptions{})handler := NewHandler(registry.Gatherer)diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 298c5351a1..91ba25ab39 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -111,6 +111,26 @@ func (q *Queries) DeleteWorkspace(ctx context.Context, id pgtype.UUID) error {return err}+const getDaemonWorkspace = `-- name: GetDaemonWorkspace :one+SELECT id, name+FROM workspace+WHERE id = $1+`++type GetDaemonWorkspaceRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+}++// Workspace-scoped daemon tokens do not carry a user ID. This narrow lookup+// lets them use the same endpoint without widening their token scope.+func (q *Queries) GetDaemonWorkspace(ctx context.Context, id pgtype.UUID) (GetDaemonWorkspaceRow, error) {+ row := q.db.QueryRow(ctx, getDaemonWorkspace, id)+ var i GetDaemonWorkspaceRow+ err := row.Scan(&i.ID, &i.Name)+ return i, err+}+const getWorkspace = `-- name: GetWorkspace :oneSELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url FROM workspaceWHERE id = $1@@ -174,6 +194,43 @@ func (q *Queries) IncrementIssueCounter(ctx context.Context, id pgtype.UUID) (inreturn issue_counter, err}+const listDaemonWorkspaces = `-- name: ListDaemonWorkspaces :many+SELECT w.id, w.name+FROM member m+JOIN workspace w ON w.id = m.workspace_id+WHERE m.user_id = $1+ORDER BY w.id ASC+`++type ListDaemonWorkspacesRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+}++// Daemons only need the membership set and display name to discover which+// workspaces should have local runtimes. Keep this projection intentionally+// narrow so the periodic consistency check never reads UI-only JSON/text+// columns such as settings, repos, or context.+func (q *Queries) ListDaemonWorkspaces(ctx context.Context, userID pgtype.UUID) ([]ListDaemonWorkspacesRow, error) {+ rows, err := q.db.Query(ctx, listDaemonWorkspaces, userID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDaemonWorkspacesRow{}+ for rows.Next() {+ var i ListDaemonWorkspacesRow+ if err := rows.Scan(&i.ID, &i.Name); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listWorkspaces = `-- name: ListWorkspaces :manySELECT w.id, w.name, w.slug, w.description, w.settings,w.created_at, w.updated_at, w.context, w.repos,diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex 09692b11a5..c79ccab103 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -7,6 +7,24 @@ JOIN workspace w ON w.id = m.workspace_idWHERE m.user_id = $1ORDER BY w.created_at ASC;+-- name: ListDaemonWorkspaces :many+-- Daemons only need the membership set and display name to discover which+-- workspaces should have local runtimes. Keep this projection intentionally+-- narrow so the periodic consistency check never reads UI-only JSON/text+-- columns such as settings, repos, or context.+SELECT w.id, w.name+FROM member m+JOIN workspace w ON w.id = m.workspace_id+WHERE m.user_id = $1+ORDER BY w.id ASC;++-- name: GetDaemonWorkspace :one+-- Workspace-scoped daemon tokens do not carry a user ID. This narrow lookup+-- lets them use the same endpoint without widening their token scope.+SELECT id, name+FROM workspace+WHERE id = $1;+-- name: GetWorkspace :oneSELECT * FROM workspaceWHERE id = $1;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 0a2ca5cf40..c5e7e82490 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -118,6 +118,7 @@ const (EventDaemonRegister = "daemon:register"EventDaemonTaskAvailable = "daemon:task_available"EventDaemonRuntimeProfilesChanged = "daemon:runtime_profiles_changed"+ EventDaemonWorkspacesChanged = "daemon:workspaces_changed"// Generic daemon→server request/response over the WebSocket control// connection (MUL-4257). The daemon sends EventDaemonRPCRequest with a// correlation id + method + body; the server replies EventDaemonRPCResponsediff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex e3dcf043d3..228415e84d 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -70,6 +70,11 @@ type RuntimeProfilesChangedPayload struct {RuntimeProfileID string `json:"runtime_profile_id,omitempty"`}+// WorkspacesChangedPayload is an account-scoped hint that asks a daemon to+// reconcile its workspace membership set. The server remains authoritative;+// no workspace data is embedded in the event.+type WorkspacesChangedPayload struct{}+// TaskProgressPayload is sent from daemon to server during task execution.type TaskProgressPayload struct {TaskID string `json:"task_id"`