feat: scope GitHub integration settings by workspace (#1572)
This commit is contained in:
@@ -127,9 +127,11 @@ function QueryEditor({
|
||||
);
|
||||
}
|
||||
|
||||
export function DefaultQueriesSection() {
|
||||
export function DefaultQueriesSection({ workspaceId }: { workspaceId?: string }) {
|
||||
const { toast } = useToast();
|
||||
const { prPresets, issuePresets, save, reset, isCustomized } = useDefaultQueryPresets();
|
||||
const { prPresets, issuePresets, save, reset, isCustomized } = useDefaultQueryPresets(
|
||||
workspaceId ?? null,
|
||||
);
|
||||
const [prDraft, setPrDraft] = useState<StoredQueryPreset[]>(prPresets);
|
||||
const [issueDraft, setIssueDraft] = useState<StoredQueryPreset[]>(issuePresets);
|
||||
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Card, CardContent } from "@kandev/ui/card";
|
||||
import { Input } from "@kandev/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { SettingsSection } from "@/components/settings/settings-section";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
updateGitHubWorkspaceSettings,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import type { GitHubRepoScopeMode, RepoFilter } from "@/lib/types/github";
|
||||
|
||||
function splitCSV(value: string): string[] {
|
||||
return value
|
||||
.split(",")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseRepoFilters(value: string): RepoFilter[] {
|
||||
return splitCSV(value)
|
||||
.map((repo) => {
|
||||
const [owner, name, ...rest] = repo.split("/");
|
||||
if (!owner || !name || rest.length > 0) return null;
|
||||
return { owner, name };
|
||||
})
|
||||
.filter((repo): repo is RepoFilter => repo !== null);
|
||||
}
|
||||
|
||||
function repoFiltersToInput(repos: RepoFilter[]): string {
|
||||
return repos.map((repo) => `${repo.owner}/${repo.name}`).join(", ");
|
||||
}
|
||||
|
||||
type ScopeFieldsProps = {
|
||||
mode: GitHubRepoScopeMode;
|
||||
orgs: string;
|
||||
repos: string;
|
||||
loading: boolean;
|
||||
invalidRepos: boolean;
|
||||
onModeChange: (mode: GitHubRepoScopeMode) => void;
|
||||
onOrgsChange: (orgs: string) => void;
|
||||
onReposChange: (repos: string) => void;
|
||||
};
|
||||
|
||||
function RepositoryScopeFields({
|
||||
mode,
|
||||
orgs,
|
||||
repos,
|
||||
loading,
|
||||
invalidRepos,
|
||||
onModeChange,
|
||||
onOrgsChange,
|
||||
onReposChange,
|
||||
}: ScopeFieldsProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="grid gap-4 py-4 md:grid-cols-[220px_minmax(0,1fr)]">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium" htmlFor="github-scope-mode">
|
||||
Mode
|
||||
</label>
|
||||
<Select
|
||||
value={mode}
|
||||
onValueChange={(value) => onModeChange(value as GitHubRepoScopeMode)}
|
||||
disabled={loading}
|
||||
>
|
||||
<SelectTrigger id="github-scope-mode" data-testid="github-scope-mode">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All repositories</SelectItem>
|
||||
<SelectItem value="orgs">Organizations</SelectItem>
|
||||
<SelectItem value="repos">Selected repositories</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium" htmlFor="github-scope-orgs">
|
||||
Organizations
|
||||
</label>
|
||||
<Input
|
||||
id="github-scope-orgs"
|
||||
value={orgs}
|
||||
onChange={(event) => onOrgsChange(event.target.value)}
|
||||
disabled={loading || mode !== "orgs"}
|
||||
placeholder="kdlbs, example-org"
|
||||
data-testid="github-scope-orgs-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium" htmlFor="github-scope-repos">
|
||||
Repositories
|
||||
</label>
|
||||
<Input
|
||||
id="github-scope-repos"
|
||||
value={repos}
|
||||
onChange={(event) => onReposChange(event.target.value)}
|
||||
disabled={loading || mode !== "repos"}
|
||||
aria-invalid={invalidRepos}
|
||||
placeholder="kdlbs/kandev, example/api"
|
||||
data-testid="github-scope-repos-input"
|
||||
/>
|
||||
{invalidRepos && (
|
||||
<p className="text-xs text-destructive">Use comma-separated owner/repo values.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function GitHubRepoScopeSection({ workspaceId }: { workspaceId: string }) {
|
||||
const { toast } = useToast();
|
||||
const [mode, setMode] = useState<GitHubRepoScopeMode>("all");
|
||||
const [orgs, setOrgs] = useState("");
|
||||
const [repos, setRepos] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const parsedRepos = useMemo(() => parseRepoFilters(repos), [repos]);
|
||||
const invalidRepos = useMemo(() => {
|
||||
const entries = splitCSV(repos);
|
||||
return entries.length > 0 && parsedRepos.length !== entries.length;
|
||||
}, [parsedRepos.length, repos]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
void fetchGitHubWorkspaceSettings(workspaceId)
|
||||
.then((settings) => {
|
||||
if (cancelled) return;
|
||||
setMode(settings.repo_scope_mode ?? "all");
|
||||
setOrgs((settings.repo_scope_orgs ?? []).join(", "));
|
||||
setRepos(repoFiltersToInput(settings.repo_scope_repos ?? []));
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled)
|
||||
toast({ description: "Failed to load GitHub workspace settings", variant: "error" });
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [toast, workspaceId]);
|
||||
|
||||
const save = async () => {
|
||||
if (invalidRepos) {
|
||||
toast({ description: "Repository filters must use owner/repo format", variant: "error" });
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await updateGitHubWorkspaceSettings({
|
||||
workspace_id: workspaceId,
|
||||
repo_scope_mode: mode,
|
||||
repo_scope_orgs: splitCSV(orgs),
|
||||
repo_scope_repos: parsedRepos,
|
||||
});
|
||||
setMode(updated.repo_scope_mode);
|
||||
setOrgs((updated.repo_scope_orgs ?? []).join(", "));
|
||||
setRepos(repoFiltersToInput(updated.repo_scope_repos ?? []));
|
||||
toast({ description: "GitHub workspace settings saved", variant: "success" });
|
||||
} catch {
|
||||
toast({ description: "Failed to save GitHub workspace settings", variant: "error" });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsSection
|
||||
title="Repository Scope"
|
||||
description="Choose which GitHub repositories belong to this workspace."
|
||||
action={
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={save}
|
||||
disabled={loading || saving}
|
||||
data-testid="github-scope-save"
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{saving ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<RepositoryScopeFields
|
||||
mode={mode}
|
||||
orgs={orgs}
|
||||
repos={repos}
|
||||
loading={loading}
|
||||
invalidRepos={invalidRepos}
|
||||
onModeChange={setMode}
|
||||
onOrgsChange={setOrgs}
|
||||
onReposChange={setRepos}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { IssueWatchTable } from "./issue-watch-table";
|
||||
import { IssueWatchDialog } from "./issue-watch-dialog";
|
||||
import { ActionPresetsSection } from "./action-presets-section";
|
||||
import { DefaultQueriesSection } from "./default-queries-section";
|
||||
import { GitHubRepoScopeSection } from "./github-repo-scope-section";
|
||||
import { PRStatsPanel } from "./pr-stats";
|
||||
import { useReviewWatches } from "@/hooks/domains/github/use-review-watches";
|
||||
import { useIssueWatches } from "@/hooks/domains/github/use-issue-watches";
|
||||
@@ -80,14 +81,19 @@ function useWatchActions(workspaceId?: string | null) {
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: string) => {
|
||||
const watch = watches.find((item) => item.id === id);
|
||||
if (!watch) {
|
||||
toast({ description: "Review watch not found", variant: "error" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await remove(id);
|
||||
await remove(id, watch.workspace_id);
|
||||
toast({ description: "Review watch deleted", variant: "success" });
|
||||
} catch {
|
||||
toast({ description: "Failed to delete review watch", variant: "error" });
|
||||
}
|
||||
},
|
||||
[remove, toast],
|
||||
[remove, toast, watches],
|
||||
);
|
||||
|
||||
const handleTrigger = useCallback(
|
||||
@@ -118,7 +124,7 @@ function useWatchActions(workspaceId?: string | null) {
|
||||
const handleToggleEnabled = useCallback(
|
||||
async (watch: ReviewWatch) => {
|
||||
try {
|
||||
await update(watch.id, { enabled: !watch.enabled });
|
||||
await update(watch.id, watch.workspace_id, { enabled: !watch.enabled });
|
||||
toast({
|
||||
description: watch.enabled ? "Watch paused" : "Watch enabled",
|
||||
variant: "success",
|
||||
@@ -175,20 +181,30 @@ function useIssueWatchActions(workspaceId?: string | null) {
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: string) => {
|
||||
const watch = watches.find((item) => item.id === id);
|
||||
if (!watch) {
|
||||
toast({ description: "Issue watch not found", variant: "error" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await remove(id);
|
||||
await remove(id, watch.workspace_id);
|
||||
toast({ description: "Issue watch deleted", variant: "success" });
|
||||
} catch {
|
||||
toast({ description: "Failed to delete issue watch", variant: "error" });
|
||||
}
|
||||
},
|
||||
[remove, toast],
|
||||
[remove, toast, watches],
|
||||
);
|
||||
|
||||
const handleTrigger = useCallback(
|
||||
async (id: string) => {
|
||||
const watch = watches.find((item) => item.id === id);
|
||||
if (!watch) {
|
||||
toast({ description: "Issue watch not found", variant: "error" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await trigger(id);
|
||||
const result = await trigger(id, watch.workspace_id);
|
||||
const count = result?.new_issues_found ?? 0;
|
||||
if (count > 0) {
|
||||
toast({
|
||||
@@ -202,13 +218,13 @@ function useIssueWatchActions(workspaceId?: string | null) {
|
||||
toast({ description: "Failed to check for issues", variant: "error" });
|
||||
}
|
||||
},
|
||||
[trigger, toast],
|
||||
[trigger, toast, watches],
|
||||
);
|
||||
|
||||
const handleToggleEnabled = useCallback(
|
||||
async (watch: IssueWatch) => {
|
||||
try {
|
||||
await update(watch.id, { enabled: !watch.enabled });
|
||||
await update(watch.id, watch.workspace_id, { enabled: !watch.enabled });
|
||||
toast({
|
||||
description: watch.enabled ? "Watch paused" : "Watch enabled",
|
||||
variant: "success",
|
||||
@@ -276,16 +292,17 @@ export function GitHubConnectionSection() {
|
||||
);
|
||||
}
|
||||
|
||||
// PerWorkspaceSection wraps the still-per-workspace surfaces (action presets,
|
||||
// PR analytics) under a workspace switcher. Watchers don't go in here — they
|
||||
// list flat across every workspace via their own sections.
|
||||
function PerWorkspaceSection({ workspaceId }: { workspaceId: string }) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<GitHubRepoScopeSection workspaceId={workspaceId} />
|
||||
<ReviewWatchSection workspaceId={workspaceId} />
|
||||
<IssueWatchSection workspaceId={workspaceId} />
|
||||
<ActionPresetsSection workspaceId={workspaceId} />
|
||||
<SettingsSection title="PR Analytics" description="Pull request activity for this workspace.">
|
||||
<PRStatsPanel workspaceId={workspaceId} />
|
||||
</SettingsSection>
|
||||
<DefaultQueriesSection workspaceId={workspaceId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -295,21 +312,15 @@ export function GitHubIntegrationPage() {
|
||||
<TooltipProvider>
|
||||
<div className="space-y-8">
|
||||
<GitHubConnectionSection />
|
||||
<ReviewWatchSection />
|
||||
<IssueWatchSection />
|
||||
<WorkspaceScopedSection label="Presets and analytics for">
|
||||
<WorkspaceScopedSection showSelector={false}>
|
||||
{(ws) => <PerWorkspaceSection key={ws} workspaceId={ws} />}
|
||||
</WorkspaceScopedSection>
|
||||
<DefaultQueriesSection />
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// ReviewWatchSection lists every review watch across every workspace in a
|
||||
// single flat table. Pass `undefined` to the hook so it fetches all rows; the
|
||||
// dialog's create flow asks the user to pick the workspace.
|
||||
function ReviewWatchSection() {
|
||||
function ReviewWatchSection({ workspaceId }: { workspaceId: string }) {
|
||||
const {
|
||||
watches,
|
||||
create,
|
||||
@@ -319,7 +330,7 @@ function ReviewWatchSection() {
|
||||
handleTrigger,
|
||||
handleReset,
|
||||
handleToggleEnabled,
|
||||
} = useWatchActions(undefined);
|
||||
} = useWatchActions(workspaceId);
|
||||
const { toast } = useToast();
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingWatch, setEditingWatch] = useState<ReviewWatch | null>(null);
|
||||
@@ -349,7 +360,10 @@ function ReviewWatchSection() {
|
||||
description="Automatically create tasks for PRs that need your review."
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
<CleanupNowButton label="Clean up merged" run={cleanupMergedReviewTasks} />
|
||||
<CleanupNowButton
|
||||
label="Clean up merged"
|
||||
run={() => cleanupMergedReviewTasks(workspaceId)}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
@@ -368,7 +382,6 @@ function ReviewWatchSection() {
|
||||
<CardContent className="p-0">
|
||||
<ReviewWatchTable
|
||||
watches={watches}
|
||||
showWorkspace
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onTrigger={handleTrigger}
|
||||
@@ -382,13 +395,15 @@ function ReviewWatchSection() {
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
watch={editingWatch}
|
||||
// No workspaceId — dialog shows a workspace picker for new watches.
|
||||
workspaceId={workspaceId}
|
||||
onCreate={async (req) => {
|
||||
await create(req);
|
||||
toast({ description: "Review watch created", variant: "success" });
|
||||
}}
|
||||
onUpdate={async (id, req) => {
|
||||
await update(id, req);
|
||||
const watch = watches.find((item) => item.id === id);
|
||||
if (!watch) throw new Error("review watch not found");
|
||||
await update(id, watch.workspace_id, req);
|
||||
toast({ description: "Review watch updated", variant: "success" });
|
||||
}}
|
||||
/>
|
||||
@@ -405,8 +420,8 @@ function ReviewWatchSection() {
|
||||
);
|
||||
}
|
||||
|
||||
function IssueWatchSection() {
|
||||
const issueActions = useIssueWatchActions(undefined);
|
||||
function IssueWatchSection({ workspaceId }: { workspaceId: string }) {
|
||||
const issueActions = useIssueWatchActions(workspaceId);
|
||||
const { toast } = useToast();
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingWatch, setEditingIssueWatch] = useState<IssueWatch | null>(null);
|
||||
@@ -436,7 +451,10 @@ function IssueWatchSection() {
|
||||
description="Automatically create tasks for GitHub issues matching your criteria."
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
<CleanupNowButton label="Clean up closed" run={cleanupClosedIssueTasks} />
|
||||
<CleanupNowButton
|
||||
label="Clean up closed"
|
||||
run={() => cleanupClosedIssueTasks(workspaceId)}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
@@ -455,7 +473,6 @@ function IssueWatchSection() {
|
||||
<CardContent className="p-0">
|
||||
<IssueWatchTable
|
||||
watches={issueActions.watches}
|
||||
showWorkspace
|
||||
onEdit={handleEdit}
|
||||
onDelete={issueActions.handleDelete}
|
||||
onTrigger={issueActions.handleTrigger}
|
||||
@@ -469,12 +486,15 @@ function IssueWatchSection() {
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
watch={editingWatch}
|
||||
workspaceId={workspaceId}
|
||||
onCreate={async (req) => {
|
||||
await issueActions.create(req);
|
||||
toast({ description: "Issue watch created", variant: "success" });
|
||||
}}
|
||||
onUpdate={async (id, req) => {
|
||||
await issueActions.update(id, req);
|
||||
const watch = issueActions.watches.find((item) => item.id === id);
|
||||
if (!watch) throw new Error("issue watch not found");
|
||||
await issueActions.update(id, watch.workspace_id, req);
|
||||
toast({ description: "Issue watch updated", variant: "success" });
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -237,6 +237,7 @@ function IssueFilterFields({
|
||||
selectedRepos={form.selectedRepos}
|
||||
onAllReposChange={onAllReposChange}
|
||||
onSelectedReposChange={onSelectedReposChange}
|
||||
workspaceId={form.workspaceId}
|
||||
/>
|
||||
<div className="space-y-1.5">
|
||||
<Label>Labels (comma-separated)</Label>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { fetchUserSettings, updateUserSettings } from "@/lib/api/domains/settings-api";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
updateGitHubWorkspaceSettings,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import {
|
||||
__resetSnapshotForTests,
|
||||
useDefaultQueryPresets,
|
||||
@@ -9,12 +13,19 @@ import {
|
||||
|
||||
const STORAGE_KEY = "kandev:github-default-queries:v1";
|
||||
const SYNC_FAILED_KEY = "kandev:github-default-queries:sync-failed:v1";
|
||||
const WORKSPACE_ID = "ws-1";
|
||||
const SETTINGS_TIMESTAMP = "2026-01-01T00:00:00Z";
|
||||
|
||||
vi.mock("@/lib/api/domains/settings-api", () => ({
|
||||
fetchUserSettings: vi.fn(),
|
||||
updateUserSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/github-api", () => ({
|
||||
fetchGitHubWorkspaceSettings: vi.fn(),
|
||||
updateGitHubWorkspaceSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
function makeLocalStorageMock() {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
@@ -31,6 +42,7 @@ function makeLocalStorageMock() {
|
||||
|
||||
const localStorageMock = makeLocalStorageMock();
|
||||
vi.stubGlobal("localStorage", localStorageMock);
|
||||
Object.defineProperty(window, "localStorage", { value: localStorageMock, configurable: true });
|
||||
|
||||
const preset: StoredQueryPreset = {
|
||||
value: "mine",
|
||||
@@ -39,18 +51,39 @@ const preset: StoredQueryPreset = {
|
||||
group: "created",
|
||||
};
|
||||
|
||||
describe("useDefaultQueryPresets", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorageMock.clear();
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchUserSettings).mockResolvedValue({
|
||||
settings: { github_default_query_presets: null },
|
||||
} as Awaited<ReturnType<typeof fetchUserSettings>>);
|
||||
vi.mocked(updateUserSettings).mockResolvedValue({
|
||||
settings: {},
|
||||
} as Awaited<ReturnType<typeof updateUserSettings>>);
|
||||
});
|
||||
function workspaceSettings(
|
||||
defaultQueryPresets: unknown = null,
|
||||
): Awaited<ReturnType<typeof fetchGitHubWorkspaceSettings>> {
|
||||
return {
|
||||
workspace_id: WORKSPACE_ID,
|
||||
repo_scope_mode: "all",
|
||||
repo_scope_orgs: [],
|
||||
repo_scope_repos: [],
|
||||
saved_presets: [],
|
||||
default_query_presets: defaultQueryPresets,
|
||||
created_at: SETTINGS_TIMESTAMP,
|
||||
updated_at: SETTINGS_TIMESTAMP,
|
||||
} as Awaited<ReturnType<typeof fetchGitHubWorkspaceSettings>>;
|
||||
}
|
||||
|
||||
function resetMocks() {
|
||||
vi.clearAllMocks();
|
||||
localStorageMock.clear();
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchUserSettings).mockResolvedValue({
|
||||
settings: { github_default_query_presets: null },
|
||||
} as Awaited<ReturnType<typeof fetchUserSettings>>);
|
||||
vi.mocked(updateUserSettings).mockResolvedValue({
|
||||
settings: {},
|
||||
} as Awaited<ReturnType<typeof updateUserSettings>>);
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockResolvedValue(workspaceSettings());
|
||||
vi.mocked(updateGitHubWorkspaceSettings).mockResolvedValue(
|
||||
{} as Awaited<ReturnType<typeof updateGitHubWorkspaceSettings>>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("useDefaultQueryPresets legacy sync", () => {
|
||||
beforeEach(resetMocks);
|
||||
|
||||
it("retries local defaults after a failed backend sync and clears the marker", async () => {
|
||||
const local = { pr: [preset], issue: [] };
|
||||
@@ -115,3 +148,59 @@ describe("useDefaultQueryPresets", () => {
|
||||
expect(updateUserSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useDefaultQueryPresets workspace sync", () => {
|
||||
beforeEach(resetMocks);
|
||||
|
||||
it("migrates local defaults into a fresh workspace", async () => {
|
||||
const local = { pr: [preset], issue: [] };
|
||||
localStorageMock.setItem(STORAGE_KEY, JSON.stringify(local));
|
||||
__resetSnapshotForTests();
|
||||
|
||||
const { result } = renderHook(() => useDefaultQueryPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(result.current.prPresets[0]?.value).toBe("mine"));
|
||||
expect(updateGitHubWorkspaceSettings).toHaveBeenCalledWith({
|
||||
workspace_id: WORKSPACE_ID,
|
||||
default_query_presets: local,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not migrate local defaults over existing workspace defaults", async () => {
|
||||
const server = { pr: [{ ...preset, value: "server", label: "Server" }], issue: [] };
|
||||
localStorageMock.setItem(STORAGE_KEY, JSON.stringify({ pr: [preset], issue: [] }));
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockResolvedValue(workspaceSettings(server));
|
||||
|
||||
const { result } = renderHook(() => useDefaultQueryPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(result.current.prPresets[0]?.value).toBe("server"));
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not save or reset while workspace defaults are still loading", () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockReturnValue(new Promise(() => {}));
|
||||
const { result } = renderHook(() => useDefaultQueryPresets(WORKSPACE_ID));
|
||||
|
||||
act(() => {
|
||||
result.current.save({ pr: [preset], issue: [] });
|
||||
result.current.reset();
|
||||
});
|
||||
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not save or reset after workspace defaults fail to load", async () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockRejectedValue(new Error("settings down"));
|
||||
const { result } = renderHook(() => useDefaultQueryPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(fetchGitHubWorkspaceSettings).toHaveBeenCalled());
|
||||
|
||||
act(() => {
|
||||
result.current.save({ pr: [preset], issue: [] });
|
||||
result.current.reset();
|
||||
});
|
||||
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
PR_PRESETS as BUILTIN_PR_PRESETS,
|
||||
ISSUE_PRESETS as BUILTIN_ISSUE_PRESETS,
|
||||
type PresetOption,
|
||||
} from "./search-bar";
|
||||
import { fetchUserSettings } from "@/lib/api/domains/settings-api";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
updateGitHubWorkspaceSettings,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import { createQueuedUserSettingsSync } from "@/lib/user-settings-sync";
|
||||
import { hasUserSettingsSyncFailure } from "@/lib/user-settings-sync-failure";
|
||||
|
||||
const STORAGE_KEY = "kandev:github-default-queries:v1";
|
||||
const MIGRATED_KEY = "kandev:github-default-queries:migrated-to-backend:v1";
|
||||
const WORKSPACE_MIGRATED_KEY_PREFIX = "kandev:github-default-queries:migrated-to-workspace:v1:";
|
||||
const SYNC_FAILED_KEY = "kandev:github-default-queries:sync-failed:v1";
|
||||
|
||||
export type StoredQueryPreset = {
|
||||
@@ -84,6 +89,16 @@ function readServerDefaults(value: unknown): StoredDefaults | null | undefined {
|
||||
return value as StoredDefaults;
|
||||
}
|
||||
|
||||
async function readLegacyServerDefaults(): Promise<StoredDefaults | null | undefined> {
|
||||
try {
|
||||
const response = await fetchUserSettings({ cache: "no-store" });
|
||||
const defaults = readServerDefaults(response.settings.github_default_query_presets);
|
||||
return defaults === undefined ? null : defaults;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const syncServer = createQueuedUserSettingsSync<StoredDefaults | null>(
|
||||
SYNC_FAILED_KEY,
|
||||
(defaults) => ({
|
||||
@@ -91,6 +106,23 @@ const syncServer = createQueuedUserSettingsSync<StoredDefaults | null>(
|
||||
}),
|
||||
);
|
||||
|
||||
let workspaceSyncQueue = Promise.resolve();
|
||||
|
||||
function syncWorkspaceDefaultQueryPresets(
|
||||
workspaceId: string,
|
||||
defaults: StoredDefaults | null,
|
||||
): Promise<void> {
|
||||
workspaceSyncQueue = workspaceSyncQueue
|
||||
.catch(() => undefined)
|
||||
.then(() =>
|
||||
updateGitHubWorkspaceSettings({
|
||||
workspace_id: workspaceId,
|
||||
default_query_presets: defaults,
|
||||
}).then(() => undefined),
|
||||
);
|
||||
return workspaceSyncQueue;
|
||||
}
|
||||
|
||||
function snapshotKey(value: StoredDefaults | null): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
@@ -109,6 +141,20 @@ function markMigratedToBackend(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function hasMigratedToWorkspace(workspaceId: string): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
return window.localStorage.getItem(WORKSPACE_MIGRATED_KEY_PREFIX + workspaceId) === "1";
|
||||
}
|
||||
|
||||
function markMigratedToWorkspace(workspaceId: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(WORKSPACE_MIGRATED_KEY_PREFIX + workspaceId, "1");
|
||||
} catch {
|
||||
/* ignore storage failures */
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(cb: () => void) {
|
||||
listeners.add(cb);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
@@ -137,10 +183,9 @@ export function __resetSnapshotForTests() {
|
||||
listeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
export function useDefaultQueryPresets() {
|
||||
const stored = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
|
||||
function useLegacyDefaultQueryPresetSync(enabled: boolean) {
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let cancelled = false;
|
||||
const initialKey = snapshotKey(getSnapshot());
|
||||
fetchUserSettings({ cache: "no-store" })
|
||||
@@ -165,24 +210,108 @@ export function useDefaultQueryPresets() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
}, [enabled]);
|
||||
}
|
||||
|
||||
const prPresets = useMemo(() => stored?.pr ?? toStored(BUILTIN_PR_PRESETS), [stored]);
|
||||
const issuePresets = useMemo(() => stored?.issue ?? toStored(BUILTIN_ISSUE_PRESETS), [stored]);
|
||||
|
||||
const save = useCallback((defaults: StoredDefaults) => {
|
||||
publish(defaults);
|
||||
void syncServer(defaults);
|
||||
markMigratedToBackend();
|
||||
function useWorkspaceDefaultQueryPresets(workspaceId: string | null) {
|
||||
const [workspaceDefaults, setWorkspaceDefaults] = useState<StoredDefaults | null | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const writeSeq = useRef(0);
|
||||
useEffect(() => {
|
||||
if (!workspaceId) {
|
||||
setWorkspaceDefaults(undefined);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const seq = writeSeq.current;
|
||||
setWorkspaceDefaults(undefined);
|
||||
fetchGitHubWorkspaceSettings(workspaceId)
|
||||
.then(async (settings) => {
|
||||
if (cancelled || seq !== writeSeq.current) return;
|
||||
const defaults = readServerDefaults(settings.default_query_presets);
|
||||
let local: StoredDefaults | null | undefined = getSnapshot();
|
||||
if (local === null) {
|
||||
local = await readLegacyServerDefaults();
|
||||
}
|
||||
if (cancelled || seq !== writeSeq.current) return;
|
||||
if (
|
||||
(defaults === null || defaults === undefined) &&
|
||||
local !== undefined &&
|
||||
local !== null &&
|
||||
!hasMigratedToWorkspace(workspaceId)
|
||||
) {
|
||||
setWorkspaceDefaults(local);
|
||||
void syncWorkspaceDefaultQueryPresets(workspaceId, local)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
setWorkspaceDefaults(defaults === undefined ? null : defaults);
|
||||
if (!(local === undefined && (defaults === null || defaults === undefined))) {
|
||||
markMigratedToWorkspace(workspaceId);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setWorkspaceDefaults(undefined);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [workspaceId]);
|
||||
const setWorkspaceDefaultsFromLocal = useCallback((next: StoredDefaults | null) => {
|
||||
writeSeq.current += 1;
|
||||
setWorkspaceDefaults(next);
|
||||
}, []);
|
||||
return { workspaceDefaults, setWorkspaceDefaults: setWorkspaceDefaultsFromLocal };
|
||||
}
|
||||
|
||||
export function useDefaultQueryPresets(workspaceId: string | null = null) {
|
||||
const stored = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
const { workspaceDefaults, setWorkspaceDefaults } = useWorkspaceDefaultQueryPresets(workspaceId);
|
||||
useLegacyDefaultQueryPresetSync(!workspaceId);
|
||||
const effectiveStored = workspaceId ? workspaceDefaults : stored;
|
||||
const prPresets = useMemo(
|
||||
() => effectiveStored?.pr ?? toStored(BUILTIN_PR_PRESETS),
|
||||
[effectiveStored],
|
||||
);
|
||||
const issuePresets = useMemo(
|
||||
() => effectiveStored?.issue ?? toStored(BUILTIN_ISSUE_PRESETS),
|
||||
[effectiveStored],
|
||||
);
|
||||
|
||||
const save = useCallback(
|
||||
(defaults: StoredDefaults) => {
|
||||
if (workspaceId && workspaceDefaults === undefined) return;
|
||||
if (workspaceId) {
|
||||
setWorkspaceDefaults(defaults);
|
||||
void syncWorkspaceDefaultQueryPresets(workspaceId, defaults)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
publish(defaults);
|
||||
void syncServer(defaults);
|
||||
markMigratedToBackend();
|
||||
},
|
||||
[workspaceId, workspaceDefaults, setWorkspaceDefaults],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
if (workspaceId && workspaceDefaults === undefined) return;
|
||||
if (workspaceId) {
|
||||
setWorkspaceDefaults(null);
|
||||
void syncWorkspaceDefaultQueryPresets(workspaceId, null)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
publish(null);
|
||||
void syncServer(null);
|
||||
markMigratedToBackend();
|
||||
}, []);
|
||||
}, [workspaceId, workspaceDefaults, setWorkspaceDefaults]);
|
||||
|
||||
const isCustomized = stored !== null;
|
||||
const isCustomized = effectiveStored !== null && effectiveStored !== undefined;
|
||||
|
||||
return { prPresets, issuePresets, save, reset, isCustomized };
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { searchUserPRs, searchUserIssues } from "@/lib/api/domains/github-api";
|
||||
import type { GitHubPR, GitHubIssue } from "@/lib/types/github";
|
||||
import type { PresetOption } from "./search-bar";
|
||||
@@ -22,6 +22,16 @@ type FetchArgs = {
|
||||
customQuery: string;
|
||||
repoFilter: string;
|
||||
page: number;
|
||||
workspaceId: string | null;
|
||||
};
|
||||
|
||||
type UseGitHubSearchOptions = {
|
||||
kind: SearchKind;
|
||||
presets: PresetOption[];
|
||||
preset: string;
|
||||
customQuery: string;
|
||||
repoFilter?: string;
|
||||
workspaceId?: string | null;
|
||||
};
|
||||
|
||||
export function buildParams(
|
||||
@@ -40,13 +50,14 @@ export function buildParams(
|
||||
return { filter };
|
||||
}
|
||||
|
||||
export function useGitHubSearch<T extends GitHubPR | GitHubIssue>(
|
||||
kind: SearchKind,
|
||||
presets: PresetOption[],
|
||||
preset: string,
|
||||
customQuery: string,
|
||||
repoFilter: string = "",
|
||||
) {
|
||||
export function useGitHubSearch<T extends GitHubPR | GitHubIssue>({
|
||||
kind,
|
||||
presets,
|
||||
preset,
|
||||
customQuery,
|
||||
repoFilter = "",
|
||||
workspaceId = null,
|
||||
}: UseGitHubSearchOptions) {
|
||||
const [state, setState] = useState<SearchState<T>>({
|
||||
items: [],
|
||||
loading: false,
|
||||
@@ -59,22 +70,33 @@ export function useGitHubSearch<T extends GitHubPR | GitHubIssue>(
|
||||
// a slow page-N request can't overwrite a fresher page-1 result after a
|
||||
// filter change.
|
||||
const requestSeq = useRef(0);
|
||||
const workspaceRef = useRef(workspaceId);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
workspaceRef.current = workspaceId;
|
||||
}, [workspaceId]);
|
||||
|
||||
// Reset to page 1 whenever the filter inputs change.
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [preset, customQuery, repoFilter, kind]);
|
||||
}, [preset, customQuery, repoFilter, workspaceId, kind]);
|
||||
|
||||
const fetchData = useCallback(
|
||||
async ({ preset: ep, customQuery: ec, repoFilter: er, page: epage }: FetchArgs) => {
|
||||
async ({
|
||||
preset: ep,
|
||||
customQuery: ec,
|
||||
repoFilter: er,
|
||||
page: epage,
|
||||
workspaceId: ews,
|
||||
}: FetchArgs) => {
|
||||
const seq = ++requestSeq.current;
|
||||
setState((s) => ({ ...s, loading: true, error: null }));
|
||||
try {
|
||||
const base = buildParams(presets, ep, ec, er);
|
||||
const params = { ...base, page: epage, perPage: SEARCH_PAGE_SIZE };
|
||||
const params = { ...base, page: epage, perPage: SEARCH_PAGE_SIZE, workspaceId: ews };
|
||||
const response =
|
||||
kind === "pr" ? await searchUserPRs(params) : await searchUserIssues(params);
|
||||
if (seq !== requestSeq.current) return;
|
||||
if (seq !== requestSeq.current || ews !== workspaceRef.current) return;
|
||||
const items = (kind === "pr"
|
||||
? (response as { prs: GitHubPR[] }).prs
|
||||
: (response as { issues: GitHubIssue[] }).issues) as unknown as T[];
|
||||
@@ -86,7 +108,7 @@ export function useGitHubSearch<T extends GitHubPR | GitHubIssue>(
|
||||
total: response.total_count ?? (items ?? []).length,
|
||||
});
|
||||
} catch (err) {
|
||||
if (seq !== requestSeq.current) return;
|
||||
if (seq !== requestSeq.current || ews !== workspaceRef.current) return;
|
||||
setState((s) => ({
|
||||
items: [],
|
||||
loading: false,
|
||||
@@ -100,12 +122,12 @@ export function useGitHubSearch<T extends GitHubPR | GitHubIssue>(
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchData({ preset, customQuery, repoFilter, page });
|
||||
}, [fetchData, preset, customQuery, repoFilter, page]);
|
||||
void fetchData({ preset, customQuery, repoFilter, page, workspaceId });
|
||||
}, [fetchData, preset, customQuery, repoFilter, page, workspaceId]);
|
||||
|
||||
const refresh = useCallback(
|
||||
() => fetchData({ preset, customQuery, repoFilter, page }),
|
||||
[fetchData, preset, customQuery, repoFilter, page],
|
||||
() => fetchData({ preset, customQuery, repoFilter, page, workspaceId }),
|
||||
[fetchData, preset, customQuery, repoFilter, page, workspaceId],
|
||||
);
|
||||
|
||||
return { ...state, page, setPage, pageSize: SEARCH_PAGE_SIZE, refresh };
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { fetchUserSettings, updateUserSettings } from "@/lib/api/domains/settings-api";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
updateGitHubWorkspaceSettings,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import {
|
||||
__resetSnapshotForTests,
|
||||
readStorage,
|
||||
@@ -10,12 +14,19 @@ import {
|
||||
|
||||
const STORAGE_KEY = "kandev:github-presets:v1";
|
||||
const SYNC_FAILED_KEY = "kandev:github-presets:sync-failed:v1";
|
||||
const WORKSPACE_ID = "ws-1";
|
||||
const SETTINGS_TIMESTAMP = "2026-01-01T00:00:00Z";
|
||||
|
||||
vi.mock("@/lib/api/domains/settings-api", () => ({
|
||||
fetchUserSettings: vi.fn(),
|
||||
updateUserSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/github-api", () => ({
|
||||
fetchGitHubWorkspaceSettings: vi.fn(),
|
||||
updateGitHubWorkspaceSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
// Provide a simple in-memory localStorage mock so the tests are not sensitive
|
||||
// to how the test runner exposes window.localStorage (e.g. Node's
|
||||
// --localstorage-file flag without a valid path).
|
||||
@@ -35,6 +46,7 @@ function makeLocalStorageMock() {
|
||||
|
||||
const localStorageMock = makeLocalStorageMock();
|
||||
vi.stubGlobal("localStorage", localStorageMock);
|
||||
Object.defineProperty(window, "localStorage", { value: localStorageMock, configurable: true });
|
||||
|
||||
function set(raw: string | null) {
|
||||
if (raw === null) localStorageMock.removeItem(STORAGE_KEY);
|
||||
@@ -47,15 +59,36 @@ const valid: SavedPreset = {
|
||||
label: "My PRs",
|
||||
customQuery: "author:@me",
|
||||
repoFilter: "",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
createdAt: SETTINGS_TIMESTAMP,
|
||||
};
|
||||
|
||||
function resetTestState() {
|
||||
localStorageMock.clear();
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchUserSettings).mockReset();
|
||||
vi.mocked(updateUserSettings).mockReset();
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockReset();
|
||||
vi.mocked(updateGitHubWorkspaceSettings).mockReset();
|
||||
}
|
||||
|
||||
function workspaceSettings(
|
||||
savedPresets: SavedPreset[] = [],
|
||||
): Awaited<ReturnType<typeof fetchGitHubWorkspaceSettings>> {
|
||||
return {
|
||||
workspace_id: WORKSPACE_ID,
|
||||
repo_scope_mode: "all",
|
||||
repo_scope_orgs: [],
|
||||
repo_scope_repos: [],
|
||||
saved_presets: savedPresets,
|
||||
default_query_presets: null,
|
||||
created_at: SETTINGS_TIMESTAMP,
|
||||
updated_at: SETTINGS_TIMESTAMP,
|
||||
} as Awaited<ReturnType<typeof fetchGitHubWorkspaceSettings>>;
|
||||
}
|
||||
|
||||
describe("readStorage", () => {
|
||||
beforeEach(() => {
|
||||
localStorageMock.clear();
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchUserSettings).mockReset();
|
||||
vi.mocked(updateUserSettings).mockReset();
|
||||
resetTestState();
|
||||
});
|
||||
|
||||
it("returns empty array when no value is stored", () => {
|
||||
@@ -108,10 +141,7 @@ describe("readStorage", () => {
|
||||
|
||||
describe("useSavedPresets", () => {
|
||||
beforeEach(() => {
|
||||
localStorageMock.clear();
|
||||
__resetSnapshotForTests();
|
||||
vi.mocked(fetchUserSettings).mockReset();
|
||||
vi.mocked(updateUserSettings).mockReset();
|
||||
resetTestState();
|
||||
});
|
||||
|
||||
it("retries local presets after a failed backend sync and clears the marker", async () => {
|
||||
@@ -150,3 +180,102 @@ describe("useSavedPresets", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("useSavedPresets workspace sync", () => {
|
||||
beforeEach(() => {
|
||||
resetTestState();
|
||||
});
|
||||
|
||||
it("migrates local presets into a fresh workspace", async () => {
|
||||
set(JSON.stringify([valid]));
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockResolvedValue(workspaceSettings());
|
||||
vi.mocked(updateGitHubWorkspaceSettings).mockResolvedValue(
|
||||
{} as Awaited<ReturnType<typeof updateGitHubWorkspaceSettings>>,
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(result.current.presets).toEqual([valid]));
|
||||
expect(updateGitHubWorkspaceSettings).toHaveBeenCalledWith({
|
||||
workspace_id: WORKSPACE_ID,
|
||||
saved_presets: [valid],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not migrate local presets over existing workspace presets", async () => {
|
||||
const server = { ...valid, id: "p_server", label: "Server" };
|
||||
set(JSON.stringify([valid]));
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockResolvedValue(workspaceSettings([server]));
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(result.current.presets).toEqual([server]));
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not save while workspace presets are still loading", () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockReturnValue(new Promise(() => {}));
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
let created: SavedPreset | null = null;
|
||||
act(() => {
|
||||
created = result.current.save({
|
||||
kind: "pr",
|
||||
label: "Loading",
|
||||
customQuery: "is:open",
|
||||
repoFilter: "",
|
||||
});
|
||||
});
|
||||
|
||||
expect(created).toBeNull();
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not save after workspace presets fail to load", async () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockRejectedValue(new Error("settings down"));
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(fetchGitHubWorkspaceSettings).toHaveBeenCalled());
|
||||
|
||||
let created: SavedPreset | null = valid;
|
||||
act(() => {
|
||||
created = result.current.save({
|
||||
kind: "pr",
|
||||
label: "Failed load",
|
||||
customQuery: "is:open",
|
||||
repoFilter: "",
|
||||
});
|
||||
});
|
||||
|
||||
expect(created).toBeNull();
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not remove while workspace presets are still loading", () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockReturnValue(new Promise(() => {}));
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
act(() => {
|
||||
result.current.remove("p_1");
|
||||
});
|
||||
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not remove after workspace presets fail to load", async () => {
|
||||
vi.mocked(fetchGitHubWorkspaceSettings).mockRejectedValue(new Error("settings down"));
|
||||
|
||||
const { result } = renderHook(() => useSavedPresets(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(fetchGitHubWorkspaceSettings).toHaveBeenCalled());
|
||||
|
||||
act(() => {
|
||||
result.current.remove("p_1");
|
||||
});
|
||||
|
||||
expect(updateGitHubWorkspaceSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { fetchUserSettings } from "@/lib/api/domains/settings-api";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
updateGitHubWorkspaceSettings,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import { createQueuedUserSettingsSync } from "@/lib/user-settings-sync";
|
||||
import { hasUserSettingsSyncFailure } from "@/lib/user-settings-sync-failure";
|
||||
|
||||
const STORAGE_KEY = "kandev:github-presets:v1";
|
||||
const MIGRATED_KEY = "kandev:github-presets:migrated-to-backend:v1";
|
||||
const WORKSPACE_MIGRATED_KEY_PREFIX = "kandev:github-presets:migrated-to-workspace:v1:";
|
||||
const SYNC_FAILED_KEY = "kandev:github-presets:sync-failed:v1";
|
||||
|
||||
export type SavedPreset = {
|
||||
@@ -86,10 +91,33 @@ function readServerPresets(value: unknown): SavedPreset[] | null {
|
||||
);
|
||||
}
|
||||
|
||||
async function readLegacyServerPresets(): Promise<SavedPreset[] | undefined> {
|
||||
try {
|
||||
const response = await fetchUserSettings({ cache: "no-store" });
|
||||
return readServerPresets(response.settings.github_saved_presets) ?? [];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const syncServer = createQueuedUserSettingsSync<SavedPreset[]>(SYNC_FAILED_KEY, (next) => ({
|
||||
github_saved_presets: next,
|
||||
}));
|
||||
|
||||
let workspaceSyncQueue = Promise.resolve();
|
||||
|
||||
function syncWorkspaceSavedPresets(workspaceId: string, next: SavedPreset[]): Promise<void> {
|
||||
workspaceSyncQueue = workspaceSyncQueue
|
||||
.catch(() => undefined)
|
||||
.then(() =>
|
||||
updateGitHubWorkspaceSettings({
|
||||
workspace_id: workspaceId,
|
||||
saved_presets: next,
|
||||
}).then(() => undefined),
|
||||
);
|
||||
return workspaceSyncQueue;
|
||||
}
|
||||
|
||||
function snapshotKey(value: SavedPreset[]): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
@@ -108,15 +136,28 @@ function markMigratedToBackend(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function hasMigratedToWorkspace(workspaceId: string): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
return window.localStorage.getItem(WORKSPACE_MIGRATED_KEY_PREFIX + workspaceId) === "1";
|
||||
}
|
||||
|
||||
function markMigratedToWorkspace(workspaceId: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(WORKSPACE_MIGRATED_KEY_PREFIX + workspaceId, "1");
|
||||
} catch {
|
||||
/* ignore storage failures */
|
||||
}
|
||||
}
|
||||
|
||||
export function __resetSnapshotForTests() {
|
||||
snapshot = null;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
export function useSavedPresets() {
|
||||
const presets = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
|
||||
function useLegacySavedPresetsSync(enabled: boolean) {
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let cancelled = false;
|
||||
const initialKey = snapshotKey(readStorage());
|
||||
fetchUserSettings({ cache: "no-store" })
|
||||
@@ -141,27 +182,107 @@ export function useSavedPresets() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const save = useCallback((input: Omit<SavedPreset, "id" | "createdAt">) => {
|
||||
const preset: SavedPreset = {
|
||||
...input,
|
||||
id: `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
const next = [...readStorage(), preset];
|
||||
publish(next);
|
||||
void syncServer(next);
|
||||
markMigratedToBackend();
|
||||
return preset;
|
||||
}, []);
|
||||
|
||||
const remove = useCallback((id: string) => {
|
||||
const next = readStorage().filter((p) => p.id !== id);
|
||||
publish(next);
|
||||
void syncServer(next);
|
||||
markMigratedToBackend();
|
||||
}, []);
|
||||
|
||||
return { presets, save, remove };
|
||||
}, [enabled]);
|
||||
}
|
||||
|
||||
function useWorkspaceSavedPresets(workspaceId: string | null) {
|
||||
const [workspacePresets, setWorkspacePresets] = useState<SavedPreset[] | undefined>(undefined);
|
||||
const writeSeq = useRef(0);
|
||||
useEffect(() => {
|
||||
if (!workspaceId) {
|
||||
setWorkspacePresets(undefined);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const seq = writeSeq.current;
|
||||
setWorkspacePresets(undefined);
|
||||
fetchGitHubWorkspaceSettings(workspaceId)
|
||||
.then(async (settings) => {
|
||||
if (cancelled || seq !== writeSeq.current) return;
|
||||
const serverPresets = readServerPresets(settings.saved_presets) ?? [];
|
||||
let local: SavedPreset[] | undefined = readStorage();
|
||||
if (local.length === 0) {
|
||||
local = await readLegacyServerPresets();
|
||||
}
|
||||
if (cancelled || seq !== writeSeq.current) return;
|
||||
if (
|
||||
serverPresets.length === 0 &&
|
||||
local !== undefined &&
|
||||
local.length > 0 &&
|
||||
!hasMigratedToWorkspace(workspaceId)
|
||||
) {
|
||||
setWorkspacePresets(local);
|
||||
void syncWorkspaceSavedPresets(workspaceId, local)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
setWorkspacePresets(serverPresets);
|
||||
if (local !== undefined || serverPresets.length > 0) {
|
||||
markMigratedToWorkspace(workspaceId);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setWorkspacePresets(undefined);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [workspaceId]);
|
||||
const setWorkspacePresetsFromLocal = useCallback((next: SavedPreset[]) => {
|
||||
writeSeq.current += 1;
|
||||
setWorkspacePresets(next);
|
||||
}, []);
|
||||
return { workspacePresets, setWorkspacePresets: setWorkspacePresetsFromLocal };
|
||||
}
|
||||
|
||||
export function useSavedPresets(workspaceId: string | null = null) {
|
||||
const presets = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
const { workspacePresets, setWorkspacePresets } = useWorkspaceSavedPresets(workspaceId);
|
||||
useLegacySavedPresetsSync(!workspaceId);
|
||||
const activePresets = workspaceId ? (workspacePresets ?? []) : presets;
|
||||
|
||||
const save = useCallback(
|
||||
(input: Omit<SavedPreset, "id" | "createdAt">) => {
|
||||
if (workspaceId && workspacePresets === undefined) return null;
|
||||
const preset: SavedPreset = {
|
||||
...input,
|
||||
id: `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
const next = [...activePresets, preset];
|
||||
if (workspaceId) {
|
||||
setWorkspacePresets(next);
|
||||
void syncWorkspaceSavedPresets(workspaceId, next)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return preset;
|
||||
}
|
||||
publish(next);
|
||||
void syncServer(next);
|
||||
markMigratedToBackend();
|
||||
return preset;
|
||||
},
|
||||
[activePresets, workspaceId, workspacePresets, setWorkspacePresets],
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
(id: string) => {
|
||||
if (workspaceId && workspacePresets === undefined) return;
|
||||
const next = activePresets.filter((p) => p.id !== id);
|
||||
if (workspaceId) {
|
||||
setWorkspacePresets(next);
|
||||
void syncWorkspaceSavedPresets(workspaceId, next)
|
||||
.then(() => markMigratedToWorkspace(workspaceId))
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
publish(next);
|
||||
void syncServer(next);
|
||||
markMigratedToBackend();
|
||||
},
|
||||
[activePresets, workspaceId, workspacePresets, setWorkspacePresets],
|
||||
);
|
||||
|
||||
return { presets: activePresets, save, remove };
|
||||
}
|
||||
|
||||
@@ -16,14 +16,24 @@ import { Label } from "@kandev/ui/label";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
|
||||
import { Switch } from "@kandev/ui/switch";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { listUserOrgs, searchOrgRepos } from "@/lib/api/domains/github-api";
|
||||
import type { RepoFilter, GitHubOrg, GitHubRepoInfo } from "@/lib/types/github";
|
||||
import {
|
||||
fetchGitHubWorkspaceSettings,
|
||||
listUserOrgs,
|
||||
searchOrgRepos,
|
||||
} from "@/lib/api/domains/github-api";
|
||||
import type {
|
||||
RepoFilter,
|
||||
GitHubOrg,
|
||||
GitHubRepoInfo,
|
||||
GitHubWorkspaceSettings,
|
||||
} from "@/lib/types/github";
|
||||
|
||||
type RepoFilterSelectorProps = {
|
||||
allRepos: boolean;
|
||||
selectedRepos: RepoFilter[];
|
||||
onAllReposChange: (checked: boolean) => void;
|
||||
onSelectedReposChange: (repos: RepoFilter[]) => void;
|
||||
workspaceId?: string;
|
||||
};
|
||||
|
||||
function useGitHubOrgs() {
|
||||
@@ -70,6 +80,58 @@ function useRepoSearch(org: string, query: string) {
|
||||
return { results, loading };
|
||||
}
|
||||
|
||||
function useWorkspaceRepoScope(workspaceId: string | undefined) {
|
||||
const [settings, setSettings] = useState<GitHubWorkspaceSettings | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceId) {
|
||||
setSettings(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void fetchGitHubWorkspaceSettings(workspaceId)
|
||||
.then((next) => {
|
||||
if (!cancelled) setSettings(next);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSettings(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [workspaceId]);
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
function repoAllowedByScope(settings: GitHubWorkspaceSettings | null, owner: string, repo: string) {
|
||||
if (!settings || settings.repo_scope_mode === "all") return true;
|
||||
const ownerLower = owner.trim().toLowerCase();
|
||||
const repoLower = repo.trim().toLowerCase();
|
||||
if (settings.repo_scope_mode === "orgs") {
|
||||
return (settings.repo_scope_orgs ?? []).some((allowed) => {
|
||||
return allowed.trim().toLowerCase() === ownerLower;
|
||||
});
|
||||
}
|
||||
return (settings.repo_scope_repos ?? []).some((allowed) => {
|
||||
return (
|
||||
allowed.owner.trim().toLowerCase() === ownerLower &&
|
||||
allowed.name.trim().toLowerCase() === repoLower
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function orgAllowedByScope(settings: GitHubWorkspaceSettings | null, org: string) {
|
||||
if (!settings || settings.repo_scope_mode === "all") return true;
|
||||
const orgLower = org.trim().toLowerCase();
|
||||
if (settings.repo_scope_mode === "orgs") {
|
||||
return (settings.repo_scope_orgs ?? []).some((allowed) => {
|
||||
return allowed.trim().toLowerCase() === orgLower;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function SelectedFilters({
|
||||
repos,
|
||||
onRemove,
|
||||
@@ -153,9 +215,11 @@ function OrgBadges({
|
||||
|
||||
function RepoSearchCombobox({
|
||||
disabled,
|
||||
scope,
|
||||
onAdd,
|
||||
}: {
|
||||
disabled: boolean;
|
||||
scope: GitHubWorkspaceSettings | null;
|
||||
onAdd: (owner: string, name: string) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -165,7 +229,10 @@ function RepoSearchCombobox({
|
||||
const org = slashIdx > 0 ? value.slice(0, slashIdx) : "";
|
||||
const query = slashIdx > 0 ? value.slice(slashIdx + 1) : "";
|
||||
const { results, loading: searchLoading } = useRepoSearch(org, query);
|
||||
const filteredResults = useMemo(() => results.slice(0, 10), [results]);
|
||||
const filteredResults = useMemo(
|
||||
() => results.filter((repo) => repoAllowedByScope(scope, repo.owner, repo.name)).slice(0, 10),
|
||||
[results, scope],
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(fullName: string) => {
|
||||
@@ -239,8 +306,15 @@ export function RepoFilterSelector({
|
||||
selectedRepos,
|
||||
onAllReposChange,
|
||||
onSelectedReposChange,
|
||||
workspaceId,
|
||||
}: RepoFilterSelectorProps) {
|
||||
const { orgs, loading: orgsLoading } = useGitHubOrgs();
|
||||
const scope = useWorkspaceRepoScope(workspaceId);
|
||||
const scopedOrgs = useMemo(
|
||||
() => orgs.filter((org) => orgAllowedByScope(scope, org.login)),
|
||||
[orgs, scope],
|
||||
);
|
||||
const showOrgBadges = !scope || scope.repo_scope_mode !== "repos";
|
||||
|
||||
const toggleOrg = useCallback(
|
||||
(login: string) => {
|
||||
@@ -278,7 +352,7 @@ export function RepoFilterSelector({
|
||||
<div>
|
||||
<Label>Repositories</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Which GitHub repositories to monitor for PRs requesting your review.
|
||||
Which allowed GitHub repositories to monitor for this watch.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -290,24 +364,26 @@ export function RepoFilterSelector({
|
||||
className="cursor-pointer"
|
||||
/>
|
||||
<Label htmlFor="all-repos-toggle" className="font-normal cursor-pointer">
|
||||
All repositories (no filtering)
|
||||
All repositories allowed by this workspace
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{!allRepos && (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground font-normal">Organizations</Label>
|
||||
<OrgBadges
|
||||
orgs={orgs}
|
||||
loading={orgsLoading}
|
||||
selectedRepos={selectedRepos}
|
||||
disabled={allRepos}
|
||||
onToggleOrg={toggleOrg}
|
||||
/>
|
||||
</div>
|
||||
{showOrgBadges && (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground font-normal">Organizations</Label>
|
||||
<OrgBadges
|
||||
orgs={scopedOrgs}
|
||||
loading={orgsLoading}
|
||||
selectedRepos={selectedRepos}
|
||||
disabled={allRepos}
|
||||
onToggleOrg={toggleOrg}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RepoSearchCombobox disabled={allRepos} onAdd={addRepo} />
|
||||
<RepoSearchCombobox disabled={allRepos} scope={scope} onAdd={addRepo} />
|
||||
|
||||
<SelectedFilters repos={selectedRepos} onRemove={removeFilter} disabled={allRepos} />
|
||||
</>
|
||||
|
||||
@@ -349,6 +349,7 @@ function WatchFormFields({
|
||||
selectedRepos={form.selectedRepos}
|
||||
onAllReposChange={onAllReposChange}
|
||||
onSelectedReposChange={onSelectedReposChange}
|
||||
workspaceId={form.workspaceId}
|
||||
/>
|
||||
<QueryField form={form} setForm={setForm} />
|
||||
<SectionHeader>Automation</SectionHeader>
|
||||
|
||||
Reference in New Issue
Block a user