Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8822 feat: ask for a GitHub star after an agent finishes enough issues (#10182)
Jiayuan Zhangbebc2791bd20
diff --git a/.env.example b/.env.exampleindex dd0f25358a..69215c4e13 100644--- a/.env.example+++ b/.env.example@@ -739,6 +739,10 @@ DISABLE_WORKSPACE_CREATION=# workspaces. Requires a backend restart.WORKSPACE_CREATION_ALLOWED_EMAILS=+# Set to "true" to stop the app from asking users to star Multica on GitHub.+# Read from /api/config at runtime; requires a backend restart.+DISABLE_STAR_PROMPT=+# ==================== Anonymous Self-host Telemetry ====================# The API server sends one first-party, deployment-level anonymous snapshot per# UTC day to https://telemetry.multica.ai. It contains the release version,diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex cae1e93657..ddbb25a209 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -111,6 +111,14 @@ Things to know:> Note: setting `ALLOW_SIGNUP=false` enables invite-only account creation. A new user with a live pending workspace invitation can create an account with the invited email; users without an allowlist match or a valid invitation remain blocked. Invitations also permit emails outside configured allowlists when `ALLOW_SIGNUP=true`. Revocation does not delete accounts already created using an invitation or prevent those accounts from signing in. Combine this with `DISABLE_WORKSPACE_CREATION=true` when invitees must join an existing workspace instead of creating their own.+### GitHub Star Prompt (Optional)++| Variable | Description |+|----------|-------------|+| `DISABLE_STAR_PROMPT` | Set to `true` to stop the app from asking users to star Multica on GitHub |++The prompt is a small card that can appear after an agent has completed a few issues: at most twice per account, at least 30 days apart, and never again once the user clicks Star. Users can still star Multica from the Help menu. While the card or Help menu is open, the browser asks `api.github.com` for the star count; with the switch on, the server rejects new showings and the card never appears. Changes take effect after restarting the backend; the web UI reads the switch from `/api/config`, so no web rebuild is needed.+### File Storage (Optional)Uploads and attachments are written to local disk by default. Set `S3_BUCKET` todiff --git a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsxindex 6acd8642e8..14a718c572 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx@@ -86,6 +86,7 @@ vi.mock("@multica/views/search", () => ({SearchCommand: () => null,}));vi.mock("@multica/views/chat", () => ({ FloatingChat: () => null }));+vi.mock("@multica/views/star-prompt", () => ({ StarPrompt: () => null }));vi.mock("./tab-bar", () => ({ TabBar: () => null }));vi.mock("./window-overlay", () => ({ WindowOverlay: () => null }));diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsxindex 48083ee646..cbce145fe4 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx@@ -24,6 +24,7 @@ import {} from "@multica/views/layout";import { SearchCommand } from "@multica/views/search";import { FloatingChat } from "@multica/views/chat";+import { StarPrompt } from "@multica/views/star-prompt";import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";import { workspaceListOptions } from "@multica/core/workspace";import {@@ -314,6 +315,7 @@ export function DesktopShell() {<NavigationProgress /><TabContent />{slug && <FloatingChat />}+ {slug && <StarPrompt />}</MainCanvas></div></ShellRouteDataPrefetch>diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsxindex abbddb933a..6a1a67e558 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx@@ -115,6 +115,9 @@ vi.mock("@multica/views/search", () => ({vi.mock("@multica/views/chat", () => ({FloatingChat: () => <div data-testid="floating-chat" />,}));+vi.mock("@multica/views/star-prompt", () => ({+ StarPrompt: () => <div data-testid="star-prompt" />,+}));vi.mock("./tab-bar", () => ({ TabBar: () => null }));vi.mock("./window-overlay", () => ({ WindowOverlay: () => null }));@@ -168,6 +171,7 @@ describe("DesktopShell workspace gating", () => {expect(queryByTestId("global-shortcuts")).not.toBeNull();expect(queryByTestId("modal-registry")).not.toBeNull();expect(queryByTestId("floating-chat")).not.toBeNull();+ expect(queryByTestId("star-prompt")).not.toBeNull();expect(queryByRole("status", { name: /loading workspace/i })).toBeNull();});diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsxindex fd37d662a6..5f4cf17c99 100644--- a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx+++ b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx@@ -5,6 +5,7 @@ import { DashboardLayout } from "@multica/views/layout";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";import { SearchCommand } from "@multica/views/search";import { FloatingChat } from "@multica/views/chat/floating-chat";+import { StarPrompt } from "@multica/views/star-prompt";import { WebNotificationBridge } from "@/components/web-notification-bridge";import { WorkspaceDocumentTitle } from "@/platform/workspace-document-title";@@ -24,6 +25,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {<SearchCommand /><WebNotificationBridge /><FloatingChat />+ <StarPrompt /></>}>diff --git a/apps/web/features/landing/utils/use-github-stars.ts b/apps/web/features/landing/utils/use-github-stars.tsindex 47f700c9fe..6d9877361f 100644--- a/apps/web/features/landing/utils/use-github-stars.ts+++ b/apps/web/features/landing/utils/use-github-stars.ts@@ -1,25 +1,19 @@"use client";import { useEffect, useState } from "react";+import { fetchGithubStars } from "@multica/core/github/stars";++export { formatStarCount } from "@multica/core/github/stars";/*** Live GitHub star count for the landing header's "GitHub" button.*- * Fetched client-side on purpose: the badge lives in the shared- * {@link LandingHeader}, which renders on every marketing page, so a single- * client fetch covers them all without threading a server value through eight- * render sites. Each visitor calls the GitHub API from their own IP, which- * sidesteps the shared-outbound-IP rate limit that the server-side- * `github-release.ts` fetcher has to work around with a PAT.- *- * The result is memoized at module scope (plus an in-flight promise) so- * client-side navigation between landing pages reuses the first fetch instead- * of hitting the API again. A failed fetch caches `null` so we don't retry in- * a loop; the button just degrades to its plain "GitHub" label.+ * The count is memoized at module scope (plus an in-flight promise) so+ * client-side navigation between landing pages reuses the first fetch. A failed fetch+ * caches `null` so we don't retry in a loop; the button just degrades to its+ * plain "GitHub" label.*/-const REPO = "multica-ai/multica";-// `undefined` = never fetched; `number` = resolved count; `null` = fetch failed.let cachedStars: number | null | undefined;let inFlight: Promise<number | null> | null = null;@@ -28,23 +22,11 @@ async function loadStars(): Promise<number | null> {if (cachedStars !== undefined) return cachedStars;if (inFlight) return inFlight;- inFlight = fetch(`https://api.github.com/repos/${REPO}`, {- headers: { Accept: "application/vnd.github+json" },- })- .then((res) => {- if (!res.ok) throw new Error(`GitHub API responded ${res.status}`);- return res.json() as Promise<{ stargazers_count?: unknown }>;- })- .then((data) => {- const count =- typeof data.stargazers_count === "number" ? data.stargazers_count : null;+ inFlight = fetchGithubStars()+ .then((count) => {cachedStars = count;return count;})- .catch(() => {- cachedStars = null;- return null;- }).finally(() => {inFlight = null;});@@ -67,19 +49,3 @@ export function useGithubStars(): number | null {return stars;}--/**- * Compact star count matching GitHub's own repo-header style: one decimal- * thousands/millions with the trailing ".0" trimmed ("1k", "37.6k", "1.2m").- * Counts below 1,000 render exactly. Mirrors GitHub's `toFixed(1)` rounding so- * our badge reads the same as the figure on the repo page.- */-export function formatStarCount(n: number): string {- if (n >= 1_000_000) {- return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;- }- if (n >= 1_000) {- return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;- }- return String(n);-}diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex b6cf25d077..387fbd4005 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -22,6 +22,7 @@ data:ALLOWED_EMAIL_DOMAINS: {{ .Values.backend.config.allowedEmailDomains | quote }}DISABLE_WORKSPACE_CREATION: {{ .Values.backend.config.disableWorkspaceCreation | quote }}WORKSPACE_CREATION_ALLOWED_EMAILS: {{ .Values.backend.config.workspaceCreationAllowedEmails | quote }}+ DISABLE_STAR_PROMPT: {{ .Values.backend.config.disableStarPrompt | quote }}DO_NOT_TRACK: {{ .Values.backend.config.doNotTrack | quote }}MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}MULTICA_CLOUD_URL: {{ .Values.backend.config.cloud.url | quote }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex 2d3efd3b6f..2acd48196d 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -152,6 +152,8 @@ backend:# create workspaces. Empty = every signed-in user may create one.# disableWorkspaceCreation=true still blocks everyone.workspaceCreationAllowedEmails: ""+ # Set to true to stop the app from asking users to star Multica on GitHub.+ disableStarPrompt: false# Set to "1" or "true" to disable first-party anonymous self-host# telemetry collection and delivery.doNotTrack: ""diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 9b89bac181..a194b42caf 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -113,6 +113,7 @@ services:ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}WORKSPACE_CREATION_ALLOWED_EMAILS: ${WORKSPACE_CREATION_ALLOWED_EMAILS:-}+ DISABLE_STAR_PROMPT: ${DISABLE_STAR_PROMPT:-}DO_NOT_TRACK: ${DO_NOT_TRACK:-}# Managed Cloud stays off for self-hosting. All managed Cloud clients use# this single URL when it is configured.diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex ca82f4f9cf..1688829a09 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -158,6 +158,25 @@ describe("ApiClient edit guards", () => {expect(parsedLegacy.issues[0]).not.toHaveProperty("revision");await expect(client.listIssues()).resolves.toEqual({ issues: [], total: 0 });});++ it("sends status category filters so custom statuses count with their phase", async () => {+ const fetchMock = vi.fn(+ async (_url: string, _init?: RequestInit) =>+ new Response(JSON.stringify({ issues: [], total: 0 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");++ await client.listIssues({ status_categories: ["done", "closed"] });+ await client.listIssues({ status_category: "started" });++ const query = (call: number) => new URL(fetchMock.mock.calls[call]![0]).searchParams;+ expect(query(0).get("status_categories")).toBe("done,closed");+ expect(query(1).get("status_category")).toBe("started");+ });});describe("ApiClient pull-request response schema", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a948ee7663..d03ba569a8 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1154,6 +1154,21 @@ export class ApiClient {});}+ /** Rejects with 409 when the server decides the prompt is not due. */+ async claimStarPromptShowing(): Promise<User> {+ const raw = await this.fetch<unknown>("/api/me/star-prompt/claim", { method: "POST" });+ return parseWithFallback(raw, UserSchema, EMPTY_USER, {+ endpoint: "POST /api/me/star-prompt/claim",+ });+ }++ async markStarPromptStarred(): Promise<User> {+ const raw = await this.fetch<unknown>("/api/me/star-prompt/starred", { method: "POST" });+ return parseWithFallback(raw, UserSchema, EMPTY_USER, {+ endpoint: "POST /api/me/star-prompt/starred",+ });+ }+async updateMe(data: UpdateMeRequest): Promise<User> {const raw = await this.fetch<unknown>("/api/me", {method: "PATCH",@@ -1173,6 +1188,8 @@ export class ApiClient {if (params?.q?.trim()) search.set("q", params.q.trim());if (params?.status) search.set("status", params.status);if (params?.statuses?.length) search.set("statuses", params.statuses.join(","));+ if (params?.status_category) search.set("status_category", params.status_category);+ if (params?.status_categories?.length) search.set("status_categories", params.status_categories.join(","));if (params?.priority) search.set("priority", params.priority);if (params?.priorities?.length) search.set("priorities", params.priorities.join(","));if (params?.assignee_id) search.set("assignee_id", params.assignee_id);diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 8cba67fdfd..58dbe8e895 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1114,6 +1114,30 @@ describe("UserSchema whats_new_seen_version drift", () => {});});+describe("UserSchema star prompt drift", () => {+ const base = {+ id: "11111111-1111-1111-1111-111111111111",+ name: "Ada",+ email: "[email protected]",+ };++ it("leaves the showing count undefined when an older server omits it", () => {+ expect(UserSchema.parse(base).star_prompt_shown_count).toBeUndefined();+ });++ it("degrades wrong-type values to undefined without discarding the user", () => {+ const parsed = parseWithFallback(+ { ...base, star_prompt_shown_count: "2", star_prompt_starred_at: 1 },+ UserSchema,+ EMPTY_USER,+ { endpoint: "GET /api/me" },+ );+ expect(parsed.email).toBe("[email protected]");+ expect(parsed.star_prompt_shown_count).toBeUndefined();+ expect(parsed.star_prompt_starred_at).toBeUndefined();+ });+});+describe("SquadListSchema member preview drift", () => {const baseSquad = {id: "squad-1",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 4e9ac0eec7..afe9cdfe17 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -918,6 +918,8 @@ export interface AppConfigResponse {daemon_app_url?: string;daemon_setup_target?: "cloud" | "self_host" | "unknown";workspace_creation_disabled?: boolean;+ /** DISABLE_STAR_PROMPT on the server. Absent means the prompt is allowed. */+ star_prompt_disabled?: boolean;/** Whether this deployment offers the self-hosted Git provider integration* (self-host only; off on the managed cloud). Absent/false hides the whole* Settings → Integrations "Git providers" section. */@@ -1205,6 +1207,7 @@ export const AppConfigSchema = z.object({daemon_app_url: OptionalStringSchema,daemon_setup_target: z.enum(["cloud", "self_host", "unknown"]).optional().catch("unknown"),workspace_creation_disabled: BooleanWithDefaultSchema(false).optional(),+ star_prompt_disabled: BooleanWithDefaultSchema(false).optional(),vcs_integration_available: BooleanWithDefaultSchema(false).optional(),feature_flags: FeatureFlagsSchema,local_worktree_supported: BooleanWithDefaultSchema(false),@@ -1224,6 +1227,7 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {daemon_app_url: "",daemon_setup_target: "unknown",workspace_creation_disabled: false,+ star_prompt_disabled: false,vcs_integration_available: false,// Fail closed: an unreadable config must not look like a server that// validates execution_mode.@@ -2767,6 +2771,10 @@ export const UserSchema = z.object({// No default: absence is the "server cannot track" signal. A malformed// value degrades to that state instead of discarding the whole user.whats_new_seen_version: z.string().nullable().optional().catch(undefined),+ // Same "absent means unsupported" contract as above.+ star_prompt_shown_count: z.number().int().nonnegative().optional().catch(undefined),+ star_prompt_last_shown_at: z.string().nullable().optional().catch(undefined),+ star_prompt_starred_at: z.string().nullable().optional().catch(undefined),created_at: z.string().default(""),updated_at: z.string().default(""),}).loose();diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 3a1278a414..8cb9c8bb27 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -19,6 +19,9 @@ interface ConfigState {// must be hidden. Defaults to false so unknown / older servers behave like// the managed-cloud case.workspaceCreationDisabled: boolean;+ // DISABLE_STAR_PROMPT: the deployment opted out of the "Star us on GitHub"+ // prompt. Defaults to false so older servers keep the prompt.+ starPromptDisabled: boolean;// Self-host-only gate for the Git provider integration (Forgejo / Gitea /// GitLab). When false the whole Settings → Integrations "Git providers"// section is hidden. Defaults to false so unknown / older servers and the@@ -61,6 +64,7 @@ interface ConfigState {daemonSetupTarget?: DaemonSetupTarget;}) => void;setDaemonConfigStatus: (status: DaemonConfigStatus) => void;+ setStarPromptDisabled: (disabled?: boolean) => void;setFeatureFlags: (flags?: Record<string, boolean>) => void;setServerVersion: (version?: string) => void;setLocalWorktreeSupported: (supported?: boolean) => void;@@ -80,6 +84,7 @@ export const configStore = createStore<ConfigState>((set) => ({daemonConfigStatus: "loading",daemonSetupTarget: "unknown",workspaceCreationDisabled: false,+ starPromptDisabled: false,vcsIntegrationAvailable: false,featureFlags: {},serverVersion: "",@@ -106,6 +111,7 @@ export const configStore = createStore<ConfigState>((set) => ({daemonConfigStatus: "ready",}),setDaemonConfigStatus: (daemonConfigStatus) => set({ daemonConfigStatus }),+ setStarPromptDisabled: (disabled = false) => set({ starPromptDisabled: disabled === true }),setFeatureFlags: (flags = {}) => set({ featureFlags: { ...flags } }),setServerVersion: (version = "") => set({ serverVersion: version }),setLocalWorktreeSupported: (supported = false) =>diff --git a/packages/core/github/index.ts b/packages/core/github/index.tsindex dde1485c9c..7ccaeb708c 100644--- a/packages/core/github/index.ts+++ b/packages/core/github/index.ts@@ -4,3 +4,4 @@ export * from "./pull-request-status";export * from "./settings";export * from "./use-github-settings";export * from "./repo-ref";+export * from "./stars";diff --git a/apps/web/features/landing/utils/use-github-stars.test.ts b/packages/core/github/stars.test.tssimilarity index 94%rename from apps/web/features/landing/utils/use-github-stars.test.tsrename to packages/core/github/stars.test.tsindex 3823b87890..a342b58274 100644--- a/apps/web/features/landing/utils/use-github-stars.test.ts+++ b/packages/core/github/stars.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { describe, expect, it } from "vitest";-import { formatStarCount } from "./use-github-stars";+import { formatStarCount } from "./stars";describe("formatStarCount", () => {it("renders counts below 1,000 exactly", () => {diff --git a/packages/core/github/stars.ts b/packages/core/github/stars.tsnew file mode 100644index 0000000000..bf57be495d--- /dev/null+++ b/packages/core/github/stars.ts@@ -0,0 +1,47 @@+import { queryOptions } from "@tanstack/react-query";++export const MULTICA_GITHUB_REPO = "multica-ai/multica";+export const MULTICA_GITHUB_URL = `https://github.com/${MULTICA_GITHUB_REPO}`;++/**+ * Star count for the Multica repository, or null when GitHub cannot be reached+ * (offline, rate-limited, an air-gapped self-hosted install). Callers fall back+ * to a label without a count. Fetched from the browser on purpose: each user+ * spends their own IP's anonymous rate limit instead of a shared server one.+ */+export async function fetchGithubStars(): Promise<number | null> {+ try {+ const res = await fetch(`https://api.github.com/repos/${MULTICA_GITHUB_REPO}`, {+ headers: { Accept: "application/vnd.github+json" },+ });+ if (!res.ok) return null;+ const data = (await res.json()) as { stargazers_count?: unknown };+ return typeof data.stargazers_count === "number" ? data.stargazers_count : null;+ } catch {+ return null;+ }+}++export function githubStarsOptions() {+ return queryOptions({+ queryKey: ["github", "stars", MULTICA_GITHUB_REPO] as const,+ queryFn: fetchGithubStars,+ staleTime: 6 * 60 * 60 * 1000,+ retry: false,+ });+}++/**+ * Compact star count matching GitHub's own repo-header style: one decimal+ * thousands/millions with the trailing ".0" trimmed ("1k", "37.6k", "1.2m").+ * Counts below 1,000 render exactly.+ */+export function formatStarCount(n: number): string {+ if (n >= 1_000_000) {+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;+ }+ if (n >= 1_000) {+ return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;+ }+ return String(n);+}diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsxindex babad7f0b2..de37f6dd66 100644--- a/packages/core/issues/mutations.test.tsx+++ b/packages/core/issues/mutations.test.tsx@@ -24,6 +24,7 @@ import {type IssueSortParam,} from "./queries";import { onIssueUpdated, onIssueAuxiliaryRevision } from "./ws-updaters";+import { useStarPromptStore } from "../star-prompt";import { inboxKeys, inboxListOptions } from "../inbox/queries";import {onInboxInvalidate,@@ -1511,3 +1512,65 @@ describe("useCreateComment — sibling caches under a shared key prefix", () =>).toEqual(["comment-1"]);});});++describe("useUpdateIssue — star prompt moment", () => {+ let qc: QueryClient;+ let updateIssue: ReturnType<typeof vi.fn<(id: string, data: unknown) => Promise<Issue>>>;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ updateIssue = vi.fn();+ setApiInstance({ updateIssue } as unknown as ApiClient);+ useStarPromptStore.setState({ moment: null });+ });++ afterEach(() => {+ qc.clear();+ useStarPromptStore.setState({ moment: null });+ });++ async function update(vars: { id: string } & UpdateIssueRequest, response: Issue) {+ updateIssue.mockResolvedValue(response);+ const { result } = renderHook(() => useUpdateIssue(), { wrapper: createWrapper(qc) });+ await act(async () => {+ await result.current.mutateAsync(vars);+ });+ }++ it("reports the moment the user moves an agent's issue to done", async () => {+ await update(+ { id: "issue-1", status: "done" },+ makeIssue(1, { status: "done", assignee_type: "agent", assignee_id: "agent-1" }),+ );+ expect(useStarPromptStore.getState().moment).toEqual({+ wsId: WS_ID,+ agentId: "agent-1",+ issueId: "issue-1",+ });+ });++ it("reports a custom status in the done category", async () => {+ await update(+ { id: "issue-1", status: "shipped" },+ makeIssue(1, {+ status: "shipped",+ status_category: "done",+ assignee_type: "agent",+ assignee_id: "agent-1",+ }),+ );+ expect(useStarPromptStore.getState().moment).toMatchObject({ agentId: "agent-1" });+ });++ it("ignores done issues owned by members and edits that leave status alone", async () => {+ await update(+ { id: "issue-1", status: "done" },+ makeIssue(1, { status: "done", assignee_type: "member", assignee_id: "user-1" }),+ );+ await update(+ { id: "issue-2", title: "Renamed" },+ makeIssue(2, { status: "done", assignee_type: "agent", assignee_id: "agent-1" }),+ );+ expect(useStarPromptStore.getState().moment).toBeNull();+ });+});diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex ba41c15468..9577927935 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -1,4 +1,4 @@-import { normalizeStatusPatch } from "./status-category";+import { issueBehavesAs, normalizeStatusPatch } from "./status-category";import {hashKey,useMutation,@@ -40,6 +40,7 @@ import { refreshSubscribedIssues } from "./subscribed";import { getCurrentWsId } from "../platform/workspace-storage";import { useRecentContextStore } from "../chat/recent-context-store";import { useRecentIssuesStore } from "./stores";+import { useStarPromptStore } from "../star-prompt";import type { InboxItem, Issue, IssueReaction } from "../types";import type {CreateCommentSubIssueManualRequest,@@ -352,6 +353,18 @@ export function useUpdateIssue() {);// The server has committed — safe to flush any drift it reported now.invalidateStaleListKeys(qc, reconcile.staleKeys);+ if (+ vars.status !== undefined &&+ serverIssue.assignee_type === "agent" &&+ serverIssue.assignee_id &&+ issueBehavesAs(serverIssue, "done")+ ) {+ useStarPromptStore.getState().reportAgentIssueDone({+ wsId,+ agentId: serverIssue.assignee_id,+ issueId: serverIssue.id,+ });+ }},onSettled: (_data, err, vars, ctx) => {settleInboxAfterIssueWrite(qc, wsId, ctx?.inboxWrite, err !== null);diff --git a/packages/core/onboarding/queries.ts b/packages/core/onboarding/queries.tsindex 75d35ceef1..f603f39e56 100644--- a/packages/core/onboarding/queries.ts+++ b/packages/core/onboarding/queries.ts@@ -4,7 +4,7 @@ import { issueKeys } from "../issues/queries";/*** Count of issues in the workspace completed by an AI assignee (agent- * or squad). Sole consumer is the source-backfill gate: the prompt+ * or squad), custom statuses in the done category included. Sole consumer is the source-backfill gate: the prompt* waits until the user has watched agents finish real work before* asking the attribution question (SOURCE_BACKFILL_MIN_AGENT_DONE_ISSUES* in `needs-backfill.ts`).@@ -23,7 +23,7 @@ export function agentCompletedIssueCountOptions(wsId: string) {queryFn: async () => {const res = await api.listIssues({workspace_id: wsId,- statuses: ["done"],+ status_categories: ["done"],assignee_types: ["agent", "squad"],limit: 1,});diff --git a/packages/core/package.json b/packages/core/package.jsonindex fb6572a08a..905ec3f225 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -140,6 +140,7 @@"./github": "./github/index.ts","./github/queries": "./github/queries.ts","./github/repo-ref": "./github/repo-ref.ts",+ "./github/stars": "./github/stars.ts","./vcs": "./vcs/index.ts","./vcs/queries": "./vcs/queries.ts","./lark": "./lark/index.ts",@@ -164,6 +165,8 @@"./modals": "./modals/index.ts","./onboarding": "./onboarding/index.ts","./whats-new": "./whats-new/index.ts",+ "./session-prompt": "./session-prompt/index.ts",+ "./star-prompt": "./star-prompt/index.ts","./paths": "./paths/index.ts","./hooks": "./hooks.tsx","./hooks/*": "./hooks/*.ts",diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 004c3ba8ec..fb35c01bf3 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -90,6 +90,7 @@ export function AuthInitializer({daemonAppUrl: cfg.daemon_app_url,daemonSetupTarget,});+ configStore.getState().setStarPromptDisabled(cfg.star_prompt_disabled);configStore.getState().setFeatureFlags(cfg.feature_flags);configStore.getState().setServerVersion(cfg.server_version);// Absent on every server that predates the worktree save gate, whichdiff --git a/packages/core/session-prompt/index.ts b/packages/core/session-prompt/index.tsnew file mode 100644index 0000000000..a6842a1e96--- /dev/null+++ b/packages/core/session-prompt/index.ts@@ -0,0 +1,18 @@+"use client";++import { create } from "zustand";++interface SessionPromptStore {+ /** A prompt that asks something of the user has been shown this app session. */+ prompted: boolean;+ markPrompted: () => void;+}++/**+ * The one interruption an app session allows, shared by the source survey and+ * the GitHub star prompt so a user who just dealt with one never meets the other.+ */+export const useSessionPromptStore = create<SessionPromptStore>((set) => ({+ prompted: false,+ markPrompted: () => set({ prompted: true }),+}));diff --git a/packages/core/star-prompt/index.test.ts b/packages/core/star-prompt/index.test.tsnew file mode 100644index 0000000000..bcdc28339c--- /dev/null+++ b/packages/core/star-prompt/index.test.ts@@ -0,0 +1,125 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { User } from "../types";+import {+ claimStarPromptShowing,+ markStarPromptStarred,+ STAR_PROMPT_COOLDOWN_MS,+ STAR_PROMPT_MIN_ACCOUNT_AGE_MS,+ starPromptDue,+} from "./index";++const api = vi.hoisted(() => ({+ claimStarPromptShowing: vi.fn(),+ markStarPromptStarred: vi.fn(),+}));+const authStore = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { create } = require("zustand") as typeof import("zustand");+ return create<{ user: User | null; setUser: (user: User) => void }>((set) => ({+ user: null,+ setUser: (user) => set({ user }),+ }));+});++vi.mock("../api", () => ({ api }));+vi.mock("../auth", () => ({ useAuthStore: authStore }));++const NOW = Date.parse("2026-11-09T12:00:00Z");+const iso = (ms: number) => new Date(ms).toISOString();++function user(patch: Partial<User> = {}): User {+ return {+ id: "u1",+ name: "Ada",+ email: "[email protected]",+ avatar_url: null,+ onboarded_at: null,+ onboarding_questionnaire: {},+ created_at: iso(NOW - STAR_PROMPT_MIN_ACCOUNT_AGE_MS - 1),+ updated_at: iso(NOW),+ star_prompt_shown_count: 0,+ star_prompt_last_shown_at: null,+ star_prompt_starred_at: null,+ ...patch,+ } as User;+}++afterEach(() => {+ authStore.setState({ user: null });+ vi.clearAllMocks();+});++describe("starPromptDue", () => {+ it("is due for an established account that has never seen it", () => {+ expect(starPromptDue(user(), NOW)).toBe(true);+ });++ it("is never due when the server cannot count showings", () => {+ expect(starPromptDue(user({ star_prompt_shown_count: undefined }), NOW)).toBe(false);+ expect(starPromptDue(null, NOW)).toBe(false);+ });++ it("waits for the account to be three days old", () => {+ expect(starPromptDue(user({ created_at: iso(NOW - STAR_PROMPT_MIN_ACCOUNT_AGE_MS + 1) }), NOW)).toBe(+ false,+ );+ });++ it("waits out the cooldown after a showing", () => {+ const shown = (ago: number) =>+ user({ star_prompt_shown_count: 1, star_prompt_last_shown_at: iso(NOW - ago) });+ expect(starPromptDue(shown(STAR_PROMPT_COOLDOWN_MS - 1), NOW)).toBe(false);+ expect(starPromptDue(shown(STAR_PROMPT_COOLDOWN_MS), NOW)).toBe(true);+ });++ it("stops after two showings or a star", () => {+ expect(starPromptDue(user({ star_prompt_shown_count: 2 }), NOW)).toBe(false);+ expect(starPromptDue(user({ star_prompt_starred_at: iso(NOW) }), NOW)).toBe(false);+ });+});++describe("claimStarPromptShowing", () => {+ it("records the granted showing on the signed-in user", async () => {+ authStore.setState({ user: user() });+ api.claimStarPromptShowing.mockResolvedValue(+ user({ star_prompt_shown_count: 1, star_prompt_last_shown_at: iso(NOW) }),+ );++ await expect(claimStarPromptShowing()).resolves.toBe(true);+ expect(authStore.getState().user?.star_prompt_shown_count).toBe(1);+ });++ it("reports a refused claim as not showable", async () => {+ authStore.setState({ user: user() });+ api.claimStarPromptShowing.mockRejectedValue(new Error("409"));++ await expect(claimStarPromptShowing()).resolves.toBe(false);+ expect(authStore.getState().user?.star_prompt_shown_count).toBe(0);+ });++ it("ignores a response that lands after an account switch", async () => {+ authStore.setState({ user: user() });+ api.claimStarPromptShowing.mockImplementation(async () => {+ authStore.setState({ user: user({ id: "u2" }) });+ return user({ star_prompt_shown_count: 1 });+ });++ await claimStarPromptShowing();+ expect(authStore.getState().user).toMatchObject({ id: "u2", star_prompt_shown_count: 0 });+ });+});++describe("markStarPromptStarred", () => {+ it("retires the prompt before the server answers", async () => {+ authStore.setState({ user: user() });+ let resolve!: (u: User) => void;+ api.markStarPromptStarred.mockReturnValue(new Promise<User>((r) => (resolve = r)));++ const pending = markStarPromptStarred();+ expect(starPromptDue(authStore.getState().user, NOW)).toBe(false);++ resolve(user({ star_prompt_starred_at: "2026-11-09T12:00:01Z" }));+ await pending;+ expect(authStore.getState().user?.star_prompt_starred_at).toBe("2026-11-09T12:00:01Z");+ });+});diff --git a/packages/core/star-prompt/index.ts b/packages/core/star-prompt/index.tsnew file mode 100644index 0000000000..42310f689c--- /dev/null+++ b/packages/core/star-prompt/index.ts@@ -0,0 +1,119 @@+"use client";++import { queryOptions } from "@tanstack/react-query";+import { create } from "zustand";+import { api } from "../api";+import { issueKeys } from "../issues/queries";+import { useAuthStore } from "../auth";+import type { User } from "../types";++const DAY_MS = 24 * 60 * 60 * 1000;++// Mirrors server/internal/handler/star_prompt.go, which has the final say.+// The client checks first only so it does not ask for a showing it cannot get.+export const STAR_PROMPT_MAX_SHOWINGS = 2;+export const STAR_PROMPT_COOLDOWN_MS = 30 * DAY_MS;+export const STAR_PROMPT_MIN_ACCOUNT_AGE_MS = 3 * DAY_MS;+/** Done issues the agent needs before its work is worth celebrating. */+export const STAR_PROMPT_MIN_AGENT_DONE_ISSUES = 3;++type StarPromptUser = Pick<+ User,+ | "created_at"+ | "star_prompt_shown_count"+ | "star_prompt_last_shown_at"+ | "star_prompt_starred_at"+>;++/**+ * Whether the user may be shown the star prompt now, by account age and the+ * showing history. False when the server cannot record showings+ * (`star_prompt_shown_count` undefined): a prompt it cannot count would come+ * back forever.+ */+export function starPromptDue(user: StarPromptUser | null, now: number): boolean {+ if (!user || user.star_prompt_shown_count === undefined) return false;+ if (user.star_prompt_starred_at) return false;+ if (user.star_prompt_shown_count >= STAR_PROMPT_MAX_SHOWINGS) return false;+ const createdAt = Date.parse(user.created_at);+ if (!Number.isFinite(createdAt) || now - createdAt < STAR_PROMPT_MIN_ACCOUNT_AGE_MS) {+ return false;+ }+ if (user.star_prompt_last_shown_at) {+ const lastShown = Date.parse(user.star_prompt_last_shown_at);+ if (!Number.isFinite(lastShown) || now - lastShown < STAR_PROMPT_COOLDOWN_MS) return false;+ }+ return true;+}++/** The current user just moved an agent's issue to a done status. */+export interface StarPromptMoment {+ wsId: string;+ agentId: string;+ issueId: string;+}++interface StarPromptStore {+ moment: StarPromptMoment | null;+ reportAgentIssueDone: (moment: StarPromptMoment) => void;+ clearMoment: () => void;+}++export const useStarPromptStore = create<StarPromptStore>((set) => ({+ moment: null,+ reportAgentIssueDone: (moment) => set({ moment }),+ clearMoment: () => set({ moment: null }),+}));++/** Issues assigned to one agent in the workspace whose status is in the done category. */+export function agentDoneIssueCountOptions(wsId: string, agentId: string) {+ return queryOptions({+ queryKey: [...issueKeys.all(wsId), "done-count-by-agent", agentId] as const,+ queryFn: async () => {+ const res = await api.listIssues({+ workspace_id: wsId,+ status_categories: ["done"],+ assignee_filters: [{ type: "agent", id: agentId }],+ limit: 1,+ });+ return res.total;+ },+ staleTime: 0,+ });+}++function applyUser(requesterId: string, user: User) {+ const current = useAuthStore.getState().user;+ // The response can land after a logout or an account switch.+ if (current?.id !== requesterId || user.id !== requesterId) return;+ useAuthStore.getState().setUser({+ ...current,+ star_prompt_shown_count: user.star_prompt_shown_count,+ star_prompt_last_shown_at: user.star_prompt_last_shown_at,+ star_prompt_starred_at: user.star_prompt_starred_at,+ });+}++/**+ * Asks the server for one showing. True means show the prompt now; false means+ * another tab or device took it, the deployment turned the prompt off, or the+ * request failed.+ */+export async function claimStarPromptShowing(): Promise<boolean> {+ const requester = useAuthStore.getState().user;+ if (!requester) return false;+ try {+ applyUser(requester.id, await api.claimStarPromptShowing());+ return true;+ } catch {+ return false;+ }+}++/** Retires the prompt for good once the user clicks through to GitHub. */+export async function markStarPromptStarred(): Promise<void> {+ const requester = useAuthStore.getState().user;+ if (!requester) return;+ applyUser(requester.id, { ...requester, star_prompt_starred_at: new Date().toISOString() });+ applyUser(requester.id, await api.markStarPromptStarred());+}diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex de9a396fc2..0b67c8ff28 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -158,8 +158,7 @@ export interface ListIssuesParams {/*** Filter by lifecycle category rather than by exact key, so one bucket holds* all concrete and custom statuses in that phase. Task views use exact- * status keys for their columns instead. The web client's- * `ApiClient.listIssues` does not send it.+ * status keys for their columns instead.*/status_category?: IssueStatusCategory;/** Multi-value form of `status_category`. OR within the field. */diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.tsindex d1c8583d67..d857c2dd1a 100644--- a/packages/core/types/workspace.ts+++ b/packages/core/types/workspace.ts@@ -84,6 +84,13 @@ export interface User {* so the client must not auto-open the card (it would reappear forever).*/whats_new_seen_version?: string | null;+ /**+ * "Star us on GitHub" prompt bookkeeping. An undefined count means the+ * server predates it, so the client must never show the prompt.+ */+ star_prompt_shown_count?: number;+ star_prompt_last_shown_at?: string | null;+ star_prompt_starred_at?: string | null;created_at: string;updated_at: string;}diff --git a/packages/views/layout/help-launcher.test.tsx b/packages/views/layout/help-launcher.test.tsxindex 87a90a02a9..d96203c3e6 100644--- a/packages/views/layout/help-launcher.test.tsx+++ b/packages/views/layout/help-launcher.test.tsx@@ -1,7 +1,10 @@import { cloneElement, type ReactElement, type ReactNode } from "react";-import { render, screen } from "@testing-library/react";+import { fireEvent, render as rtlRender, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { configStore } from "@multica/core/config";+import { githubStarsOptions } from "@multica/core/github/stars";+import { markStarPromptStarred } from "@multica/core/star-prompt";import enLayout from "../locales/en/layout.json";import { isDesktopShell } from "../platform/local-directory";import { HelpLauncher } from "./help-launcher";@@ -13,6 +16,10 @@ vi.mock("../platform/local-directory", () => ({isDesktopShell: vi.fn(() => false),}));+vi.mock("@multica/core/star-prompt", () => ({+ markStarPromptStarred: vi.fn(() => Promise.resolve()),+}));+// The What's new entry is covered with the real menu in whats-new-menu-panel.test.tsx.vi.mock("../whats-new/whats-new-menu-panel", () => ({useWhatsNewMenuPanel: () => ({ available: false }),@@ -63,10 +70,12 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", async () => {DropdownMenuItem: ({children,render,+ onClick,}: {children: ReactNode;render?: ReactElement;- }) => (render ? cloneElement(render, undefined, children) : <>{children}</>),+ onClick?: () => void;+ }) => (render ? cloneElement(render, { onClick } as object, children) : <>{children}</>),DropdownMenuGroup: ({ children }: { children: ReactNode }) => (<GroupContext.Provider value={true}>{children}</GroupContext.Provider>),@@ -83,13 +92,21 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", async () => {};});+let qc: QueryClient;++function render(ui: ReactElement) {+ return rtlRender(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);+}+beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });vi.mocked(isDesktopShell).mockReturnValue(false);i18nState.language = "en";});afterEach(() => {configStore.getState().setServerVersion("");+ qc.clear();});describe("HelpLauncher", () => {@@ -136,4 +153,18 @@ describe("HelpLauncher", () => {// The rest of the menu is unaffected by the gate.expect(screen.getByText("Docs")).toBeInTheDocument();});++ it("links to the GitHub repo and retires the star prompt on click", () => {+ render(<HelpLauncher />);+ const link = screen.getByRole("link", { name: /Star on GitHub/ });+ expect(link).toHaveAttribute("href", "https://github.com/multica-ai/multica");+ fireEvent.click(link);+ expect(markStarPromptStarred).toHaveBeenCalledTimes(1);+ });++ it("shows the star count once it is known", () => {+ qc.setQueryData(githubStarsOptions().queryKey, 37_612);+ render(<HelpLauncher />);+ expect(screen.getByRole("link", { name: /Star on GitHub/ })).toHaveTextContent("37.6k");+ });});diff --git a/packages/views/layout/help-launcher.tsx b/packages/views/layout/help-launcher.tsxindex 52ae57c6b5..9e24f02a89 100644--- a/packages/views/layout/help-launcher.tsx+++ b/packages/views/layout/help-launcher.tsx@@ -1,6 +1,7 @@"use client";-import { useRef } from "react";+import { useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";import {ArrowUpRight,BookOpen,@@ -9,6 +10,7 @@ import {History,Megaphone,MessageCircle,+ Star,} from "@multica/ui/icons";import {DropdownMenu,@@ -22,14 +24,19 @@ import {import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import { useModalStore } from "@multica/core/modals";import { useConfigStore } from "@multica/core/config";+import { formatStarCount, githubStarsOptions, MULTICA_GITHUB_URL } from "@multica/core/github/stars";+import { createLogger } from "@multica/core/logger";+import { markStarPromptStarred } from "@multica/core/star-prompt";import { isDesktopShell } from "../platform/local-directory";import { DISCORD_URL, DiscordIcon } from "./discord";+import { GitHubIcon } from "../onboarding/components/brand-icons";import { useT } from "../i18n";import { docsLocalePrefix } from "../common/docs-locale";import { RAIL_ICON_BUTTON_CLASS } from "./rail-styles";import { CHANGELOG_URL, DOCS_URL, DOWNLOAD_URL } from "./help-links";import { useWhatsNewMenuPanel, WhatsNewMenuPanel } from "../whats-new/whats-new-menu-panel";+const logger = createLogger("help-launcher");export function HelpLauncher() {const { t, i18n } = useT("layout");@@ -46,9 +53,12 @@ export function HelpLauncher() {const desktop = isDesktopShell();const triggerRef = useRef<HTMLButtonElement>(null);const whatsNew = useWhatsNewMenuPanel();+ const [open, setOpen] = useState(false);+ // Asked only once the menu opens, so closed sessions never call GitHub.+ const { data: stars } = useQuery({ ...githubStarsOptions(), enabled: open });return (<>- <DropdownMenu>+ <DropdownMenu open={open} onOpenChange={setOpen}><TooltipHint label={t(($) => $.help.trigger)} side="right"><DropdownMenuTriggerref={triggerRef}@@ -131,6 +141,25 @@ export function HelpLauncher() {{t(($) => $.help.discord)}<ArrowUpRight className="size-3 translate-y-px text-faint-foreground" /></DropdownMenuItem>+ <DropdownMenuItem+ render={+ <a href={MULTICA_GITHUB_URL} target="_blank" rel="noopener noreferrer" />+ }+ onClick={() => {+ markStarPromptStarred().catch((err) => logger.warn("failed to record star click", err));+ }}+ >+ <GitHubIcon className="h-3.5 w-3.5" />+ {t(($) => $.help.star_on_github)}+ {typeof stars === "number" ? (+ <span className="ml-auto inline-flex shrink-0 items-center gap-1 text-caption whitespace-nowrap text-muted-foreground tabular-nums">+ <Star aria-hidden="true" className="size-3" />+ {formatStarCount(stars)}+ </span>+ ) : (+ <ArrowUpRight className="size-3 translate-y-px text-faint-foreground" />+ )}+ </DropdownMenuItem><DropdownMenuItemonClick={() => useModalStore.getState().open("feedback")}>diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 9ef4c8f0c1..9a90a44002 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -35,6 +35,7 @@"docs": "Docs","changelog": "Change log","discord": "Discord",+ "star_on_github": "Star on GitHub","feedback": "Feedback","server_version": "Server version {{version}}"},@@ -53,6 +54,15 @@"learn_more": "Learn more"}},+ "star_prompt": {+ "title_one": "{{agent}} has completed {{count}} issue",+ "title_other": "{{agent}} has completed {{count}} issues",+ "body": "If Multica has been useful, a star on GitHub helps other teams find it.",+ "star": "Star",+ "star_label": "Star Multica on GitHub",+ "later": "Not now",+ "close": "Close"+ },"workspace_loader": {"loading_workspace": "Loading workspace…","loading_named_prefix": "Loading"diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex d834304664..5ce0b3d299 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -35,6 +35,7 @@"docs": "Documentación","changelog": "Registro de cambios","discord": "Discord",+ "star_on_github": "Dar una estrella en GitHub","feedback": "Comentarios","server_version": "Versión del servidor {{version}}"},@@ -78,6 +79,15 @@"learn_more": "Más información"}},+ "star_prompt": {+ "title_one": "{{agent}} ha completado {{count}} tarea",+ "title_other": "{{agent}} ha completado {{count}} tareas",+ "body": "Si Multica te resulta útil, una estrella en GitHub ayuda a que otros equipos lo descubran.",+ "star": "Star",+ "star_label": "Dar una Star a Multica en GitHub",+ "later": "Ahora no",+ "close": "Cerrar"+ },"spaces": {"work": "Trabajo","team": "Equipo"diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex 523855ba86..728ff6c1cd 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -35,6 +35,7 @@"docs": "Documentation","changelog": "Journal des modifications","discord": "Discord",+ "star_on_github": "Mettre une étoile sur GitHub","feedback": "Faire un retour","server_version": "Version du serveur {{version}}"},@@ -53,6 +54,15 @@"learn_more": "En savoir plus"}},+ "star_prompt": {+ "title_one": "{{agent}} a terminé {{count}} tâche",+ "title_other": "{{agent}} a terminé {{count}} tâches",+ "body": "Si Multica vous est utile, une étoile sur GitHub aide d'autres équipes à le découvrir.",+ "star": "Star",+ "star_label": "Mettre une Star à Multica sur GitHub",+ "later": "Plus tard",+ "close": "Fermer"+ },"workspace_loader": {"loading_workspace": "Chargement de l'espace de travail…","loading_named_prefix": "Chargement"diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex d92f26d5cc..ed63dc6f46 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -35,6 +35,7 @@"docs": "ドキュメント","changelog": "変更ログ","discord": "Discord",+ "star_on_github": "GitHub でスターする","feedback": "フィードバック","server_version": "サーバーバージョン {{version}}"},@@ -53,6 +54,14 @@"learn_more": "詳しく見る"}},+ "star_prompt": {+ "title_other": "{{agent}} がタスクを {{count}} 件完了しました",+ "body": "Multica がお役に立っていたら、GitHub でスターをお願いします。ほかのチームが Multica を見つけやすくなります。",+ "star": "Star",+ "star_label": "GitHub で Multica にスターする",+ "later": "あとで",+ "close": "閉じる"+ },"workspace_loader": {"loading_workspace": "ワークスペースを読み込み中…","loading_named_prefix": "読み込み中"diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 118fa523a7..a5863e289b 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -35,6 +35,7 @@"docs": "문서","changelog": "변경 로그","discord": "Discord",+ "star_on_github": "GitHub에서 Star 하기","feedback": "피드백","server_version": "서버 버전 {{version}}"},@@ -53,6 +54,14 @@"learn_more": "자세히 알아보기"}},+ "star_prompt": {+ "title_other": "{{agent}}이(가) 태스크 {{count}}개를 완료했습니다",+ "body": "Multica가 도움이 되었다면 GitHub에서 Star를 눌러 주세요. 다른 팀이 Multica를 찾는 데 도움이 됩니다.",+ "star": "Star",+ "star_label": "GitHub에서 Multica에 Star 하기",+ "later": "나중에",+ "close": "닫기"+ },"workspace_loader": {"loading_workspace": "워크스페이스 로딩 중...","loading_named_prefix": "로딩 중"diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex 7cee418abd..586d319d0f 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -35,6 +35,7 @@"docs": "Документация","changelog": "История изменений","discord": "Discord",+ "star_on_github": "Поставить звезду на GitHub","feedback": "Обратная связь","server_version": "Версия сервера {{version}}"},@@ -228,5 +229,16 @@"title": "Что нового"},"trigger": "Что нового"+ },+ "star_prompt": {+ "title_one": "{{agent}}: {{count}} задача выполнена",+ "title_few": "{{agent}}: {{count}} задачи выполнены",+ "title_many": "{{agent}}: {{count}} задач выполнено",+ "title_other": "{{agent}}: выполнено задач — {{count}}",+ "body": "Если Multica оказалась полезной, поставьте звезду на GitHub — так её найдут другие команды.",+ "star": "Star",+ "star_label": "Поставить звезду Multica на GitHub",+ "later": "Не сейчас",+ "close": "Закрыть"}}diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex f1787aad3b..a02f72f5ee 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -35,6 +35,7 @@"docs": "文档","changelog": "更新日志","discord": "Discord",+ "star_on_github": "在 GitHub 上 Star","feedback": "反馈","server_version": "服务器版本 {{version}}"},@@ -53,6 +54,14 @@"learn_more": "了解更多"}},+ "star_prompt": {+ "title_other": "{{agent}} 已经完成了 {{count}} 个任务",+ "body": "如果 Multica 帮上了忙,在 GitHub 上点个 Star,能让更多团队发现它。",+ "star": "Star",+ "star_label": "在 GitHub 上给 Multica 点 Star",+ "later": "以后再说",+ "close": "关闭"+ },"workspace_loader": {"loading_workspace": "正在加载工作区...","loading_named_prefix": "正在加载"diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex e6b6ee3a15..63eb8f6bde 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -35,6 +35,7 @@"docs": "文件","changelog": "更新日誌","discord": "Discord",+ "star_on_github": "在 GitHub 上 Star","feedback": "反饋","server_version": "伺服器版本 {{version}}"},@@ -53,6 +54,14 @@"learn_more": "了解更多"}},+ "star_prompt": {+ "title_other": "{{agent}} 已經完成了 {{count}} 個任務",+ "body": "如果 Multica 幫上了忙,在 GitHub 上按個 Star,能讓更多團隊發現它。",+ "star": "Star",+ "star_label": "在 GitHub 上給 Multica 按 Star",+ "later": "以後再說",+ "close": "關閉"+ },"workspace_loader": {"loading_workspace": "正在載入工作區...","loading_named_prefix": "正在載入"diff --git a/packages/views/onboarding/source-backfill-dismiss.ts b/packages/views/onboarding/source-backfill-dismiss.tsindex 28aee58544..e805ec67fc 100644--- a/packages/views/onboarding/source-backfill-dismiss.ts+++ b/packages/views/onboarding/source-backfill-dismiss.ts@@ -23,7 +23,7 @@ function storageKey(userId: string): string {return `${STORAGE_PREFIX}${userId}`;}-function readCount(userId: string | null | undefined): number {+export function readSourceBackfillDismissCount(userId: string | null | undefined): number {if (!userId) return 0;if (typeof window === "undefined") return 0;try {@@ -66,7 +66,7 @@ export function useSourceBackfillDismissCount(off();};},- () => readCount(userId),+ () => readSourceBackfillDismissCount(userId),() => 0,);@@ -74,7 +74,7 @@ export function useSourceBackfillDismissCount(if (!userId) return;if (typeof window === "undefined") return;try {- const next = readCount(userId) + 1;+ const next = readSourceBackfillDismissCount(userId) + 1;window.localStorage.setItem(storageKey(userId), String(next));notify();} catch {diff --git a/packages/views/onboarding/source-backfill-modal.test.tsx b/packages/views/onboarding/source-backfill-modal.test.tsxindex e0f1ccd731..945dc2a886 100644--- a/packages/views/onboarding/source-backfill-modal.test.tsx+++ b/packages/views/onboarding/source-backfill-modal.test.tsx@@ -212,7 +212,7 @@ describe("SourceBackfillModal", () => {await waitFor(() => {expect(mockListIssues).toHaveBeenCalledWith({workspace_id: "ws-1",- statuses: ["done"],+ status_categories: ["done"],assignee_types: ["agent", "squad"],limit: 1,});diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsxindex 2a2208146d..07e5860142 100644--- a/packages/views/onboarding/source-backfill-modal.tsx+++ b/packages/views/onboarding/source-backfill-modal.tsx@@ -22,6 +22,7 @@ import {type Source,} from "@multica/core/onboarding";import { useCurrentWorkspace } from "@multica/core/paths";+import { useSessionPromptStore } from "@multica/core/session-prompt";import { Button } from "@multica/ui/components/ui/button";import {Dialog,@@ -125,6 +126,10 @@ export function SourceBackfillModal() {return () => window.clearTimeout(timer);}, [user, shouldPrompt]);+ useEffect(() => {+ if (open) useSessionPromptStore.getState().markPrompted();+ }, [open]);+return (<Dialogopen={open}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 82e388360d..11ded9d9e2 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -60,6 +60,7 @@"./invite": "./invite/index.ts","./invitations": "./invitations/index.ts","./onboarding": "./onboarding/index.ts",+ "./star-prompt": "./star-prompt/index.ts","./platform": "./platform/index.ts","./i18n": "./i18n/index.ts","./attachments": "./attachments/index.ts",diff --git a/packages/views/star-prompt/index.ts b/packages/views/star-prompt/index.tsnew file mode 100644index 0000000000..a864964342--- /dev/null+++ b/packages/views/star-prompt/index.ts@@ -0,0 +1 @@+export { StarPrompt } from "./star-prompt";diff --git a/packages/views/star-prompt/star-prompt.test.tsx b/packages/views/star-prompt/star-prompt.test.tsxnew file mode 100644index 0000000000..e86f86dd9d--- /dev/null+++ b/packages/views/star-prompt/star-prompt.test.tsx@@ -0,0 +1,315 @@+import type { ReactNode } from "react";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setApiInstance, type ApiClient } from "@multica/core/api";+import { configStore } from "@multica/core/config";+import { I18nProvider } from "@multica/core/i18n/react";+import { useSessionPromptStore } from "@multica/core/session-prompt";+import {+ claimStarPromptShowing,+ markStarPromptStarred,+ useStarPromptStore,+} from "@multica/core/star-prompt";+import type { User } from "@multica/core/types";+import enCommon from "../locales/en/common.json";+import enLayout from "../locales/en/layout.json";+import enOnboarding from "../locales/en/onboarding.json";+import { SourceBackfillModal } from "../onboarding/source-backfill-modal";+import { STAR_PROMPT_DELAY_MS, StarPrompt } from "./star-prompt";++const stores = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { create } = require("zustand") as typeof import("zustand");+ return {+ auth: create<{ user: Partial<User> | null }>(() => ({ user: null })),+ chat: create<{ isOpen: boolean; floatingChatEnabled: boolean }>(() => ({+ isOpen: false,+ floatingChatEnabled: true,+ })),+ };+});++vi.mock("@multica/core/auth", () => ({ useAuthStore: stores.auth }));+vi.mock("@multica/core/chat", () => ({ useChatStore: stores.chat }));+vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>("@multica/core/paths");+ return {+ ...actual,+ useWorkspacePaths: () => ({ chat: () => "/acme/chat" }),+ useCurrentWorkspace: () => workspace.current,+ };+});+vi.mock("@multica/core/onboarding", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/onboarding")>("@multica/core/onboarding");+ return {+ ...actual,+ // The real call refreshes /api/me; the answer landing on the user is what matters here.+ saveQuestionnaire: vi.fn(async (questionnaire: Record<string, unknown>) => {+ const user = stores.auth.getState().user;+ stores.auth.setState({ user: { ...user, onboarding_questionnaire: questionnaire } });+ }),+ };+});+vi.mock("../navigation", () => ({ useNavigation: () => ({ pathname: "/acme/issues" }) }));+vi.mock("@multica/core/star-prompt", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/star-prompt")>(+ "@multica/core/star-prompt",+ );+ return {+ ...actual,+ claimStarPromptShowing: vi.fn(),+ markStarPromptStarred: vi.fn(() => Promise.resolve()),+ };+});++const DAY_MS = 24 * 60 * 60 * 1000;+const workspace = vi.hoisted(() => ({+ current: { id: "ws-1", slug: "acme" } as { id: string; slug: string } | null,+}));+const listIssues = vi.fn();+let qc: QueryClient;++function eligibleUser(): Partial<User> {+ return {+ id: "u1",+ created_at: new Date(Date.now() - 10 * DAY_MS).toISOString(),+ // Already answered the source survey, so it does not claim the session.+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: ["friend"] },+ star_prompt_shown_count: 0,+ star_prompt_last_shown_at: null,+ star_prompt_starred_at: null,+ };+}++function renderPrompt(children: ReactNode = <StarPrompt />) {+ return render(+ <QueryClientProvider client={qc}>+ <I18nProvider+ locale="en"+ resources={{ en: { common: enCommon, layout: enLayout, onboarding: enOnboarding } }}+ >+ {children}+ </I18nProvider>+ </QueryClientProvider>,+ );+}++async function agentFinishesIssue() {+ act(() => {+ useStarPromptStore.getState().reportAgentIssueDone({ wsId: "ws-1", agentId: "agent-1", issueId: "i1" });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(STAR_PROMPT_DELAY_MS);+ });+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ listIssues.mockResolvedValue({ issues: [], total: 4 });+ setApiInstance({+ listIssues,+ listAgents: vi.fn().mockResolvedValue([{ id: "agent-1", name: "Lambda" }]),+ } as unknown as ApiClient);+ vi.stubGlobal("fetch", vi.fn(() => Promise.reject(new Error("offline"))));+ vi.mocked(claimStarPromptShowing).mockResolvedValue(true);+ stores.auth.setState({ user: eligibleUser() });+ stores.chat.setState({ isOpen: false });+ useStarPromptStore.setState({ moment: null });+ useSessionPromptStore.setState({ prompted: false });+ workspace.current = { id: "ws-1", slug: "acme" };+});++afterEach(() => {+ window.localStorage.removeItem("multica.source_backfill.dismiss.u1");+ qc.clear();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ configStore.getState().setStarPromptDisabled(false);+});++describe("StarPrompt", () => {+ it("celebrates the agent a moment after it finishes enough issues", async () => {+ renderPrompt();+ await agentFinishesIssue();++ expect(await screen.findByText("Lambda has completed 4 issues")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Star Multica on GitHub" })).toHaveAttribute(+ "href",+ "https://github.com/multica-ai/multica",+ );+ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({+ status_categories: ["done"],+ assignee_filters: [{ type: "agent", id: "agent-1" }],+ }),+ );+ });++ it("retires the prompt when the user clicks through to GitHub", async () => {+ renderPrompt();+ await agentFinishesIssue();+ fireEvent.click(await screen.findByRole("link", { name: "Star Multica on GitHub" }));++ expect(markStarPromptStarred).toHaveBeenCalledTimes(1);+ expect(screen.queryByText("Lambda has completed 4 issues")).not.toBeInTheDocument();+ });++ it("closes on Not now without retiring the prompt", async () => {+ renderPrompt();+ await agentFinishesIssue();+ fireEvent.click(await screen.findByRole("button", { name: "Not now" }));++ expect(screen.queryByText("Lambda has completed 4 issues")).not.toBeInTheDocument();+ expect(markStarPromptStarred).not.toHaveBeenCalled();+ });++ it("stays hidden until the agent has finished three issues", async () => {+ listIssues.mockResolvedValue({ issues: [], total: 2 });+ renderPrompt();+ await agentFinishesIssue();++ expect(claimStarPromptShowing).not.toHaveBeenCalled();+ expect(screen.queryByRole("region")).not.toBeInTheDocument();+ });++ it("stays hidden when the server refuses the showing", async () => {+ vi.mocked(claimStarPromptShowing).mockResolvedValue(false);+ renderPrompt();+ await agentFinishesIssue();++ expect(claimStarPromptShowing).toHaveBeenCalledTimes(1);+ expect(screen.queryByText("Lambda has completed 4 issues")).not.toBeInTheDocument();+ });++ it("asks at most once per session", async () => {+ renderPrompt();+ await agentFinishesIssue();+ fireEvent.click(await screen.findByRole("button", { name: "Not now" }));+ await agentFinishesIssue();++ expect(claimStarPromptShowing).toHaveBeenCalledTimes(1);+ });++ it("yields to the source survey when it is still owed", async () => {+ stores.auth.setState({ user: { ...eligibleUser(), onboarding_questionnaire: {} } });+ renderPrompt();+ await agentFinishesIssue();++ expect(listIssues).not.toHaveBeenCalled();+ });++ it("skips the moment while the user is typing", async () => {+ renderPrompt();+ const input = document.createElement("input");+ document.body.appendChild(input);+ input.focus();+ await agentFinishesIssue();+ input.remove();++ expect(listIssues).not.toHaveBeenCalled();+ });++ it("waits quietly while the workspace is still resolving", async () => {+ workspace.current = null;+ renderPrompt();+ await agentFinishesIssue();++ expect(listIssues).not.toHaveBeenCalled();+ expect(claimStarPromptShowing).not.toHaveBeenCalled();+ });++ it("does nothing when the deployment turns it off", async () => {+ configStore.getState().setStarPromptDisabled(true);+ renderPrompt();+ await agentFinishesIssue();++ expect(listIssues).not.toHaveBeenCalled();+ });+});++describe("StarPrompt after the source survey", () => {+ it.each([+ [+ "answering",+ async () => {+ fireEvent.click(await screen.findByText("Friends or colleagues"));+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ },+ ],+ ["skipping", async () => fireEvent.click(await screen.findByRole("button", { name: "Skip" }))],+ ["closing", async () => fireEvent.click(await screen.findByRole("button", { name: "Close" }))],+ ])("does not ask again in the session after %s the survey", async (_name, finishSurvey) => {+ stores.auth.setState({ user: { ...eligibleUser(), onboarding_questionnaire: { source: [] } } });+ renderPrompt(+ <>+ <SourceBackfillModal />+ <StarPrompt />+ </>,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(screen.getByText("How did you hear about Multica?")).toBeInTheDocument();++ await finishSurvey();+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ await agentFinishesIssue();++ expect(claimStarPromptShowing).not.toHaveBeenCalled();+ });+});++describe("StarPrompt for a workspace that finishes work in custom done statuses", () => {+ // Mirrors the server: three issues sit in a custom done-category status, so+ // only a category query finds them and an exact `done` query finds none.+ function customDoneIssues() {+ listIssues.mockImplementation(async (params: { status_categories?: string[] }) => ({+ issues: [],+ total: params.status_categories?.includes("done") ? 3 : 0,+ }));+ }++ function renderSession() {+ return renderPrompt(+ <>+ <SourceBackfillModal />+ <StarPrompt />+ </>,+ );+ }++ it.each([+ ["answering", async () => {+ fireEvent.click(await screen.findByText("Friends or colleagues"));+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ }],+ ["skipping", async () => fireEvent.click(await screen.findByRole("button", { name: "Skip" }))],+ ])("asks for the survey first, then for a star only in a later session after %s it", async (_name, finishSurvey) => {+ customDoneIssues();+ stores.auth.setState({ user: { ...eligibleUser(), onboarding_questionnaire: { source: [] } } });++ const first = renderSession();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(screen.getByText("How did you hear about Multica?")).toBeInTheDocument();+ await finishSurvey();+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ await agentFinishesIssue();+ expect(claimStarPromptShowing).not.toHaveBeenCalled();+ first.unmount();++ // A new app session: fresh module state and caches, same signed-in user.+ useSessionPromptStore.setState({ prompted: false });+ qc.clear();+ renderSession();+ await agentFinishesIssue();++ expect(await screen.findByText("Lambda has completed 3 issues")).toBeInTheDocument();+ expect(screen.queryByText("How did you hear about Multica?")).not.toBeInTheDocument();+ });+});diff --git a/packages/views/star-prompt/star-prompt.tsx b/packages/views/star-prompt/star-prompt.tsxnew file mode 100644index 0000000000..d33ea2c861--- /dev/null+++ b/packages/views/star-prompt/star-prompt.tsx@@ -0,0 +1,183 @@+"use client";++import { useEffect, useId, useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Star, X } from "@multica/ui/icons";+import { Button, buttonVariants } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";+import { useAuthStore } from "@multica/core/auth";+import { useChatStore } from "@multica/core/chat";+import { useConfigStore } from "@multica/core/config";+import { formatStarCount, githubStarsOptions, MULTICA_GITHUB_URL } from "@multica/core/github/stars";+import { createLogger } from "@multica/core/logger";+import { needsSourceBackfill } from "@multica/core/onboarding";+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";+import { useSessionPromptStore } from "@multica/core/session-prompt";+import {+ agentDoneIssueCountOptions,+ claimStarPromptShowing,+ markStarPromptStarred,+ STAR_PROMPT_MIN_AGENT_DONE_ISSUES,+ starPromptDue,+ useStarPromptStore,+ type StarPromptMoment,+} from "@multica/core/star-prompt";+import { agentListOptions } from "@multica/core/workspace/queries";+import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";+import { useT } from "../i18n";+import { useNavigation } from "../navigation";+import { GitHubIcon } from "../onboarding/components/brand-icons";+import { readSourceBackfillDismissCount } from "../onboarding/source-backfill-dismiss";++const logger = createLogger("star-prompt");++/** Lets the status change settle before the card slides in. */+export const STAR_PROMPT_DELAY_MS = 2500;++/**+ * Nothing is open or being typed into. A card that appears mid-sentence or+ * over a dialog reads as an interruption, so such moments are skipped rather+ * than deferred.+ */+function isQuietMoment(): boolean {+ if (document.visibilityState !== "visible") return false;+ if (document.querySelector("[role='dialog'][aria-modal='true'], [role='alertdialog']")) return false;+ const active = document.activeElement;+ if (+ active instanceof HTMLElement &&+ (active.isContentEditable || active.tagName === "INPUT" || active.tagName === "TEXTAREA")+ ) {+ return false;+ }+ return true;+}++interface Showing {+ agentName: string;+ doneCount: number;+}++/**+ * "Star us on GitHub" card. Appears a moment after the user moves an agent's+ * issue to done, once that agent has finished enough issues to have earned it.+ * The server decides whether a showing is still due (account age, cooldown,+ * showings used); this component decides whether the moment is right.+ */+export function StarPrompt() {+ const { t } = useT("layout");+ const titleId = useId();+ // Shells mount this while the workspace slug is still resolving.+ const wsId = useCurrentWorkspace()?.id ?? null;+ const qc = useQueryClient();+ const moment = useStarPromptStore((s) => s.moment);+ const disabled = useConfigStore((s) => s.starPromptDisabled);+ const chatOpen = useChatStore((s) => s.isOpen);+ const floatingChatEnabled = useChatStore((s) => s.floatingChatEnabled);+ const { pathname } = useNavigation();+ const chatPath = useWorkspacePaths().chat();+ const launcherVisible =+ floatingChatEnabled && !chatOpen && !isFloatingChatRouteSuppressed(pathname, chatPath);+ const [showing, setShowing] = useState<Showing | null>(null);+ const { data: stars } = useQuery({ ...githubStarsOptions(), enabled: showing !== null });++ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ useEffect(() => {+ if (!moment || !wsId) return;++ const consider = async (m: StarPromptMoment, workspaceId: string) => {+ if (m.wsId !== workspaceId || disabled) return;+ if (useSessionPromptStore.getState().prompted) return;+ const user = useAuthStore.getState().user;+ if (!starPromptDue(user, Date.now())) return;+ // The attribution survey owns this session's one interruption.+ if (needsSourceBackfill(user, readSourceBackfillDismissCount(user?.id))) return;+ if (!isQuietMoment()) return;++ const [doneCount, agents] = await Promise.all([+ qc.fetchQuery(agentDoneIssueCountOptions(workspaceId, m.agentId)),+ qc.fetchQuery(agentListOptions(workspaceId)),+ ]);+ const agent = agents.find((a) => a.id === m.agentId);+ if (!agent || doneCount < STAR_PROMPT_MIN_AGENT_DONE_ISSUES) return;+ if (!mountedRef.current || !(await claimStarPromptShowing())) return;+ useSessionPromptStore.getState().markPrompted();+ if (mountedRef.current) setShowing({ agentName: agent.name, doneCount });+ };++ const timer = window.setTimeout(() => {+ useStarPromptStore.getState().clearMoment();+ consider(moment, wsId).catch((err) => logger.warn("failed to evaluate star prompt", err));+ }, STAR_PROMPT_DELAY_MS);+ return () => window.clearTimeout(timer);+ }, [moment, wsId, disabled, qc]);++ // The chat window covers this corner while it is open.+ if (!showing || chatOpen) return null;++ const close = () => setShowing(null);+ const star = () => {+ close();+ markStarPromptStarred().catch((err) => logger.warn("failed to record star click", err));+ };++ return (+ <section+ aria-labelledby={titleId}+ aria-live="polite"+ data-slot="star-prompt"+ className={cn(+ "absolute right-[var(--chat-launcher-inset)] z-50 w-[min(23.75rem,calc(100%-2*var(--chat-launcher-inset)))] rounded-xl bg-surface-raised p-4 pb-3 text-popover-foreground shadow-[var(--floating-shadow)] ring-1 ring-surface-border",+ "animate-in fade-in-0 slide-in-from-bottom-2 duration-200 motion-reduce:animate-none",+ launcherVisible ? "above-chat-launcher" : "bottom-[var(--chat-launcher-inset)]",+ )}+ >+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.star_prompt.close)}+ onClick={close}+ className="absolute top-2 right-2 text-muted-foreground"+ >+ <X />+ </Button>+ <div className="flex items-start gap-2 pr-6">+ <Star aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-brand" />+ <div className="min-w-0">+ <h2 id={titleId} className="text-body font-semibold [overflow-wrap:anywhere]">+ {t(($) => $.star_prompt.title, { agent: showing.agentName, count: showing.doneCount })}+ </h2>+ <p className="mt-1 text-label text-muted-foreground">{t(($) => $.star_prompt.body)}</p>+ </div>+ </div>+ <div className="mt-3 flex items-center justify-end gap-2">+ <Button variant="ghost" size="sm" onClick={close}>+ {t(($) => $.star_prompt.later)}+ </Button>+ <a+ href={MULTICA_GITHUB_URL}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={t(($) => $.star_prompt.star_label)}+ onClick={star}+ className={buttonVariants({ size: "sm" })}+ >+ <GitHubIcon className="size-3.5" />+ {t(($) => $.star_prompt.star)}+ {typeof stars === "number" && (+ <span aria-hidden="true" className="inline-flex items-center gap-1.5 tabular-nums">+ <span className="h-3 w-px bg-current opacity-30" />+ {formatStarCount(stars)}+ </span>+ )}+ </a>+ </div>+ </section>+ );+}diff --git a/packages/views/whats-new/whats-new-menu-panel.test.tsx b/packages/views/whats-new/whats-new-menu-panel.test.tsxindex eed00d7738..32e395af76 100644--- a/packages/views/whats-new/whats-new-menu-panel.test.tsx+++ b/packages/views/whats-new/whats-new-menu-panel.test.tsx@@ -1,5 +1,6 @@import type { ReactNode } from "react";-import { act, fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render as rtlRender, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useSearchStore } from "@multica/core/command-bar";import { configStore } from "@multica/core/config";@@ -139,7 +140,16 @@ function closePanel() {const release = (version: string) => screen.getByRole("region", { name: `v${version}` });+let qc: QueryClient;++function render(ui: ReactNode) {+ return rtlRender(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);+}+beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ // The Help menu asks GitHub for the star count when it opens.+ vi.stubGlobal("fetch", vi.fn(() => Promise.reject(new Error("offline"))));vi.useFakeTimers();i18nState.language = "en";mocks.markWhatsNewSeen.mockImplementation(async (version: string) => {@@ -149,6 +159,8 @@ beforeEach(() => {});afterEach(() => {+ qc.clear();+ vi.unstubAllGlobals();vi.useRealTimers();vi.clearAllMocks();authStore.setState({ user: null });diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 2da0173564..17762043a8 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -434,6 +434,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusAllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),DisableWorkspaceCreation: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",+ DisableStarPrompt: os.Getenv("DISABLE_STAR_PROMPT") == "true",WorkspaceCreationAllowedEmails: splitAndTrim(os.Getenv("WORKSPACE_CREATION_ALLOWED_EMAILS")),VCSIntegrationEnabled: os.Getenv("MULTICA_VCS_INTEGRATION_ENABLED") == "true",PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),@@ -1743,6 +1744,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/api/me/onboarding/complete", h.CompleteOnboarding)r.Post("/api/me/onboarding/cloud-waitlist", h.JoinCloudWaitlist)r.Post("/api/me/whats-new/seen", h.MarkWhatsNewSeen)+ r.With(handler.RequireHumanActor).Post("/api/me/star-prompt/claim", h.ClaimStarPromptShowing)+ r.With(handler.RequireHumanActor).Post("/api/me/star-prompt/starred", h.MarkStarPromptStarred)// Credential minting is human-only (MUL-8154): an agent task token// (mat_) or cloud-node PAT (mcn_) authenticates as its owner, so// without this guard a prompt-injected agent could trade its scoped,diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.goindex 9995aab800..12515866fc 100644--- a/server/internal/handler/auth.go+++ b/server/internal/handler/auth.go@@ -78,8 +78,13 @@ type UserResponse struct {// Always serialized (null when unset): clients treat a missing key as// "server cannot track What's new" and suppress the auto-opening card.WhatsNewSeenVersion *string `json:"whats_new_seen_version"`- CreatedAt string `json:"created_at"`- UpdatedAt string `json:"updated_at"`+ // Star prompt bookkeeping. The count is always serialized: clients treat+ // a missing key as "server cannot track the prompt" and never show it.+ StarPromptShownCount int32 `json:"star_prompt_shown_count"`+ StarPromptLastShownAt *string `json:"star_prompt_last_shown_at"`+ StarPromptStarredAt *string `json:"star_prompt_starred_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`}// MaxProfileDescriptionLen caps the user-supplied profile_description body.@@ -107,6 +112,9 @@ func (h *Handler) userToResponse(u db.User) UserResponse {OnboardingQuestionnaire: json.RawMessage(q),ProfileDescription: u.ProfileDescription,WhatsNewSeenVersion: textToPtr(u.WhatsNewSeenVersion),+ StarPromptShownCount: u.StarPromptShownCount,+ StarPromptLastShownAt: timestampToPtr(u.StarPromptLastShownAt),+ StarPromptStarredAt: timestampToPtr(u.StarPromptStarredAt),CreatedAt: timestampToString(u.CreatedAt),UpdatedAt: timestampToString(u.UpdatedAt),}diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 02e4fedb9f..5fa7bb8f0b 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -34,6 +34,9 @@ type AppConfig struct {// from the JSON when false to keep responses identical to the// previous shape for the common managed-cloud case (#3433).WorkspaceCreationDisabled bool `json:"workspace_creation_disabled,omitempty"`+ // StarPromptDisabled mirrors DISABLE_STAR_PROMPT so clients skip the+ // "Star us on GitHub" prompt. Omitted when false.+ StarPromptDisabled bool `json:"star_prompt_disabled,omitempty"`// Public daemon setup config consumed by the web app at runtime so// self-hosted instances can show `multica setup self-host` commands// with the operator's own domains instead of Multica Cloud defaults.@@ -132,6 +135,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()config.DaemonSetupTarget = "self_host"config.VCSIntegrationAvailable = h.cfg.VCSIntegrationEnabled+ config.StarPromptDisabled = h.cfg.DisableStarPromptconfig.FeatureFlags = featureflags.EvaluateFrontendPublicFlags(r.Context(), h.FeatureFlags)// Only surface the build version on self-hosted deployments. The managed// cloud is continuously deployed and its users can't choose the build, sodiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex c4c85ccc91..d25850a77a 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -77,6 +77,10 @@ type Config struct {// invitation only. The public /api/config endpoint mirrors this flag so// the UI can hide every "Create workspace" affordance — see #3433.DisableWorkspaceCreation bool+ // DisableStarPrompt turns off the "Star us on GitHub" prompt for every+ // user of the deployment: /api/config tells clients not to show it, and+ // claiming a showing is refused. The Help menu link is unaffected.+ DisableStarPrompt bool// WorkspaceCreationAllowedEmails, when non-empty, restricts// POST /api/workspaces to callers whose account email matches one of// the entries (case-insensitive). Empty means every signed-in user maydiff --git a/server/internal/handler/star_prompt.go b/server/internal/handler/star_prompt.gonew file mode 100644index 0000000000..7174d6a28c--- /dev/null+++ b/server/internal/handler/star_prompt.go@@ -0,0 +1,70 @@+package handler++import (+ "errors"+ "net/http"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Frequency rules for the "Star us on GitHub" prompt. The client mirrors them+// to avoid pointless claims; these are the authority.+const (+ starPromptMaxShowings = 2+ starPromptCooldown = 30 * 24 * time.Hour+ starPromptMinAccountAge = 3 * 24 * time.Hour+)++// ClaimStarPromptShowing grants the caller one showing of the star prompt.+// The client asks before showing, so 409 means "do not show" and covers a+// second tab or device that reacted to the same moment.+func (h *Handler) ClaimStarPromptShowing(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ if h.cfg.DisableStarPrompt {+ writeError(w, http.StatusConflict, "star prompt is disabled")+ return+ }+ now := time.Now()+ user, err := h.Queries.ClaimStarPromptShowing(r.Context(), db.ClaimStarPromptShowingParams{+ ID: parseUUID(userID),+ MaxShowings: starPromptMaxShowings,+ CreatedBefore: pgtype.Timestamptz{Time: now.Add(-starPromptMinAccountAge), Valid: true},+ ShownBefore: pgtype.Timestamptz{Time: now.Add(-starPromptCooldown), Valid: true},+ })+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusConflict, "star prompt is not due")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to claim star prompt")+ return+ }+ writeJSON(w, http.StatusOK, h.userToResponse(user))+}++// MarkStarPromptStarred records that the user clicked through to GitHub, which+// retires the prompt for good. GitHub cannot confirm the star, so the click+// stands in for it.+func (h *Handler) MarkStarPromptStarred(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ user, err := h.Queries.MarkStarPromptStarred(r.Context(), parseUUID(userID))+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusUnauthorized, "user not found")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update star prompt")+ return+ }+ writeJSON(w, http.StatusOK, h.userToResponse(user))+}diff --git a/server/internal/handler/star_prompt_test.go b/server/internal/handler/star_prompt_test.gonew file mode 100644index 0000000000..f887b9c35d--- /dev/null+++ b/server/internal/handler/star_prompt_test.go@@ -0,0 +1,238 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/uuid"+)++func callStarPrompt(t *testing.T, userID, action string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest("POST", "/api/me/star-prompt/"+action, nil)+ req.Header.Set("X-User-ID", userID)+ w := httptest.NewRecorder()+ switch action {+ case "claim":+ testHandler.ClaimStarPromptShowing(w, req)+ case "starred":+ testHandler.MarkStarPromptStarred(w, req)+ default:+ t.Fatalf("unknown action %q", action)+ }+ return w+}++func starPromptUser(t *testing.T, email string, accountAgeDays int) string {+ t.Helper()+ userID := newWaitlistTestUser(t, email)+ if _, err := testPool.Exec(context.Background(),+ `UPDATE "user" SET created_at = now() - make_interval(days => $2) WHERE id = $1`,+ userID, accountAgeDays,+ ); err != nil {+ t.Fatalf("backdate user: %v", err)+ }+ return userID+}++func storedStarPromptShownCount(t *testing.T, userID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(),+ `SELECT star_prompt_shown_count FROM "user" WHERE id = $1`, userID,+ ).Scan(&n); err != nil {+ t.Fatalf("lookup user: %v", err)+ }+ return n+}++func backdateStarPromptShowing(t *testing.T, userID string, days int) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(),+ `UPDATE "user" SET star_prompt_last_shown_at = now() - make_interval(days => $2) WHERE id = $1`,+ userID, days,+ ); err != nil {+ t.Fatalf("backdate showing: %v", err)+ }+}++func TestClaimStarPromptShowingFrequency(t *testing.T) {+ userID := starPromptUser(t, "[email protected]", 4)++ w := callStarPrompt(t, userID, "claim")+ if w.Code != http.StatusOK {+ t.Fatalf("first claim: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp UserResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.StarPromptShownCount != 1 || resp.StarPromptLastShownAt == nil {+ t.Fatalf("first claim: got count %d, last shown %v", resp.StarPromptShownCount, resp.StarPromptLastShownAt)+ }++ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusConflict {+ t.Fatalf("claim inside cooldown: expected 409, got %d", w.Code)+ }++ backdateStarPromptShowing(t, userID, 31)+ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusOK {+ t.Fatalf("claim after cooldown: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ backdateStarPromptShowing(t, userID, 31)+ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusConflict {+ t.Fatalf("claim past the last showing: expected 409, got %d", w.Code)+ }+ if n := storedStarPromptShownCount(t, userID); n != 2 {+ t.Fatalf("stored count = %d, want 2", n)+ }+}++func TestClaimStarPromptShowingWaitsForAccountAge(t *testing.T) {+ userID := starPromptUser(t, "[email protected]", 1)++ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusConflict {+ t.Fatalf("claim on a new account: expected 409, got %d", w.Code)+ }+ if n := storedStarPromptShownCount(t, userID); n != 0 {+ t.Fatalf("refused claim must not write, got count %d", n)+ }+}++func TestStarPromptStarredRetiresThePrompt(t *testing.T) {+ userID := starPromptUser(t, "[email protected]", 4)++ w := callStarPrompt(t, userID, "starred")+ if w.Code != http.StatusOK {+ t.Fatalf("starred: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var first UserResponse+ if err := json.Unmarshal(w.Body.Bytes(), &first); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if first.StarPromptStarredAt == nil {+ t.Fatal("starred_at should be set")+ }++ var again UserResponse+ if err := json.Unmarshal(callStarPrompt(t, userID, "starred").Body.Bytes(), &again); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if again.StarPromptStarredAt == nil || *again.StarPromptStarredAt != *first.StarPromptStarredAt {+ t.Fatalf("repeat click must keep the first time: %v vs %v", again.StarPromptStarredAt, first.StarPromptStarredAt)+ }++ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusConflict {+ t.Fatalf("claim after starring: expected 409, got %d", w.Code)+ }+}++func TestClaimStarPromptShowingHonoursDeploymentSwitch(t *testing.T) {+ userID := starPromptUser(t, "[email protected]", 4)+ prev := testHandler.cfg.DisableStarPrompt+ t.Cleanup(func() { testHandler.cfg.DisableStarPrompt = prev })+ testHandler.cfg.DisableStarPrompt = true++ if w := callStarPrompt(t, userID, "claim"); w.Code != http.StatusConflict {+ t.Fatalf("claim while disabled: expected 409, got %d", w.Code)+ }+ if n := storedStarPromptShownCount(t, userID); n != 0 {+ t.Fatalf("refused claim must not write, got count %d", n)+ }++ req := httptest.NewRequest("GET", "/api/config", nil)+ rec := httptest.NewRecorder()+ testHandler.GetConfig(rec, req)+ var cfg AppConfig+ if err := json.Unmarshal(rec.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if !cfg.StarPromptDisabled {+ t.Fatal("config should report the star prompt as disabled")+ }+}++func TestGetMeAlwaysSerializesStarPromptCount(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")++ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("X-User-ID", userID)+ w := httptest.NewRecorder()+ testHandler.GetMe(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var raw map[string]json.RawMessage+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if got, ok := raw["star_prompt_shown_count"]; !ok || string(got) != "0" {+ t.Fatalf("star_prompt_shown_count must be present and 0 for a fresh user, got %s (present=%v)", got, ok)+ }+}++// The star prompt counts an agent's finished issues by lifecycle category, so+// a workspace that finishes work in a custom done status still qualifies.+func TestListIssuesCountsAgentDoneCategoryIncludingCustomStatuses(t *testing.T) {+ ctx := context.Background()+ suffix := time.Now().UnixNano()+ customKey := fmt.Sprintf("shipped_%d", suffix)+ agentID := uuid.NewString()++ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_status (workspace_id, key, name, description, category, color, position)+ VALUES ($1, $2, 'Shipped', '', 'done', '#00aa00', 1)+ `, testWorkspaceID, customKey); err != nil {+ t.Fatalf("create custom status: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE assignee_id = $1`, agentID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE workspace_id = $1 AND key = $2`, testWorkspaceID, customKey)+ })++ var firstNumber int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(+ issue_counter,+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)+ ) + 4+ WHERE id = $1+ RETURNING issue_counter - 3+ `, testWorkspaceID).Scan(&firstNumber); err != nil {+ t.Fatalf("reserve issue numbers: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, assignee_type, assignee_id, position, number)+ VALUES+ ($1, 'built-in done', 'done', 'none', 'member', $3, 'agent', $4, 1, $5),+ ($1, 'custom done', $2, 'none', 'member', $3, 'agent', $4, 2, $5 + 1),+ ($1, 'cancelled', 'cancelled', 'none', 'member', $3, 'agent', $4, 3, $5 + 2),+ ($1, 'in review', 'in_review', 'none', 'member', $3, 'agent', $4, 4, $5 + 3)+ `, testWorkspaceID, customKey, testUserID, agentID, firstNumber); err != nil {+ t.Fatalf("seed issues: %v", err)+ }++ path := fmt.Sprintf("/api/issues?workspace_id=%s&status_categories=done&assignee_filters=agent:%s&limit=1",+ testWorkspaceID, agentID)+ w := httptest.NewRecorder()+ testHandler.ListIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListIssues: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Total int64 `json:"total"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode list response: %v", err)+ }+ if resp.Total != 2 {+ t.Fatalf("done-category total = %d, want 2 (built-in done + custom done)", resp.Total)+ }+}diff --git a/server/migrations/629_user_star_prompt.down.sql b/server/migrations/629_user_star_prompt.down.sqlnew file mode 100644index 0000000000..c7ad74fcb5--- /dev/null+++ b/server/migrations/629_user_star_prompt.down.sql@@ -0,0 +1,3 @@+ALTER TABLE "user" DROP COLUMN IF EXISTS star_prompt_starred_at;+ALTER TABLE "user" DROP COLUMN IF EXISTS star_prompt_last_shown_at;+ALTER TABLE "user" DROP COLUMN IF EXISTS star_prompt_shown_count;diff --git a/server/migrations/629_user_star_prompt.up.sql b/server/migrations/629_user_star_prompt.up.sqlnew file mode 100644index 0000000000..dbc639adea--- /dev/null+++ b/server/migrations/629_user_star_prompt.up.sql@@ -0,0 +1,6 @@+-- Bookkeeping for the "Star us on GitHub" prompt. The prompt shows a bounded+-- number of times with a cooldown between showings, and never again once the+-- user clicks through to GitHub.+ALTER TABLE "user" ADD COLUMN IF NOT EXISTS star_prompt_shown_count INTEGER NOT NULL DEFAULT 0;+ALTER TABLE "user" ADD COLUMN IF NOT EXISTS star_prompt_last_shown_at TIMESTAMPTZ;+ALTER TABLE "user" ADD COLUMN IF NOT EXISTS star_prompt_starred_at TIMESTAMPTZ;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex a2cf087231..e339625336 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1763,8 +1763,11 @@ type User struct {Language pgtype.Text `json:"language"`ProfileDescription string `json:"profile_description"`// User-preferred IANA timezone for report rendering (Viewing tz). NULL means "use the browser-detected tz at render time". Affects dashboards, charts, and any "today" label shown to this user. Does not affect data materialisation — all rollups remain in UTC.- Timezone pgtype.Text `json:"timezone"`- WhatsNewSeenVersion pgtype.Text `json:"whats_new_seen_version"`+ Timezone pgtype.Text `json:"timezone"`+ WhatsNewSeenVersion pgtype.Text `json:"whats_new_seen_version"`+ StarPromptShownCount int32 `json:"star_prompt_shown_count"`+ StarPromptLastShownAt pgtype.Timestamptz `json:"star_prompt_last_shown_at"`+ StarPromptStarredAt pgtype.Timestamptz `json:"star_prompt_starred_at"`}type UserComposioConnection struct {diff --git a/server/pkg/db/generated/user.sql.go b/server/pkg/db/generated/user.sql.goindex 624f6099e0..0f4c19e2c8 100644--- a/server/pkg/db/generated/user.sql.go+++ b/server/pkg/db/generated/user.sql.go@@ -20,7 +20,7 @@ WHERE id = $2whats_new_seen_version IS NULLOR string_to_array(whats_new_seen_version, '.')::int[] < string_to_array($1::text, '.')::int[])-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`type AdvanceWhatsNewSeenVersionParams struct {@@ -52,6 +52,63 @@ func (q *Queries) AdvanceWhatsNewSeenVersion(ctx context.Context, arg AdvanceWha&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,+ )+ return i, err+}++const claimStarPromptShowing = `-- name: ClaimStarPromptShowing :one+UPDATE "user" SET+ star_prompt_shown_count = star_prompt_shown_count + 1,+ star_prompt_last_shown_at = now()+WHERE id = $1+ AND star_prompt_starred_at IS NULL+ AND star_prompt_shown_count < $2::int+ AND created_at <= $3::timestamptz+ AND (star_prompt_last_shown_at IS NULL OR star_prompt_last_shown_at <= $4::timestamptz)+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at+`++type ClaimStarPromptShowingParams struct {+ ID pgtype.UUID `json:"id"`+ MaxShowings int32 `json:"max_showings"`+ CreatedBefore pgtype.Timestamptz `json:"created_before"`+ ShownBefore pgtype.Timestamptz `json:"shown_before"`+}++// Grants one showing of the star prompt, atomically, so two tabs or devices+// reacting to the same moment cannot both show it. No row comes back when the+// user already starred, used up the showings, is inside the cooldown, or has+// an account newer than the cutoff.+func (q *Queries) ClaimStarPromptShowing(ctx context.Context, arg ClaimStarPromptShowingParams) (User, error) {+ row := q.db.QueryRow(ctx, claimStarPromptShowing,+ arg.ID,+ arg.MaxShowings,+ arg.CreatedBefore,+ arg.ShownBefore,+ )+ var i User+ err := row.Scan(+ &i.ID,+ &i.Name,+ &i.Email,+ &i.AvatarUrl,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OnboardedAt,+ &i.OnboardingQuestionnaire,+ &i.CloudWaitlistEmail,+ &i.CloudWaitlistReason,+ &i.StarterContentState,+ &i.Language,+ &i.ProfileDescription,+ &i.Timezone,+ &i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}@@ -59,7 +116,7 @@ func (q *Queries) AdvanceWhatsNewSeenVersion(ctx context.Context, arg AdvanceWhaconst createUser = `-- name: CreateUser :oneINSERT INTO "user" (name, email, avatar_url)VALUES ($1, $2, $3)-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`type CreateUserParams struct {@@ -87,12 +144,15 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}const getUser = `-- name: GetUser :one-SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version FROM "user"+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at FROM "user"WHERE id = $1`@@ -115,12 +175,15 @@ func (q *Queries) GetUser(ctx context.Context, id pgtype.UUID) (User, error) {&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}const getUserByEmail = `-- name: GetUserByEmail :one-SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version FROM "user"+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at FROM "user"WHERE email = $1`@@ -143,6 +206,9 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}@@ -193,7 +259,7 @@ UPDATE "user" SETcloud_waitlist_reason = $3,updated_at = now()WHERE id = $1-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`type JoinCloudWaitlistParams struct {@@ -224,6 +290,43 @@ func (q *Queries) JoinCloudWaitlist(ctx context.Context, arg JoinCloudWaitlistPa&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,+ )+ return i, err+}++const markStarPromptStarred = `-- name: MarkStarPromptStarred :one+UPDATE "user" SET+ star_prompt_starred_at = COALESCE(star_prompt_starred_at, now())+WHERE id = $1+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at+`++// Keeps the first click time; repeating the call is a no-op.+func (q *Queries) MarkStarPromptStarred(ctx context.Context, id pgtype.UUID) (User, error) {+ row := q.db.QueryRow(ctx, markStarPromptStarred, id)+ var i User+ err := row.Scan(+ &i.ID,+ &i.Name,+ &i.Email,+ &i.AvatarUrl,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OnboardedAt,+ &i.OnboardingQuestionnaire,+ &i.CloudWaitlistEmail,+ &i.CloudWaitlistReason,+ &i.StarterContentState,+ &i.Language,+ &i.ProfileDescription,+ &i.Timezone,+ &i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}@@ -233,7 +336,7 @@ UPDATE "user" SETonboarded_at = COALESCE(onboarded_at, now()),updated_at = now()WHERE id = $1-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`func (q *Queries) MarkUserOnboarded(ctx context.Context, id pgtype.UUID) (User, error) {@@ -255,6 +358,9 @@ func (q *Queries) MarkUserOnboarded(ctx context.Context, id pgtype.UUID) (User,&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}@@ -264,7 +370,7 @@ UPDATE "user" SETonboarding_questionnaire = COALESCE($1, onboarding_questionnaire),updated_at = now()WHERE id = $2-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`type PatchUserOnboardingParams struct {@@ -295,6 +401,9 @@ func (q *Queries) PatchUserOnboarding(ctx context.Context, arg PatchUserOnboardi&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}@@ -312,7 +421,7 @@ UPDATE "user" SETEND,updated_at = now()WHERE id = $1-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone, whats_new_seen_version, star_prompt_shown_count, star_prompt_last_shown_at, star_prompt_starred_at`type UpdateUserParams struct {@@ -362,6 +471,9 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, e&i.ProfileDescription,&i.Timezone,&i.WhatsNewSeenVersion,+ &i.StarPromptShownCount,+ &i.StarPromptLastShownAt,+ &i.StarPromptStarredAt,)return i, err}diff --git a/server/pkg/db/queries/user.sql b/server/pkg/db/queries/user.sqlindex 3a273097d3..b05c4e812c 100644--- a/server/pkg/db/queries/user.sql+++ b/server/pkg/db/queries/user.sql@@ -79,6 +79,28 @@ WHERE id = sqlc.arg('id'))RETURNING *;+-- name: ClaimStarPromptShowing :one+-- Grants one showing of the star prompt, atomically, so two tabs or devices+-- reacting to the same moment cannot both show it. No row comes back when the+-- user already starred, used up the showings, is inside the cooldown, or has+-- an account newer than the cutoff.+UPDATE "user" SET+ star_prompt_shown_count = star_prompt_shown_count + 1,+ star_prompt_last_shown_at = now()+WHERE id = sqlc.arg('id')+ AND star_prompt_starred_at IS NULL+ AND star_prompt_shown_count < sqlc.arg('max_showings')::int+ AND created_at <= sqlc.arg('created_before')::timestamptz+ AND (star_prompt_last_shown_at IS NULL OR star_prompt_last_shown_at <= sqlc.arg('shown_before')::timestamptz)+RETURNING *;++-- name: MarkStarPromptStarred :one+-- Keeps the first click time; repeating the call is a no-op.+UPDATE "user" SET+ star_prompt_starred_at = COALESCE(star_prompt_starred_at, now())+WHERE id = $1+RETURNING *;+-- name: JoinCloudWaitlist :one-- Records interest in cloud runtimes. Does NOT mark onboarding-- complete — the user still has to pick a real path (CLI / Skip)