更新一下前端风格样式
This commit is contained in:
@@ -4,6 +4,10 @@
|
|||||||
|
|
||||||
Star Manager 是一个本地优先(local-first)的 Web 应用,用于整理你的 GitHub Star 仓库与 Star Lists,并支持可选的 LLM 辅助分类。
|
Star Manager 是一个本地优先(local-first)的 Web 应用,用于整理你的 GitHub Star 仓库与 Star Lists,并支持可选的 LLM 辅助分类。
|
||||||
|
|
||||||
|
如果您想在不进行本地设置的情况下体验该应用,可以使用[在线部署](https://github-star-manager.blackzero.edu.kg)。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 为什么使用 Star Manager
|
## 为什么使用 Star Manager
|
||||||
|
|
||||||
当 Star 仓库数量变多后,手工维护列表效率低且容易不一致。Star Manager 可以帮助你:
|
当 Star 仓库数量变多后,手工维护列表效率低且容易不一致。Star Manager 可以帮助你:
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="color-scheme" content="light" />
|
<meta name="color-scheme" content="light" />
|
||||||
<meta name="description" content="Manage GitHub starred repositories with Star Lists and smart classification." />
|
<meta name="description" content="Manage GitHub starred repositories with Star Lists." />
|
||||||
<title>Star Manager</title>
|
<title>GitHub星标管理面板</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
1962
package-lock.json
generated
Normal file
1962
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
330
src/app/App.tsx
330
src/app/App.tsx
@@ -6,10 +6,9 @@ import { db } from "./data/db";
|
|||||||
import { useLiveQuery } from "./data/useLiveQuery";
|
import { useLiveQuery } from "./data/useLiveQuery";
|
||||||
import { validatePat } from "./services/githubAuth";
|
import { validatePat } from "./services/githubAuth";
|
||||||
import { usePreferenceStore } from "./store/preferences";
|
import { usePreferenceStore } from "./store/preferences";
|
||||||
import { ApplyUpdatesModal } from "./ui/ApplyUpdatesModal";
|
|
||||||
import { AssignListModal } from "./ui/AssignListModal";
|
import { AssignListModal } from "./ui/AssignListModal";
|
||||||
import { FirstRunPrompt } from "./ui/FirstRunPrompt";
|
import { FirstRunPrompt } from "./ui/FirstRunPrompt";
|
||||||
import { LlmClassificationModal } from "./ui/LlmClassificationModal";
|
import { ManageListsModal } from "./ui/ManageListsModal";
|
||||||
import { PatModal } from "./ui/PatModal";
|
import { PatModal } from "./ui/PatModal";
|
||||||
import { SettingsModal } from "./ui/SettingsModal";
|
import { SettingsModal } from "./ui/SettingsModal";
|
||||||
|
|
||||||
@@ -23,16 +22,10 @@ type RepoPreview = {
|
|||||||
updatedAt?: string;
|
updatedAt?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type SyncStatusCode = "idle" | "running" | "completed" | "failed" | "ready" | "retrying";
|
|
||||||
|
|
||||||
type SyncMessage = {
|
|
||||||
key: string;
|
|
||||||
values?: Record<string, number | string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const previewRepos: RepoPreview[] = [];
|
const previewRepos: RepoPreview[] = [];
|
||||||
const previewLists: { id: string; name: string; count: number }[] = [
|
const previewLists: { id: string; name: string; count: number }[] = [
|
||||||
{ id: "all", name: "", count: 0 },
|
{ id: "all", name: "", count: 0 },
|
||||||
|
{ id: "unclassified", name: "", count: 0 },
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
@@ -42,19 +35,10 @@ export default function App() {
|
|||||||
const [activeList, setActiveList] = useState("all");
|
const [activeList, setActiveList] = useState("all");
|
||||||
const [isPatModalOpen, setIsPatModalOpen] = useState(false);
|
const [isPatModalOpen, setIsPatModalOpen] = useState(false);
|
||||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||||
const [isClassificationOpen, setIsClassificationOpen] = useState(false);
|
const [isManageListsOpen, setIsManageListsOpen] = useState(false);
|
||||||
const [isApplyUpdatesOpen, setIsApplyUpdatesOpen] = useState(false);
|
|
||||||
const [assignRepo, setAssignRepo] = useState<{ id: string; name: string } | null>(null);
|
const [assignRepo, setAssignRepo] = useState<{ id: string; name: string } | null>(null);
|
||||||
const [syncStatus, setSyncStatus] = useState<SyncStatusCode>("idle");
|
|
||||||
const [syncMessage, setSyncMessage] = useState<SyncMessage>({
|
|
||||||
key: "app.sync.detail.connectPat",
|
|
||||||
});
|
|
||||||
const [syncError, setSyncError] = useState("");
|
|
||||||
const [syncStage, setSyncStage] = useState("idle");
|
|
||||||
const [syncCurrent, setSyncCurrent] = useState(0);
|
|
||||||
const [syncTotal, setSyncTotal] = useState(0);
|
|
||||||
const [syncFailed, setSyncFailed] = useState(0);
|
|
||||||
const [failedListIds, setFailedListIds] = useState<string[]>([]);
|
const [failedListIds, setFailedListIds] = useState<string[]>([]);
|
||||||
|
const [listSidebarOpen, setListSidebarOpen] = useState(false);
|
||||||
const [languageFilter, setLanguageFilter] = useState("all");
|
const [languageFilter, setLanguageFilter] = useState("all");
|
||||||
const [showUnlisted, setShowUnlisted] = useState(false);
|
const [showUnlisted, setShowUnlisted] = useState(false);
|
||||||
const [recentOnly, setRecentOnly] = useState(false);
|
const [recentOnly, setRecentOnly] = useState(false);
|
||||||
@@ -85,6 +69,7 @@ export default function App() {
|
|||||||
async () => {
|
async () => {
|
||||||
const listRows = await db.lists.toArray();
|
const listRows = await db.lists.toArray();
|
||||||
const repoListRows = await db.repoLists.toArray();
|
const repoListRows = await db.repoLists.toArray();
|
||||||
|
const repoListMap = new Map(repoListRows.map((row) => [row.repoId, row.listIds]));
|
||||||
const countMap = new Map<string, number>();
|
const countMap = new Map<string, number>();
|
||||||
for (const row of repoListRows) {
|
for (const row of repoListRows) {
|
||||||
for (const listId of row.listIds) {
|
for (const listId of row.listIds) {
|
||||||
@@ -97,8 +82,18 @@ export default function App() {
|
|||||||
name: list.name,
|
name: list.name,
|
||||||
count: countMap.get(list.id) ?? 0,
|
count: countMap.get(list.id) ?? 0,
|
||||||
}));
|
}));
|
||||||
const total = await db.repos.count();
|
const repoRows = await db.repos.toArray();
|
||||||
return [{ id: "all", name: "", count: total }, ...listCounts];
|
let unclassifiedCount = 0;
|
||||||
|
for (const repo of repoRows) {
|
||||||
|
const ids = repoListMap.get(repo.id);
|
||||||
|
if (!ids || ids.length === 0) unclassifiedCount += 1;
|
||||||
|
}
|
||||||
|
const total = repoRows.length;
|
||||||
|
return [
|
||||||
|
{ id: "all", name: "", count: total },
|
||||||
|
{ id: "unclassified", name: "", count: unclassifiedCount },
|
||||||
|
...listCounts,
|
||||||
|
];
|
||||||
},
|
},
|
||||||
[],
|
[],
|
||||||
previewLists
|
previewLists
|
||||||
@@ -141,11 +136,20 @@ export default function App() {
|
|||||||
|
|
||||||
const visibleRepos = useMemo(() => {
|
const visibleRepos = useMemo(() => {
|
||||||
if (activeList === "all") return repos;
|
if (activeList === "all") return repos;
|
||||||
|
if (activeList === "unclassified") return repos.filter((repo) => repo.tags.length === 0);
|
||||||
const listName = lists.find((list) => list.id === activeList)?.name;
|
const listName = lists.find((list) => list.id === activeList)?.name;
|
||||||
if (!listName) return [];
|
if (!listName) return [];
|
||||||
return repos.filter((repo) => repo.tags.includes(listName));
|
return repos.filter((repo) => repo.tags.includes(listName));
|
||||||
}, [activeList, repos, lists]);
|
}, [activeList, repos, lists]);
|
||||||
|
|
||||||
|
const activeListLabel = useMemo(() => {
|
||||||
|
const item = lists.find((l) => l.id === activeList);
|
||||||
|
if (!item) return "";
|
||||||
|
if (item.id === "all") return t("common.values.allStarred");
|
||||||
|
if (item.id === "unclassified") return t("common.values.unclassified");
|
||||||
|
return item.name;
|
||||||
|
}, [lists, activeList, t]);
|
||||||
|
|
||||||
const filteredRepos = useMemo(() => {
|
const filteredRepos = useMemo(() => {
|
||||||
const query = searchQuery.trim().toLowerCase();
|
const query = searchQuery.trim().toLowerCase();
|
||||||
const threshold = Date.now() - 1000 * 60 * 60 * 24 * 180;
|
const threshold = Date.now() - 1000 * 60 * 60 * 24 * 180;
|
||||||
@@ -164,32 +168,42 @@ export default function App() {
|
|||||||
});
|
});
|
||||||
}, [visibleRepos, languageFilter, showUnlisted, recentOnly, searchQuery]);
|
}, [visibleRepos, languageFilter, showUnlisted, recentOnly, searchQuery]);
|
||||||
|
|
||||||
const lastSyncText = useMemo(() => {
|
|
||||||
if (!preferences.lastSyncedAt) return "";
|
|
||||||
const parsed = Date.parse(preferences.lastSyncedAt);
|
|
||||||
if (Number.isNaN(parsed)) return preferences.lastSyncedAt;
|
|
||||||
return new Date(parsed).toLocaleString(i18n.language);
|
|
||||||
}, [preferences.lastSyncedAt, i18n.language]);
|
|
||||||
|
|
||||||
const syncDetail = useMemo(() => {
|
|
||||||
if (syncError) return syncError;
|
|
||||||
if (syncStatus === "running" || syncStatus === "retrying") {
|
|
||||||
const stageText = t(`progress.sync.${syncStage}`, { defaultValue: syncStage });
|
|
||||||
return t("app.sync.detail.progress", {
|
|
||||||
stage: stageText,
|
|
||||||
current: syncCurrent,
|
|
||||||
total: syncTotal,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return t(syncMessage.key, syncMessage.values);
|
|
||||||
}, [syncError, syncStatus, syncStage, syncCurrent, syncTotal, syncMessage, t]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeList === "all") return;
|
if (activeList === "all") return;
|
||||||
const exists = lists.some((list) => list.id === activeList);
|
const exists = lists.some((list) => list.id === activeList);
|
||||||
if (!exists) setActiveList("all");
|
if (!exists) setActiveList("all");
|
||||||
}, [activeList, lists]);
|
}, [activeList, lists]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!listSidebarOpen) return;
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") setListSidebarOpen(false);
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [listSidebarOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!listSidebarOpen) return;
|
||||||
|
const mq = window.matchMedia("(max-width: 1100px)");
|
||||||
|
if (!mq.matches) return;
|
||||||
|
const prev = document.body.style.overflow;
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
document.body.style.overflow = prev;
|
||||||
|
};
|
||||||
|
}, [listSidebarOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const mq = window.matchMedia("(min-width: 1101px)");
|
||||||
|
const close = () => {
|
||||||
|
if (mq.matches) setListSidebarOpen(false);
|
||||||
|
};
|
||||||
|
mq.addEventListener("change", close);
|
||||||
|
close();
|
||||||
|
return () => mq.removeEventListener("change", close);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app">
|
<div className="app">
|
||||||
<header className="app-header">
|
<header className="app-header">
|
||||||
@@ -216,69 +230,108 @@ export default function App() {
|
|||||||
setIsPatModalOpen(true);
|
setIsPatModalOpen(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSyncStatus("running");
|
|
||||||
setSyncError("");
|
|
||||||
setSyncMessage({ key: "app.sync.detail.preparing" });
|
|
||||||
setSyncStage("idle");
|
|
||||||
setSyncCurrent(0);
|
|
||||||
setSyncTotal(0);
|
|
||||||
setSyncFailed(0);
|
|
||||||
try {
|
try {
|
||||||
const result = await syncFromGitHub({ token: preferences.patToken }, (progress) => {
|
const result = await syncFromGitHub({ token: preferences.patToken });
|
||||||
setSyncStage(progress.stage);
|
|
||||||
setSyncCurrent(progress.current);
|
|
||||||
setSyncTotal(progress.total);
|
|
||||||
setSyncFailed(progress.failed);
|
|
||||||
});
|
|
||||||
setSyncStatus("completed");
|
|
||||||
setSyncMessage({
|
|
||||||
key: "app.sync.detail.loaded",
|
|
||||||
values: { repos: result.repos, lists: result.lists },
|
|
||||||
});
|
|
||||||
setFailedListIds(result.failedListIds);
|
setFailedListIds(result.failedListIds);
|
||||||
setLastSyncedAt(new Date().toISOString());
|
setLastSyncedAt(new Date().toISOString());
|
||||||
if (result.failedListIds.length === 0) {
|
|
||||||
setSyncFailed(0);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setSyncStatus("failed");
|
window.alert((error as Error).message || t("app.sync.detail.syncFailed"));
|
||||||
setSyncError((error as Error).message || t("app.sync.detail.syncFailed"));
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{t("app.actions.syncStarLists")}
|
{t("app.actions.syncStarLists")}
|
||||||
</button>
|
</button>
|
||||||
|
{failedListIds.length > 0 ? (
|
||||||
|
<button
|
||||||
|
className="button"
|
||||||
|
onClick={async () => {
|
||||||
|
if (!preferences.patToken) return;
|
||||||
|
try {
|
||||||
|
const result = await retryListMembership(
|
||||||
|
{ token: preferences.patToken },
|
||||||
|
failedListIds
|
||||||
|
);
|
||||||
|
setFailedListIds(result.failedListIds);
|
||||||
|
} catch (error) {
|
||||||
|
window.alert((error as Error).message || t("app.sync.detail.retryFailed"));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("app.actions.retryFailedLists", { count: failedListIds.length })}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="app-main">
|
<main className="app-main">
|
||||||
<section className="panel">
|
{listSidebarOpen ? (
|
||||||
<h2>{t("app.sections.starLists")}</h2>
|
<div
|
||||||
{lists.length === 1 && lists[0].id === "all" ? (
|
className="list-sidebar-backdrop"
|
||||||
<div className="empty-state">
|
aria-hidden
|
||||||
<p>{t("app.empty.noListsTitle")}</p>
|
onClick={() => setListSidebarOpen(false)}
|
||||||
<p>{t("app.empty.noListsHint")}</p>
|
/>
|
||||||
|
) : null}
|
||||||
|
<section className={`panel panel--star-lists ${listSidebarOpen ? "is-open" : ""}`}>
|
||||||
|
<div className="panel-heading panel-heading--list-sidebar">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="list-sidebar-close-btn"
|
||||||
|
onClick={() => setListSidebarOpen(false)}
|
||||||
|
aria-label={t("app.nav.closeListSidebar")}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
<h2>{t("app.sections.starLists")}</h2>
|
||||||
|
<button type="button" className="button" onClick={() => setIsManageListsOpen(true)}>
|
||||||
|
{t("app.actions.manageLists")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{lists.filter((l) => l.id !== "all" && l.id !== "unclassified").length === 0 ? (
|
||||||
|
<p className="helper-text list-panel-hint">{t("app.empty.noListsHint")}</p>
|
||||||
|
) : null}
|
||||||
|
{lists.map((list) => (
|
||||||
|
<div
|
||||||
|
key={list.id}
|
||||||
|
className={`list-item ${activeList === list.id ? "active" : ""}`}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={() => {
|
||||||
|
setActiveList(list.id);
|
||||||
|
setListSidebarOpen(false);
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") {
|
||||||
|
setActiveList(list.id);
|
||||||
|
setListSidebarOpen(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
{list.id === "all"
|
||||||
|
? t("common.values.allStarred")
|
||||||
|
: list.id === "unclassified"
|
||||||
|
? t("common.values.unclassified")
|
||||||
|
: list.name}
|
||||||
|
</span>
|
||||||
|
<span>{list.count}</span>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
))}
|
||||||
lists.map((list) => (
|
|
||||||
<div
|
|
||||||
key={list.id}
|
|
||||||
className={`list-item ${activeList === list.id ? "active" : ""}`}
|
|
||||||
role="button"
|
|
||||||
tabIndex={0}
|
|
||||||
onClick={() => setActiveList(list.id)}
|
|
||||||
onKeyDown={(event) => {
|
|
||||||
if (event.key === "Enter") setActiveList(list.id);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span>{list.id === "all" ? t("common.values.allStarred") : list.name}</span>
|
|
||||||
<span>{list.count}</span>
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="panel">
|
<section className="panel panel--repos">
|
||||||
|
<div className="repo-panel-toolbar">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button list-sidebar-open-btn"
|
||||||
|
onClick={() => setListSidebarOpen(true)}
|
||||||
|
>
|
||||||
|
<span className="list-sidebar-open-icon" aria-hidden>
|
||||||
|
☰
|
||||||
|
</span>
|
||||||
|
<span className="list-sidebar-open-text">{t("app.nav.openStarLists")}</span>
|
||||||
|
<span className="list-sidebar-active-chip">{activeListLabel}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<h2>{t("app.sections.repositories")}</h2>
|
<h2>{t("app.sections.repositories")}</h2>
|
||||||
{repos.length === 0 ? (
|
{repos.length === 0 ? (
|
||||||
<div className="empty-state">
|
<div className="empty-state">
|
||||||
@@ -340,7 +393,7 @@ export default function App() {
|
|||||||
<article key={repo.id} className="repo-card">
|
<article key={repo.id} className="repo-card">
|
||||||
<h3 className="repo-title">{repo.name}</h3>
|
<h3 className="repo-title">{repo.name}</h3>
|
||||||
<p className="repo-desc">{repo.description || t("app.values.noDescription")}</p>
|
<p className="repo-desc">{repo.description || t("app.values.noDescription")}</p>
|
||||||
<div>
|
<div className="repo-tags">
|
||||||
{repo.tags.map((tag) => (
|
{repo.tags.map((tag) => (
|
||||||
<span className="tag" key={tag}>
|
<span className="tag" key={tag}>
|
||||||
{tag}
|
{tag}
|
||||||
@@ -362,83 +415,6 @@ export default function App() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="sidebar-meta">
|
|
||||||
<div className="meta-card">
|
|
||||||
<h3 className="meta-title">{t("app.sections.syncStatus")}</h3>
|
|
||||||
<p className="meta-desc">
|
|
||||||
{t("common.labels.status")}: {t(`app.sync.status.${syncStatus}`, { defaultValue: syncStatus })}
|
|
||||||
</p>
|
|
||||||
<p className="meta-desc">{syncDetail}</p>
|
|
||||||
<p className="meta-desc">
|
|
||||||
{t("common.labels.stage")}: {t(`progress.sync.${syncStage}`, { defaultValue: syncStage })}
|
|
||||||
</p>
|
|
||||||
<p className="meta-desc">
|
|
||||||
{t("common.labels.progress")}: {syncCurrent}/{syncTotal} · {t("common.labels.failed")}: {syncFailed}
|
|
||||||
</p>
|
|
||||||
{preferences.lastSyncedAt ? (
|
|
||||||
<p className="meta-desc">
|
|
||||||
{t("common.labels.lastSync")}: {lastSyncText}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
{failedListIds.length > 0 ? (
|
|
||||||
<button
|
|
||||||
className="button"
|
|
||||||
onClick={async () => {
|
|
||||||
if (!preferences.patToken) return;
|
|
||||||
setSyncStatus("retrying");
|
|
||||||
setSyncError("");
|
|
||||||
try {
|
|
||||||
const result = await retryListMembership(
|
|
||||||
{ token: preferences.patToken },
|
|
||||||
failedListIds,
|
|
||||||
(progress) => {
|
|
||||||
setSyncStage(progress.stage);
|
|
||||||
setSyncCurrent(progress.current);
|
|
||||||
setSyncTotal(progress.total);
|
|
||||||
setSyncFailed(progress.failed);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
setFailedListIds(result.failedListIds);
|
|
||||||
setSyncStatus("completed");
|
|
||||||
setSyncMessage({
|
|
||||||
key:
|
|
||||||
result.failedListIds.length === 0
|
|
||||||
? "app.sync.detail.retryRecovered"
|
|
||||||
: "app.sync.detail.retryFinished",
|
|
||||||
values:
|
|
||||||
result.failedListIds.length === 0
|
|
||||||
? undefined
|
|
||||||
: { count: result.failedListIds.length },
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
setSyncStatus("failed");
|
|
||||||
setSyncError((error as Error).message || t("app.sync.detail.retryFailed"));
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t("app.actions.retryFailedLists", { count: failedListIds.length })}
|
|
||||||
</button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<div className="meta-card">
|
|
||||||
<h3 className="meta-title">{t("app.sections.llmClassification")}</h3>
|
|
||||||
<p className="meta-desc">{t("app.sidebar.llmDesc")}</p>
|
|
||||||
<button className="button" onClick={() => setIsSettingsOpen(true)}>
|
|
||||||
{t("app.actions.configureLlm")}
|
|
||||||
</button>
|
|
||||||
<button className="button" onClick={() => setIsClassificationOpen(true)}>
|
|
||||||
{t("app.actions.runClassification")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="meta-card">
|
|
||||||
<h3 className="meta-title">{t("app.sections.batchActions")}</h3>
|
|
||||||
<p className="meta-desc">{t("app.sidebar.batchDesc")}</p>
|
|
||||||
<button className="button primary" onClick={() => setIsApplyUpdatesOpen(true)}>
|
|
||||||
{t("app.actions.applyUpdates")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{!preferences.hasCompletedOnboarding ? (
|
{!preferences.hasCompletedOnboarding ? (
|
||||||
@@ -460,25 +436,17 @@ export default function App() {
|
|||||||
try {
|
try {
|
||||||
const viewer = await validatePat(token);
|
const viewer = await validatePat(token);
|
||||||
setPatToken(token, viewer.login);
|
setPatToken(token, viewer.login);
|
||||||
setSyncStatus("ready");
|
|
||||||
setSyncError("");
|
|
||||||
setSyncMessage({ key: "app.sync.detail.tokenOk", values: { login: viewer.login } });
|
|
||||||
setIsPatModalOpen(false);
|
setIsPatModalOpen(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setSyncStatus("failed");
|
window.alert((error as Error).message || t("app.sync.detail.tokenValidationFailed"));
|
||||||
setSyncError((error as Error).message || t("app.sync.detail.tokenValidationFailed"));
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<SettingsModal isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
|
<SettingsModal isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
|
||||||
<LlmClassificationModal
|
<ManageListsModal
|
||||||
isOpen={isClassificationOpen}
|
isOpen={isManageListsOpen}
|
||||||
onClose={() => setIsClassificationOpen(false)}
|
onClose={() => setIsManageListsOpen(false)}
|
||||||
/>
|
patToken={preferences.patToken}
|
||||||
<ApplyUpdatesModal
|
|
||||||
isOpen={isApplyUpdatesOpen}
|
|
||||||
onClose={() => setIsApplyUpdatesOpen(false)}
|
|
||||||
token={preferences.patToken}
|
|
||||||
onRequestToken={() => setIsPatModalOpen(true)}
|
onRequestToken={() => setIsPatModalOpen(true)}
|
||||||
/>
|
/>
|
||||||
{assignRepo ? (
|
{assignRepo ? (
|
||||||
@@ -486,7 +454,9 @@ export default function App() {
|
|||||||
isOpen={Boolean(assignRepo)}
|
isOpen={Boolean(assignRepo)}
|
||||||
repoId={assignRepo.id}
|
repoId={assignRepo.id}
|
||||||
repoName={assignRepo.name}
|
repoName={assignRepo.name}
|
||||||
|
patToken={preferences.patToken}
|
||||||
onClose={() => setAssignRepo(null)}
|
onClose={() => setAssignRepo(null)}
|
||||||
|
onRequestToken={() => setIsPatModalOpen(true)}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,607 +0,0 @@
|
|||||||
import { db } from "../data/db";
|
|
||||||
import type { GitHubConfig } from "../services/githubClient";
|
|
||||||
import {
|
|
||||||
addStar,
|
|
||||||
buildRepoMembershipIndex,
|
|
||||||
createUserList,
|
|
||||||
detectStarListApi,
|
|
||||||
fetchStarLists,
|
|
||||||
getRepositoryMeta,
|
|
||||||
type UserListRef,
|
|
||||||
updateUserListsForItem,
|
|
||||||
} from "../services/githubStarLists";
|
|
||||||
import { runWithConcurrency } from "./queues";
|
|
||||||
|
|
||||||
export type WritebackIssueReason =
|
|
||||||
| "empty_tags"
|
|
||||||
| "repo_not_found"
|
|
||||||
| "invalid_repo_name"
|
|
||||||
| "repo_meta_missing"
|
|
||||||
| "repo_meta_fetch_failed"
|
|
||||||
| "missing_list"
|
|
||||||
| "create_list_failed"
|
|
||||||
| "membership_scan_failed"
|
|
||||||
| "no_changes"
|
|
||||||
| "unstarred_requires_confirmation"
|
|
||||||
| "add_star_failed"
|
|
||||||
| "update_failed";
|
|
||||||
|
|
||||||
export type WritebackIssue = {
|
|
||||||
repoId?: string;
|
|
||||||
repoFullName?: string;
|
|
||||||
reason: WritebackIssueReason;
|
|
||||||
message: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WritebackCandidate = {
|
|
||||||
repoId: string;
|
|
||||||
repoFullName: string;
|
|
||||||
itemId: string;
|
|
||||||
viewerHasStarred: boolean;
|
|
||||||
targetTags: string[];
|
|
||||||
targetListIds: string[];
|
|
||||||
targetListNames: string[];
|
|
||||||
currentListIds: string[];
|
|
||||||
currentListNames: string[];
|
|
||||||
finalListIds: string[];
|
|
||||||
finalListNames: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WritebackPlan = {
|
|
||||||
totalClassifications: number;
|
|
||||||
validTaggedRepos: number;
|
|
||||||
actionableRepos: number;
|
|
||||||
unchangedRepos: number;
|
|
||||||
scanFailures: number;
|
|
||||||
missingLists: string[];
|
|
||||||
createdLists: string[];
|
|
||||||
unstarredActionableRepos: number;
|
|
||||||
skipped: WritebackIssue[];
|
|
||||||
candidates: WritebackCandidate[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WritebackResult = {
|
|
||||||
plan: WritebackPlan;
|
|
||||||
applied: number;
|
|
||||||
failed: WritebackIssue[];
|
|
||||||
skipped: WritebackIssue[];
|
|
||||||
createdLists: string[];
|
|
||||||
locallyUpdated: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WritebackProgress = {
|
|
||||||
stage: string;
|
|
||||||
current: number;
|
|
||||||
total: number;
|
|
||||||
failed: number;
|
|
||||||
skipped: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PlanWritebackOptions = {
|
|
||||||
createMissingLists?: boolean;
|
|
||||||
createMissingListsAsPrivate?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ApplyWritebackOptions = {
|
|
||||||
autoStarForUnstarred?: boolean;
|
|
||||||
resolveAutoStarForUnstarred?: (unstarredCount: number) => boolean | Promise<boolean>;
|
|
||||||
createMissingListsAsPrivate?: boolean;
|
|
||||||
reusePlan?: WritebackPlan | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type PreparedWriteback = {
|
|
||||||
plan: WritebackPlan;
|
|
||||||
listIdToName: Map<string, string>;
|
|
||||||
createdListRefs: UserListRef[];
|
|
||||||
};
|
|
||||||
|
|
||||||
const REPO_META_CONCURRENCY = 3;
|
|
||||||
|
|
||||||
export async function planWriteback(
|
|
||||||
config: GitHubConfig,
|
|
||||||
options: PlanWritebackOptions = {},
|
|
||||||
onProgress?: (progress: WritebackProgress) => void
|
|
||||||
): Promise<WritebackPlan> {
|
|
||||||
const prepared = await prepareWriteback(
|
|
||||||
config,
|
|
||||||
options.createMissingLists ?? false,
|
|
||||||
options.createMissingListsAsPrivate,
|
|
||||||
onProgress
|
|
||||||
);
|
|
||||||
return prepared.plan;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function applyWriteback(
|
|
||||||
config: GitHubConfig,
|
|
||||||
options: ApplyWritebackOptions,
|
|
||||||
onProgress?: (progress: WritebackProgress) => void
|
|
||||||
): Promise<WritebackResult> {
|
|
||||||
const prepared =
|
|
||||||
options.reusePlan != null
|
|
||||||
? {
|
|
||||||
plan: options.reusePlan,
|
|
||||||
listIdToName: new Map<string, string>(),
|
|
||||||
createdListRefs: [],
|
|
||||||
}
|
|
||||||
: await prepareWriteback(config, true, options.createMissingListsAsPrivate, onProgress);
|
|
||||||
|
|
||||||
return applyPreparedWriteback(config, prepared, options, onProgress);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function applyPreparedWriteback(
|
|
||||||
config: GitHubConfig,
|
|
||||||
prepared: PreparedWriteback,
|
|
||||||
options: ApplyWritebackOptions,
|
|
||||||
onProgress?: (progress: WritebackProgress) => void
|
|
||||||
): Promise<WritebackResult> {
|
|
||||||
const failed: WritebackIssue[] = [];
|
|
||||||
const skipped: WritebackIssue[] = [...prepared.plan.skipped];
|
|
||||||
const successfulCandidates: WritebackCandidate[] = [];
|
|
||||||
let applied = 0;
|
|
||||||
let current = 0;
|
|
||||||
const total = prepared.plan.candidates.length;
|
|
||||||
let autoStarForUnstarred = options.autoStarForUnstarred ?? false;
|
|
||||||
|
|
||||||
if (prepared.plan.unstarredActionableRepos > 0 && options.resolveAutoStarForUnstarred) {
|
|
||||||
autoStarForUnstarred = await options.resolveAutoStarForUnstarred(
|
|
||||||
prepared.plan.unstarredActionableRepos
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "applying_updates",
|
|
||||||
current: 0,
|
|
||||||
total: total || 1,
|
|
||||||
failed: failed.length,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const candidate of prepared.plan.candidates) {
|
|
||||||
if (!autoStarForUnstarred && !candidate.viewerHasStarred) {
|
|
||||||
skipped.push({
|
|
||||||
repoId: candidate.repoId,
|
|
||||||
repoFullName: candidate.repoFullName,
|
|
||||||
reason: "unstarred_requires_confirmation",
|
|
||||||
message: "Repo is not starred and auto-star was declined.",
|
|
||||||
});
|
|
||||||
current += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "applying_updates",
|
|
||||||
current,
|
|
||||||
total: total || 1,
|
|
||||||
failed: failed.length,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (autoStarForUnstarred && !candidate.viewerHasStarred) {
|
|
||||||
await addStar(config, candidate.itemId);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
failed.push({
|
|
||||||
repoId: candidate.repoId,
|
|
||||||
repoFullName: candidate.repoFullName,
|
|
||||||
reason: "add_star_failed",
|
|
||||||
message: `Failed to star repo before writeback: ${(error as Error).message || "unknown"}`,
|
|
||||||
});
|
|
||||||
current += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "applying_updates",
|
|
||||||
current,
|
|
||||||
total: total || 1,
|
|
||||||
failed: failed.length,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await updateUserListsForItem(config, candidate.itemId, candidate.finalListIds);
|
|
||||||
applied += 1;
|
|
||||||
successfulCandidates.push(candidate);
|
|
||||||
} catch (error) {
|
|
||||||
failed.push({
|
|
||||||
repoId: candidate.repoId,
|
|
||||||
repoFullName: candidate.repoFullName,
|
|
||||||
reason: "update_failed",
|
|
||||||
message: `Failed to update repo lists: ${(error as Error).message || "unknown"}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
current += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "applying_updates",
|
|
||||||
current,
|
|
||||||
total: total || 1,
|
|
||||||
failed: failed.length,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const locallyUpdated = await syncLocalWritebackState(
|
|
||||||
prepared,
|
|
||||||
successfulCandidates,
|
|
||||||
options.createMissingListsAsPrivate ?? false
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
plan: prepared.plan,
|
|
||||||
applied,
|
|
||||||
failed,
|
|
||||||
skipped,
|
|
||||||
createdLists: prepared.plan.createdLists,
|
|
||||||
locallyUpdated,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function prepareWriteback(
|
|
||||||
config: GitHubConfig,
|
|
||||||
createMissingLists: boolean,
|
|
||||||
createMissingListsAsPrivate = false,
|
|
||||||
onProgress?: (progress: WritebackProgress) => void
|
|
||||||
): Promise<PreparedWriteback> {
|
|
||||||
const skipped: WritebackIssue[] = [];
|
|
||||||
const createdLists: string[] = [];
|
|
||||||
const createdListRefs: UserListRef[] = [];
|
|
||||||
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "loading_local_classifications",
|
|
||||||
current: 0,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: 0,
|
|
||||||
});
|
|
||||||
const [classificationRows, repoRows] = await Promise.all([db.classifications.toArray(), db.repos.toArray()]);
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "loading_local_classifications",
|
|
||||||
current: 1,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
const repoById = new Map(repoRows.map((repo) => [repo.id, repo]));
|
|
||||||
const repoTargetTags = new Map<string, string[]>();
|
|
||||||
const allTargetTags = new Set<string>();
|
|
||||||
|
|
||||||
for (const row of classificationRows) {
|
|
||||||
const validTags = normalizeTags(row.tags);
|
|
||||||
if (validTags.length === 0) {
|
|
||||||
skipped.push({
|
|
||||||
repoId: row.repoId,
|
|
||||||
reason: "empty_tags",
|
|
||||||
message: "Classification has no valid tags.",
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!repoById.has(row.repoId)) {
|
|
||||||
skipped.push({
|
|
||||||
repoId: row.repoId,
|
|
||||||
reason: "repo_not_found",
|
|
||||||
message: "Repo is not present in local database.",
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
repoTargetTags.set(row.repoId, validTags);
|
|
||||||
for (const tag of validTags) {
|
|
||||||
allTargetTags.add(tag);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "fetching_star_lists",
|
|
||||||
current: 0,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
const listApi = await detectStarListApi(config);
|
|
||||||
const remoteLists = await fetchStarLists(config, listApi);
|
|
||||||
const listNameToId = new Map(remoteLists.map((list) => [list.name, list.id]));
|
|
||||||
const listIdToName = new Map(remoteLists.map((list) => [list.id, list.name]));
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "fetching_star_lists",
|
|
||||||
current: 1,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
const missingLists: string[] = [];
|
|
||||||
for (const tag of allTargetTags) {
|
|
||||||
if (!listNameToId.has(tag)) {
|
|
||||||
missingLists.push(tag);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (createMissingLists && missingLists.length > 0) {
|
|
||||||
let current = 0;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "creating_missing_lists",
|
|
||||||
current: 0,
|
|
||||||
total: missingLists.length,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
for (const listName of missingLists) {
|
|
||||||
try {
|
|
||||||
const created = await createUserList(config, listName, createMissingListsAsPrivate, "");
|
|
||||||
listNameToId.set(created.name, created.id);
|
|
||||||
listIdToName.set(created.id, created.name);
|
|
||||||
createdLists.push(created.name);
|
|
||||||
createdListRefs.push(created);
|
|
||||||
} catch (error) {
|
|
||||||
skipped.push({
|
|
||||||
reason: "create_list_failed",
|
|
||||||
message: `Failed to create list "${listName}": ${(error as Error).message || "unknown"}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
current += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "creating_missing_lists",
|
|
||||||
current,
|
|
||||||
total: missingLists.length,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolvableRepoIds = Array.from(repoTargetTags.keys());
|
|
||||||
const repoMetaByRepoId = new Map<string, { itemId: string; viewerHasStarred: boolean; repoFullName: string }>();
|
|
||||||
let repoMetaCurrent = 0;
|
|
||||||
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "resolving_repositories",
|
|
||||||
current: 0,
|
|
||||||
total: resolvableRepoIds.length || 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
const repoMetaTasks = resolvableRepoIds.map((repoId) => async () => {
|
|
||||||
const repo = repoById.get(repoId);
|
|
||||||
if (!repo) return;
|
|
||||||
const parsed = parseRepoFullName(repo.fullName);
|
|
||||||
if (!parsed) {
|
|
||||||
skipped.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: repo.fullName,
|
|
||||||
reason: "invalid_repo_name",
|
|
||||||
message: `Invalid fullName format: ${repo.fullName}`,
|
|
||||||
});
|
|
||||||
repoMetaCurrent += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "resolving_repositories",
|
|
||||||
current: repoMetaCurrent,
|
|
||||||
total: resolvableRepoIds.length || 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const meta = await getRepositoryMeta(config, parsed.owner, parsed.name);
|
|
||||||
if (!meta) {
|
|
||||||
skipped.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: repo.fullName,
|
|
||||||
reason: "repo_meta_missing",
|
|
||||||
message: "Repository metadata cannot be loaded from GitHub.",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
repoMetaByRepoId.set(repoId, {
|
|
||||||
itemId: meta.id,
|
|
||||||
viewerHasStarred: meta.viewerHasStarred,
|
|
||||||
repoFullName: repo.fullName,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
skipped.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: repo.fullName,
|
|
||||||
reason: "repo_meta_fetch_failed",
|
|
||||||
message: `Repository metadata request failed: ${(error as Error).message || "unknown"}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
repoMetaCurrent += 1;
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "resolving_repositories",
|
|
||||||
current: repoMetaCurrent,
|
|
||||||
total: resolvableRepoIds.length || 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
await runWithConcurrency(repoMetaTasks, REPO_META_CONCURRENCY);
|
|
||||||
|
|
||||||
const targetRepoIds = new Set<string>();
|
|
||||||
for (const meta of repoMetaByRepoId.values()) {
|
|
||||||
targetRepoIds.add(meta.itemId);
|
|
||||||
}
|
|
||||||
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "scanning_existing_memberships",
|
|
||||||
current: 0,
|
|
||||||
total: listNameToId.size || 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
const repoMembershipResult = await buildRepoMembershipIndex(
|
|
||||||
config,
|
|
||||||
Array.from(listNameToId.values()),
|
|
||||||
targetRepoIds,
|
|
||||||
(progress) => {
|
|
||||||
emitProgress(onProgress, {
|
|
||||||
stage: "scanning_existing_memberships",
|
|
||||||
current: progress.current,
|
|
||||||
total: progress.total || 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: skipped.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const repoMembershipIndex = repoMembershipResult.index;
|
|
||||||
const scanFailures = repoMembershipResult.failedListIds.length;
|
|
||||||
for (const failedListId of repoMembershipResult.failedListIds) {
|
|
||||||
skipped.push({
|
|
||||||
reason: "membership_scan_failed",
|
|
||||||
message: `Membership scan failed for list ${listIdToName.get(failedListId) || failedListId}.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidates: WritebackCandidate[] = [];
|
|
||||||
let unchangedRepos = 0;
|
|
||||||
let unstarredActionableRepos = 0;
|
|
||||||
|
|
||||||
for (const [repoId, tags] of repoTargetTags.entries()) {
|
|
||||||
const meta = repoMetaByRepoId.get(repoId);
|
|
||||||
if (!meta) continue;
|
|
||||||
|
|
||||||
const targetListIds: string[] = [];
|
|
||||||
let hasMissingList = false;
|
|
||||||
for (const tag of tags) {
|
|
||||||
const listId = listNameToId.get(tag);
|
|
||||||
if (!listId) {
|
|
||||||
hasMissingList = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
targetListIds.push(listId);
|
|
||||||
}
|
|
||||||
if (hasMissingList) {
|
|
||||||
skipped.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: meta.repoFullName,
|
|
||||||
reason: "missing_list",
|
|
||||||
message: "One or more target lists do not exist on GitHub.",
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentSet = repoMembershipIndex.get(meta.itemId) ?? new Set<string>();
|
|
||||||
const finalSet = new Set([...currentSet, ...targetListIds]);
|
|
||||||
const changed = finalSet.size !== currentSet.size;
|
|
||||||
|
|
||||||
if (!changed) {
|
|
||||||
unchangedRepos += 1;
|
|
||||||
skipped.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: meta.repoFullName,
|
|
||||||
reason: "no_changes",
|
|
||||||
message: "Repo already contains all target lists.",
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!meta.viewerHasStarred) {
|
|
||||||
unstarredActionableRepos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
candidates.push({
|
|
||||||
repoId,
|
|
||||||
repoFullName: meta.repoFullName,
|
|
||||||
itemId: meta.itemId,
|
|
||||||
viewerHasStarred: meta.viewerHasStarred,
|
|
||||||
targetTags: tags,
|
|
||||||
targetListIds: uniqueArray(targetListIds),
|
|
||||||
targetListNames: uniqueArray(
|
|
||||||
targetListIds.map((id) => listIdToName.get(id)).filter((name): name is string => Boolean(name))
|
|
||||||
),
|
|
||||||
currentListIds: Array.from(currentSet),
|
|
||||||
currentListNames: Array.from(currentSet)
|
|
||||||
.map((id) => listIdToName.get(id))
|
|
||||||
.filter((name): name is string => Boolean(name)),
|
|
||||||
finalListIds: Array.from(finalSet),
|
|
||||||
finalListNames: Array.from(finalSet)
|
|
||||||
.map((id) => listIdToName.get(id))
|
|
||||||
.filter((name): name is string => Boolean(name)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
plan: {
|
|
||||||
totalClassifications: classificationRows.length,
|
|
||||||
validTaggedRepos: repoTargetTags.size,
|
|
||||||
actionableRepos: candidates.length,
|
|
||||||
unchangedRepos,
|
|
||||||
scanFailures,
|
|
||||||
missingLists,
|
|
||||||
createdLists,
|
|
||||||
unstarredActionableRepos,
|
|
||||||
skipped,
|
|
||||||
candidates,
|
|
||||||
},
|
|
||||||
listIdToName,
|
|
||||||
createdListRefs,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function syncLocalWritebackState(
|
|
||||||
prepared: PreparedWriteback,
|
|
||||||
successfulCandidates: WritebackCandidate[],
|
|
||||||
createMissingListsAsPrivate: boolean
|
|
||||||
): Promise<number> {
|
|
||||||
const updates = successfulCandidates.map((candidate) => ({
|
|
||||||
repoId: candidate.repoId,
|
|
||||||
listIds: candidate.finalListIds,
|
|
||||||
}));
|
|
||||||
|
|
||||||
await db.transaction("rw", db.lists, db.repoLists, async () => {
|
|
||||||
if (prepared.createdListRefs.length > 0) {
|
|
||||||
await db.lists.bulkPut(
|
|
||||||
prepared.createdListRefs.map((list) => ({
|
|
||||||
id: list.id,
|
|
||||||
name: list.name,
|
|
||||||
description: "",
|
|
||||||
isPrivate: createMissingListsAsPrivate,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const update of updates) {
|
|
||||||
await db.repoLists.put(update);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return updates.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTags(tags: string[]): string[] {
|
|
||||||
const out: string[] = [];
|
|
||||||
const seen = new Set<string>();
|
|
||||||
|
|
||||||
for (const raw of tags) {
|
|
||||||
const tag = raw.trim();
|
|
||||||
if (!tag) continue;
|
|
||||||
if (tag.toLowerCase() === "unclassified") continue;
|
|
||||||
const key = tag.toLowerCase();
|
|
||||||
if (seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
out.push(tag);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseRepoFullName(fullName: string): { owner: string; name: string } | null {
|
|
||||||
const parts = fullName.split("/");
|
|
||||||
if (parts.length !== 2) return null;
|
|
||||||
const owner = parts[0].trim();
|
|
||||||
const name = parts[1].trim();
|
|
||||||
if (!owner || !name) return null;
|
|
||||||
return { owner, name };
|
|
||||||
}
|
|
||||||
|
|
||||||
function uniqueArray(items: string[]): string[] {
|
|
||||||
return Array.from(new Set(items));
|
|
||||||
}
|
|
||||||
|
|
||||||
function emitProgress(
|
|
||||||
onProgress: ((progress: WritebackProgress) => void) | undefined,
|
|
||||||
progress: WritebackProgress
|
|
||||||
) {
|
|
||||||
onProgress?.(progress);
|
|
||||||
}
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
import type { LLMConfig } from "../services/llmClient";
|
|
||||||
import { requestCompletion } from "../services/llmClient";
|
|
||||||
import { resolvePrompts } from "./llmPromptResolver";
|
|
||||||
import { runWithConcurrency } from "./queues";
|
|
||||||
|
|
||||||
export type RepoForClassification = {
|
|
||||||
id: string;
|
|
||||||
fullName: string;
|
|
||||||
description: string;
|
|
||||||
topics: string[];
|
|
||||||
language: string | null;
|
|
||||||
readmeExcerpt: string;
|
|
||||||
existingLists?: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ClassificationProgress = {
|
|
||||||
stage: string;
|
|
||||||
current: number;
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ClassificationResult = {
|
|
||||||
repoTags: Record<string, string[]>;
|
|
||||||
compressedTags: string[];
|
|
||||||
tagMap: Record<string, string>;
|
|
||||||
runId: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ClassificationOptions = {
|
|
||||||
strictSingleTag?: boolean;
|
|
||||||
pass1Prompt?: string;
|
|
||||||
pass1StrictPrompt?: string;
|
|
||||||
pass2Prompt?: string;
|
|
||||||
useExistingLists?: boolean;
|
|
||||||
allowNewTagsWithExistingLists?: boolean;
|
|
||||||
language?: "zh" | "en";
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_PASS2_PROMPT =
|
|
||||||
"You consolidate tag lists by merging synonyms and near-duplicates. Output only JSON mapping each original tag to a compressed tag. Do not invent new tags beyond the provided list.";
|
|
||||||
|
|
||||||
export async function runTwoStageClassification(
|
|
||||||
config: LLMConfig,
|
|
||||||
repos: RepoForClassification[],
|
|
||||||
options: ClassificationOptions = {},
|
|
||||||
onProgress?: (progress: ClassificationProgress) => void
|
|
||||||
): Promise<ClassificationResult> {
|
|
||||||
const mode = {
|
|
||||||
strictSingleTag: options.strictSingleTag ?? false,
|
|
||||||
useExistingLists: options.useExistingLists ?? false,
|
|
||||||
allowNewTagsWithExistingLists: options.allowNewTagsWithExistingLists !== false,
|
|
||||||
language: options.language ?? "en",
|
|
||||||
} as const;
|
|
||||||
const prompts = resolvePrompts(config, mode);
|
|
||||||
const repoTags: Record<string, string[]> = {};
|
|
||||||
let completed = 0;
|
|
||||||
const runId = createRunId();
|
|
||||||
|
|
||||||
const tasks = repos.map((repo) => async () => {
|
|
||||||
const tags = await classifyRepo(config, repo, {
|
|
||||||
strictSingleTag: mode.strictSingleTag,
|
|
||||||
systemPrompt: prompts.selectedPass1,
|
|
||||||
useExistingLists: mode.useExistingLists,
|
|
||||||
allowNewTagsWithExistingLists: mode.allowNewTagsWithExistingLists,
|
|
||||||
});
|
|
||||||
completed += 1;
|
|
||||||
onProgress?.({ stage: "classifying_repos", current: completed, total: repos.length });
|
|
||||||
return { id: repo.id, tags };
|
|
||||||
});
|
|
||||||
|
|
||||||
const results = await runWithConcurrency(tasks, 3);
|
|
||||||
const allTags: string[] = [];
|
|
||||||
for (const result of results) {
|
|
||||||
repoTags[result.id] = result.tags;
|
|
||||||
allTags.push(...result.tags);
|
|
||||||
}
|
|
||||||
|
|
||||||
const uniqueTags = normalizeTags(allTags);
|
|
||||||
onProgress?.({ stage: "compressing_tags", current: 0, total: 1 });
|
|
||||||
const tagMap = await compressTags(config, uniqueTags, prompts.pass2);
|
|
||||||
const compressedTags = Array.from(new Set(Object.values(tagMap)));
|
|
||||||
|
|
||||||
for (const repoId of Object.keys(repoTags)) {
|
|
||||||
repoTags[repoId] = repoTags[repoId].map((tag) => tagMap[tag] ?? tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
onProgress?.({ stage: "compressing_tags", current: 1, total: 1 });
|
|
||||||
return { repoTags, compressedTags, tagMap, runId };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function classifyRepo(
|
|
||||||
config: LLMConfig,
|
|
||||||
repo: RepoForClassification,
|
|
||||||
options: {
|
|
||||||
strictSingleTag: boolean;
|
|
||||||
systemPrompt: string;
|
|
||||||
useExistingLists?: boolean;
|
|
||||||
allowNewTagsWithExistingLists?: boolean;
|
|
||||||
}
|
|
||||||
): Promise<string[]> {
|
|
||||||
const userContent = [
|
|
||||||
`Name: ${repo.fullName}`,
|
|
||||||
`Description: ${repo.description || ""}`,
|
|
||||||
`Topics: ${repo.topics.join(", ") || ""}`,
|
|
||||||
`Language: ${repo.language || ""}`,
|
|
||||||
`README: ${repo.readmeExcerpt.slice(0, 800)}`,
|
|
||||||
options.useExistingLists
|
|
||||||
? `Existing Lists: ${repo.existingLists && repo.existingLists.length > 0 ? repo.existingLists.join(", ") : "(none)"}`
|
|
||||||
: "",
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
const response = await requestCompletion(config, [
|
|
||||||
{ role: "system", content: options.systemPrompt },
|
|
||||||
{ role: "user", content: userContent },
|
|
||||||
]);
|
|
||||||
|
|
||||||
const tags = parseTags(response, options.strictSingleTag);
|
|
||||||
if (options.useExistingLists && options.allowNewTagsWithExistingLists === false) {
|
|
||||||
const existing = new Set((repo.existingLists || []).map((tag) => tag.toLowerCase()));
|
|
||||||
return tags.filter((tag) => existing.has(tag.toLowerCase()));
|
|
||||||
}
|
|
||||||
if (tags.length === 0) {
|
|
||||||
return ["Unclassified"];
|
|
||||||
}
|
|
||||||
return tags;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function compressTags(
|
|
||||||
config: LLMConfig,
|
|
||||||
tags: string[],
|
|
||||||
pass2Prompt?: string
|
|
||||||
): Promise<Record<string, string>> {
|
|
||||||
if (tags.length === 0) return {};
|
|
||||||
if (tags.length === 1) return { [tags[0]]: tags[0] };
|
|
||||||
|
|
||||||
const userContent = JSON.stringify({ tags });
|
|
||||||
try {
|
|
||||||
const response = await requestCompletion(config, [
|
|
||||||
{ role: "system", content: pass2Prompt || DEFAULT_PASS2_PROMPT },
|
|
||||||
{ role: "user", content: userContent },
|
|
||||||
]);
|
|
||||||
return parseTagMap(response, tags);
|
|
||||||
} catch {
|
|
||||||
return Object.fromEntries(tags.map((tag) => [tag, tag]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTags(response: string, strictSingleTag: boolean): string[] {
|
|
||||||
const trimmed = response.trim();
|
|
||||||
if (!trimmed) return [];
|
|
||||||
|
|
||||||
if (trimmed.startsWith("[")) {
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(trimmed) as string[];
|
|
||||||
if (Array.isArray(parsed)) {
|
|
||||||
const normalized = normalizeTags(parsed);
|
|
||||||
return strictSingleTag ? normalized.slice(0, 1) : normalized;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// fall through
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = trimmed
|
|
||||||
.split(/[,\n]/)
|
|
||||||
.map((part) => part.replace(/^[-*\d.\s]+/, "").trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const normalized = normalizeTags(parts);
|
|
||||||
return strictSingleTag ? normalized.slice(0, 1) : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTagMap(response: string, originals: string[]): Record<string, string> {
|
|
||||||
const fallback = Object.fromEntries(originals.map((tag) => [tag, tag]));
|
|
||||||
const raw = extractJson(response);
|
|
||||||
if (!raw) return fallback;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(raw) as Record<string, string> | Array<{ from: string; to: string }>;
|
|
||||||
const map: Record<string, string> = { ...fallback };
|
|
||||||
if (Array.isArray(parsed)) {
|
|
||||||
for (const entry of parsed) {
|
|
||||||
if (!entry?.from || !entry?.to) continue;
|
|
||||||
map[entry.from.trim()] = entry.to.trim();
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
for (const [key, value] of Object.entries(parsed)) {
|
|
||||||
if (!key || !value) continue;
|
|
||||||
map[key.trim()] = value.trim();
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
} catch {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractJson(text: string): string | null {
|
|
||||||
const start = text.indexOf("{");
|
|
||||||
const end = text.lastIndexOf("}");
|
|
||||||
if (start === -1 || end === -1 || end <= start) return null;
|
|
||||||
return text.slice(start, end + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTags(tags: string[]): string[] {
|
|
||||||
const seen = new Set<string>();
|
|
||||||
const result: string[] = [];
|
|
||||||
for (const tag of tags) {
|
|
||||||
const cleaned = tag.trim();
|
|
||||||
if (!cleaned) continue;
|
|
||||||
const key = cleaned.toLowerCase();
|
|
||||||
if (seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
result.push(cleaned);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
function createRunId(): string {
|
|
||||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
||||||
const random = Math.random().toString(36).slice(2, 8);
|
|
||||||
return `run-${stamp}-${random}`;
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
import type { LLMConfig } from "../services/llmClient";
|
|
||||||
|
|
||||||
export type PromptLanguage = "zh" | "en";
|
|
||||||
|
|
||||||
export type PromptFieldKey =
|
|
||||||
| "pass1Prompt"
|
|
||||||
| "pass1StrictPrompt"
|
|
||||||
| "pass2Prompt"
|
|
||||||
| "pass1PromptWithExisting"
|
|
||||||
| "pass1PromptNoNewWithExisting"
|
|
||||||
| "pass1StrictPromptWithExisting"
|
|
||||||
| "pass1StrictNoNewWithExisting"
|
|
||||||
| "pass2PromptWithExisting"
|
|
||||||
| "pass1PromptZh"
|
|
||||||
| "pass1StrictPromptZh"
|
|
||||||
| "pass2PromptZh"
|
|
||||||
| "pass1PromptWithExistingZh"
|
|
||||||
| "pass1PromptNoNewWithExistingZh"
|
|
||||||
| "pass1StrictPromptWithExistingZh"
|
|
||||||
| "pass1StrictNoNewWithExistingZh"
|
|
||||||
| "pass2PromptWithExistingZh";
|
|
||||||
|
|
||||||
type PromptFieldSet = {
|
|
||||||
pass1: PromptFieldKey;
|
|
||||||
pass1Strict: PromptFieldKey;
|
|
||||||
pass2: PromptFieldKey;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PromptMode = {
|
|
||||||
useExistingLists: boolean;
|
|
||||||
allowNewTagsWithExistingLists: boolean;
|
|
||||||
strictSingleTag: boolean;
|
|
||||||
language: PromptLanguage;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ResolvedPrompts = {
|
|
||||||
pass1: string;
|
|
||||||
pass1Strict: string;
|
|
||||||
pass2: string;
|
|
||||||
selectedPass1: string;
|
|
||||||
activeKeys: PromptFieldSet;
|
|
||||||
inactiveKeys: PromptFieldKey[];
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_PASS1_PROMPT =
|
|
||||||
"You label GitHub repositories with 1-3 concise tags. Output only comma-separated tags.";
|
|
||||||
const DEFAULT_PASS1_STRICT_PROMPT =
|
|
||||||
"You label GitHub repositories with exactly 1 concise tag. Output only the tag text.";
|
|
||||||
const DEFAULT_PASS2_PROMPT =
|
|
||||||
"You consolidate tag lists by merging synonyms and near-duplicates. Output only JSON mapping each original tag to a compressed tag. Do not invent new tags beyond the provided list.";
|
|
||||||
|
|
||||||
const EN_PROMPT_FIELDS: PromptFieldKey[] = [
|
|
||||||
"pass1Prompt",
|
|
||||||
"pass1StrictPrompt",
|
|
||||||
"pass2Prompt",
|
|
||||||
"pass1PromptWithExisting",
|
|
||||||
"pass1PromptNoNewWithExisting",
|
|
||||||
"pass1StrictPromptWithExisting",
|
|
||||||
"pass1StrictNoNewWithExisting",
|
|
||||||
"pass2PromptWithExisting",
|
|
||||||
];
|
|
||||||
|
|
||||||
const ZH_PROMPT_FIELDS: PromptFieldKey[] = [
|
|
||||||
"pass1PromptZh",
|
|
||||||
"pass1StrictPromptZh",
|
|
||||||
"pass2PromptZh",
|
|
||||||
"pass1PromptWithExistingZh",
|
|
||||||
"pass1PromptNoNewWithExistingZh",
|
|
||||||
"pass1StrictPromptWithExistingZh",
|
|
||||||
"pass1StrictNoNewWithExistingZh",
|
|
||||||
"pass2PromptWithExistingZh",
|
|
||||||
];
|
|
||||||
|
|
||||||
export function resolvePrompts(config: LLMConfig, mode: PromptMode): ResolvedPrompts {
|
|
||||||
const activeKeys = resolvePromptKeys(mode);
|
|
||||||
const pass1 = readPrompt(config, activeKeys.pass1, DEFAULT_PASS1_PROMPT);
|
|
||||||
const pass1Strict = readPrompt(config, activeKeys.pass1Strict, DEFAULT_PASS1_STRICT_PROMPT);
|
|
||||||
const pass2 = readPrompt(config, activeKeys.pass2, DEFAULT_PASS2_PROMPT);
|
|
||||||
const selectedPass1 = mode.strictSingleTag ? pass1Strict : pass1;
|
|
||||||
const inactiveKeys = getPromptFields(mode.language).filter(
|
|
||||||
(key) =>
|
|
||||||
key !== activeKeys.pass1 && key !== activeKeys.pass1Strict && key !== activeKeys.pass2
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
pass1,
|
|
||||||
pass1Strict,
|
|
||||||
pass2,
|
|
||||||
selectedPass1,
|
|
||||||
activeKeys,
|
|
||||||
inactiveKeys,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePromptKeys(mode: PromptMode): PromptFieldSet {
|
|
||||||
if (mode.language === "zh") {
|
|
||||||
return resolveZhPromptKeys(mode);
|
|
||||||
}
|
|
||||||
return resolveEnPromptKeys(mode);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveEnPromptKeys(mode: PromptMode): PromptFieldSet {
|
|
||||||
if (!mode.useExistingLists) {
|
|
||||||
return {
|
|
||||||
pass1: "pass1Prompt",
|
|
||||||
pass1Strict: "pass1StrictPrompt",
|
|
||||||
pass2: "pass2Prompt",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode.allowNewTagsWithExistingLists) {
|
|
||||||
return {
|
|
||||||
pass1: "pass1PromptWithExisting",
|
|
||||||
pass1Strict: "pass1StrictPromptWithExisting",
|
|
||||||
pass2: "pass2PromptWithExisting",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
pass1: "pass1PromptNoNewWithExisting",
|
|
||||||
pass1Strict: "pass1StrictNoNewWithExisting",
|
|
||||||
pass2: "pass2PromptWithExisting",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveZhPromptKeys(mode: PromptMode): PromptFieldSet {
|
|
||||||
if (!mode.useExistingLists) {
|
|
||||||
return {
|
|
||||||
pass1: "pass1PromptZh",
|
|
||||||
pass1Strict: "pass1StrictPromptZh",
|
|
||||||
pass2: "pass2PromptZh",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode.allowNewTagsWithExistingLists) {
|
|
||||||
return {
|
|
||||||
pass1: "pass1PromptWithExistingZh",
|
|
||||||
pass1Strict: "pass1StrictPromptWithExistingZh",
|
|
||||||
pass2: "pass2PromptWithExistingZh",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
pass1: "pass1PromptNoNewWithExistingZh",
|
|
||||||
pass1Strict: "pass1StrictNoNewWithExistingZh",
|
|
||||||
pass2: "pass2PromptWithExistingZh",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function getPromptFields(language: PromptLanguage): PromptFieldKey[] {
|
|
||||||
return language === "zh" ? ZH_PROMPT_FIELDS : EN_PROMPT_FIELDS;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readPrompt(config: LLMConfig, key: PromptFieldKey, fallback: string): string {
|
|
||||||
const value = config[key];
|
|
||||||
if (typeof value === "string" && value.trim()) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
18
src/app/core/purgeListLocal.ts
Normal file
18
src/app/core/purgeListLocal.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { db } from "../data/db";
|
||||||
|
|
||||||
|
/** Removes a list from `db.lists` and strips its id from every `repoLists` row. */
|
||||||
|
export async function purgeListFromLocalStores(listId: string): Promise<void> {
|
||||||
|
await db.transaction("rw", db.lists, db.repoLists, async () => {
|
||||||
|
await db.lists.delete(listId);
|
||||||
|
const rows = await db.repoLists.toArray();
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!row.listIds.includes(listId)) continue;
|
||||||
|
const next = row.listIds.filter((id) => id !== listId);
|
||||||
|
if (next.length === 0) {
|
||||||
|
await db.repoLists.delete(row.repoId);
|
||||||
|
} else {
|
||||||
|
await db.repoLists.put({ repoId: row.repoId, listIds: next });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
40
src/app/core/syncRepoListToGitHub.ts
Normal file
40
src/app/core/syncRepoListToGitHub.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { db } from "../data/db";
|
||||||
|
import type { GitHubConfig } from "../services/githubClient";
|
||||||
|
import { addStar, getRepositoryMeta, updateUserListsForItem } from "../services/githubStarLists";
|
||||||
|
|
||||||
|
function parseRepoFullName(fullName: string): { owner: string; name: string } | null {
|
||||||
|
const parts = fullName.split("/");
|
||||||
|
if (parts.length !== 2) return null;
|
||||||
|
const owner = parts[0].trim();
|
||||||
|
const name = parts[1].trim();
|
||||||
|
if (!owner || !name) return null;
|
||||||
|
return { owner, name };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pushes the selected Star List IDs for a repo to GitHub (replaces list membership for that starred item).
|
||||||
|
* Stars the repo first if the viewer has not starred it yet.
|
||||||
|
*/
|
||||||
|
export async function syncRepoListAssignmentToGitHub(
|
||||||
|
config: GitHubConfig,
|
||||||
|
repoId: string,
|
||||||
|
listIds: string[]
|
||||||
|
): Promise<void> {
|
||||||
|
const repo = await db.repos.get(repoId);
|
||||||
|
if (!repo) {
|
||||||
|
throw new Error("Repository not found in local database.");
|
||||||
|
}
|
||||||
|
const parsed = parseRepoFullName(repo.fullName);
|
||||||
|
if (!parsed) {
|
||||||
|
throw new Error(`Invalid repository name: ${repo.fullName}`);
|
||||||
|
}
|
||||||
|
const meta = await getRepositoryMeta(config, parsed.owner, parsed.name);
|
||||||
|
if (!meta) {
|
||||||
|
throw new Error("Could not load repository from GitHub.");
|
||||||
|
}
|
||||||
|
const uniqueListIds = Array.from(new Set(listIds.map((id) => id.trim()).filter(Boolean)));
|
||||||
|
if (!meta.viewerHasStarred) {
|
||||||
|
await addStar(config, meta.id);
|
||||||
|
}
|
||||||
|
await updateUserListsForItem(config, meta.id, uniqueListIds);
|
||||||
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
export type RepoInfo = {
|
|
||||||
id: string;
|
|
||||||
fullName: string;
|
|
||||||
description: string;
|
|
||||||
url: string;
|
|
||||||
topics: string[];
|
|
||||||
language: string | null;
|
|
||||||
updatedAt: string;
|
|
||||||
readmeExcerpt: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type StarList = {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
isPrivate: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ClassificationResult = {
|
|
||||||
repoId: string;
|
|
||||||
listName: string;
|
|
||||||
confidence: number;
|
|
||||||
};
|
|
||||||
@@ -31,17 +31,13 @@ export const resources = {
|
|||||||
app: {
|
app: {
|
||||||
subtitle: "Organize GitHub Star Lists with confidence.",
|
subtitle: "Organize GitHub Star Lists with confidence.",
|
||||||
actions: {
|
actions: {
|
||||||
applyUpdates: "Apply Updates",
|
|
||||||
assignList: "Assign List",
|
assignList: "Assign List",
|
||||||
configureLlm: "Configure LLM",
|
|
||||||
connectPat: "Connect PAT",
|
connectPat: "Connect PAT",
|
||||||
|
manageLists: "Manage lists",
|
||||||
retryFailedLists: "Retry failed lists ({{count}})",
|
retryFailedLists: "Retry failed lists ({{count}})",
|
||||||
runClassification: "Run Classification",
|
|
||||||
syncStarLists: "Sync Star Lists",
|
syncStarLists: "Sync Star Lists",
|
||||||
},
|
},
|
||||||
sections: {
|
sections: {
|
||||||
batchActions: "Batch Actions",
|
|
||||||
llmClassification: "LLM Classification",
|
|
||||||
repositories: "Repositories",
|
repositories: "Repositories",
|
||||||
starLists: "Star Lists",
|
starLists: "Star Lists",
|
||||||
syncStatus: "Sync Status",
|
syncStatus: "Sync Status",
|
||||||
@@ -81,18 +77,18 @@ export const resources = {
|
|||||||
noFilteredTitle: "No repositories match the current filters.",
|
noFilteredTitle: "No repositories match the current filters.",
|
||||||
noFilteredHint: "Try clearing filters or sync your Star Lists first.",
|
noFilteredHint: "Try clearing filters or sync your Star Lists first.",
|
||||||
},
|
},
|
||||||
sidebar: {
|
|
||||||
llmDesc: "Configure your OpenAI-compatible endpoint to auto-label repos.",
|
|
||||||
batchDesc: "Apply optimized Star Lists back to GitHub with one click.",
|
|
||||||
},
|
|
||||||
values: {
|
values: {
|
||||||
noDescription: "No description",
|
noDescription: "No description",
|
||||||
},
|
},
|
||||||
|
nav: {
|
||||||
|
openStarLists: "Categories",
|
||||||
|
closeListSidebar: "Close categories",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
onboarding: {
|
onboarding: {
|
||||||
title: "README Fetching",
|
title: "README Fetching",
|
||||||
description1:
|
description1:
|
||||||
"We can fetch README snippets to improve classification quality. This may increase GitHub API usage and takes longer to sync.",
|
"We can fetch README snippets during sync. This may increase GitHub API usage and takes longer.",
|
||||||
description2:
|
description2:
|
||||||
"Would you like to enable README fetching now? You can change this later in Settings.",
|
"Would you like to enable README fetching now? You can change this later in Settings.",
|
||||||
skip: "Skip for now",
|
skip: "Skip for now",
|
||||||
@@ -108,14 +104,12 @@ export const resources = {
|
|||||||
settings: {
|
settings: {
|
||||||
closeAria: "Close settings",
|
closeAria: "Close settings",
|
||||||
title: "Settings",
|
title: "Settings",
|
||||||
description: "Manage tokens, LLM configuration, README fetching, and local cache.",
|
description: "Manage tokens, README fetching, and local cache.",
|
||||||
sections: {
|
sections: {
|
||||||
language: "Language",
|
language: "Language",
|
||||||
localCache: "Local Cache",
|
localCache: "Local Cache",
|
||||||
llmConfiguration: "LLM Configuration",
|
|
||||||
patManagement: "PAT Management",
|
patManagement: "PAT Management",
|
||||||
readmeFetching: "README Fetching",
|
readmeFetching: "README Fetching",
|
||||||
writeback: "Writeback",
|
|
||||||
},
|
},
|
||||||
language: {
|
language: {
|
||||||
appLanguage: "App language",
|
appLanguage: "App language",
|
||||||
@@ -137,122 +131,43 @@ export const resources = {
|
|||||||
validationFailed: "PAT validation failed ({{name}}): {{message}}",
|
validationFailed: "PAT validation failed ({{name}}): {{message}}",
|
||||||
cleared: "PAT cleared.",
|
cleared: "PAT cleared.",
|
||||||
},
|
},
|
||||||
llm: {
|
|
||||||
useExistingLists: "Use existing Star Lists as context",
|
|
||||||
allowNewTags: "Allow new tags when using existing lists",
|
|
||||||
currentMode: "Current mode",
|
|
||||||
modeBase: "Base mode: classify without existing Star Lists context.",
|
|
||||||
modeExisting:
|
|
||||||
"Existing lists mode: prefer existing lists and allow new tags.",
|
|
||||||
modeExistingOnly:
|
|
||||||
"Existing-only mode: classify with existing lists only, no new tags.",
|
|
||||||
baseUrl: "Base URL",
|
|
||||||
apiKey: "API Key",
|
|
||||||
model: "Model",
|
|
||||||
temperature: "Temperature",
|
|
||||||
maxTokens: "Max Tokens",
|
|
||||||
activePass1: "Pass 1 System Prompt (active mode)",
|
|
||||||
activePass1Strict: "Pass 1 Strict System Prompt (active mode)",
|
|
||||||
activePass2: "Pass 2 System Prompt (active mode)",
|
|
||||||
advancedSettings: "Advanced prompt settings ({{count}})",
|
|
||||||
advancedHelp:
|
|
||||||
"Edit prompts for non-active modes. These values are kept but hidden from the main view.",
|
|
||||||
testLlm: "Test LLM",
|
|
||||||
testing: "Testing...",
|
|
||||||
resetLlm: "Reset LLM",
|
|
||||||
missingBaseUrl: "Missing base URL.",
|
|
||||||
missingApiKey: "Missing API key.",
|
|
||||||
testOk: "OK in {{elapsed}}ms · {{response}}",
|
|
||||||
testError: "Error ({{name}}) in {{elapsed}}ms: {{message}}",
|
|
||||||
cleared: "LLM config cleared.",
|
|
||||||
promptLabels: {
|
|
||||||
pass1Prompt: "Pass 1 Base Prompt",
|
|
||||||
pass1StrictPrompt: "Pass 1 Strict Base Prompt",
|
|
||||||
pass2Prompt: "Pass 2 Base Prompt",
|
|
||||||
pass1PromptWithExisting: "Pass 1 Existing Context Prompt",
|
|
||||||
pass1PromptNoNewWithExisting: "Pass 1 Existing-Only Prompt",
|
|
||||||
pass1StrictPromptWithExisting:
|
|
||||||
"Pass 1 Strict Existing Context Prompt",
|
|
||||||
pass1StrictNoNewWithExisting: "Pass 1 Strict Existing-Only Prompt",
|
|
||||||
pass2PromptWithExisting: "Pass 2 Existing Context Prompt",
|
|
||||||
pass1PromptZh: "Pass 1 Base Prompt (ZH)",
|
|
||||||
pass1StrictPromptZh: "Pass 1 Strict Base Prompt (ZH)",
|
|
||||||
pass2PromptZh: "Pass 2 Base Prompt (ZH)",
|
|
||||||
pass1PromptWithExistingZh: "Pass 1 Existing Context Prompt (ZH)",
|
|
||||||
pass1PromptNoNewWithExistingZh:
|
|
||||||
"Pass 1 Existing-Only Prompt (ZH)",
|
|
||||||
pass1StrictPromptWithExistingZh:
|
|
||||||
"Pass 1 Strict Existing Context Prompt (ZH)",
|
|
||||||
pass1StrictNoNewWithExistingZh:
|
|
||||||
"Pass 1 Strict Existing-Only Prompt (ZH)",
|
|
||||||
pass2PromptWithExistingZh: "Pass 2 Existing Context Prompt (ZH)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
readme: {
|
readme: {
|
||||||
enable: "Enable README snippets during sync",
|
enable: "Enable README snippets during sync",
|
||||||
},
|
},
|
||||||
writeback: {
|
|
||||||
refreshBeforeApply: "Refresh GitHub data before apply",
|
|
||||||
refreshHelp:
|
|
||||||
"When enabled, Apply Updates recalculates the writeback plan using latest GitHub state.",
|
|
||||||
},
|
|
||||||
cache: {
|
cache: {
|
||||||
help: "Clear IndexedDB data to reset your local cache.",
|
help: "Clear IndexedDB data to reset your local cache.",
|
||||||
clearButton: "Clear Local Cache",
|
clearButton: "Clear Local Cache",
|
||||||
cleared: "Local cache cleared. Reloading...",
|
cleared: "Local cache cleared. Reloading...",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
classification: {
|
listManage: {
|
||||||
closeAria: "Close classification",
|
closeAria: "Close list management",
|
||||||
title: "LLM Classification",
|
title: "Manage Star Lists",
|
||||||
description:
|
intro:
|
||||||
"Run a two-stage classification. Stage 2 only compresses tags to save tokens.",
|
"Create, rename, or delete lists on GitHub. Changes apply to your account and update the local cache.",
|
||||||
sections: {
|
createSection: "New list",
|
||||||
diffView: "Diff View",
|
editSection: "Edit list",
|
||||||
preview: "Preview",
|
existingSection: "Your lists",
|
||||||
runStatus: "Run Status",
|
nameLabel: "Name",
|
||||||
},
|
descriptionLabel: "Description",
|
||||||
actions: {
|
isPrivate: "Private list",
|
||||||
run: "Run Classification",
|
create: "Create",
|
||||||
running: "Running...",
|
save: "Save",
|
||||||
},
|
cancelEdit: "Cancel edit",
|
||||||
labels: {
|
edit: "Edit",
|
||||||
compareAgainst: "Compare against",
|
delete: "Delete",
|
||||||
current: "Current",
|
reposColumn: "Repos",
|
||||||
existing: "Existing",
|
actionsColumn: "Actions",
|
||||||
previous: "Previous",
|
deleteConfirm:
|
||||||
selectRun: "Select run",
|
"Delete list \"{{name}}\" on GitHub? Starred repositories stay starred; only this list is removed.",
|
||||||
},
|
empty: "No lists yet. Create one above, or sync to import existing lists.",
|
||||||
options: {
|
needPat: "Connect a GitHub PAT first.",
|
||||||
existingStarLists: "Existing Star Lists",
|
nameRequired: "Name is required.",
|
||||||
previousRun: "Previous run",
|
saveFailed: "Could not save the list.",
|
||||||
selectRunPlaceholder: "Select a run",
|
deleteFailed: "Could not delete the list.",
|
||||||
reposSuffix: "repos",
|
|
||||||
testSuffix: "test",
|
|
||||||
singleSuffix: "single",
|
|
||||||
},
|
|
||||||
toggles: {
|
|
||||||
strictSingleTag: "Strict single tag (exactly 1 per repo)",
|
|
||||||
testMode: "Test mode (first 5 repos)",
|
|
||||||
},
|
|
||||||
status: {
|
status: {
|
||||||
noResults: "No classification results yet.",
|
creating: "Creating...",
|
||||||
noSavedRuns: "No saved runs yet.",
|
saving: "Saving...",
|
||||||
noTagDiff: "No tag differences found.",
|
|
||||||
noDiffFromExisting: "No differences from existing lists.",
|
|
||||||
},
|
|
||||||
errors: {
|
|
||||||
missingConfig: "LLM config is missing.",
|
|
||||||
noRepos: "No repos available. Sync your Star Lists first.",
|
|
||||||
classificationFailed: "Classification failed",
|
|
||||||
},
|
|
||||||
stage: {
|
|
||||||
idle: "Idle",
|
|
||||||
preparing: "Preparing",
|
|
||||||
classifying_repos: "Classifying repos",
|
|
||||||
compressing_tags: "Compressing tags",
|
|
||||||
completed: "Completed",
|
|
||||||
failed: "Failed",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
assignList: {
|
assignList: {
|
||||||
@@ -267,81 +182,7 @@ export const resources = {
|
|||||||
saved: "Saved.",
|
saved: "Saved.",
|
||||||
saveFailed: "Save failed.",
|
saveFailed: "Save failed.",
|
||||||
saving: "Saving...",
|
saving: "Saving...",
|
||||||
},
|
needPat: "Connect a GitHub PAT first to sync Star Lists to GitHub.",
|
||||||
},
|
|
||||||
apply: {
|
|
||||||
closeAria: "Close apply updates",
|
|
||||||
title: "Apply Updates",
|
|
||||||
description: "Write current classification results back to GitHub Star Lists.",
|
|
||||||
sections: {
|
|
||||||
applyResult: "Apply Result",
|
|
||||||
issues: "Issues",
|
|
||||||
planSummary: "Plan Summary",
|
|
||||||
plannedRepoChanges: "Planned Repo Changes",
|
|
||||||
progress: "Progress",
|
|
||||||
runControls: "Run Controls",
|
|
||||||
},
|
|
||||||
controls: {
|
|
||||||
refreshBeforeApply: "Refresh GitHub data before apply",
|
|
||||||
refreshOn:
|
|
||||||
"Apply will re-plan against latest GitHub state.",
|
|
||||||
refreshOff:
|
|
||||||
"Apply will use the current preview plan without re-planning.",
|
|
||||||
applyToGithub: "Apply to GitHub",
|
|
||||||
applying: "Applying...",
|
|
||||||
},
|
|
||||||
labels: {
|
|
||||||
actionable: "Actionable",
|
|
||||||
after: "After",
|
|
||||||
applied: "Applied",
|
|
||||||
createdLists: "Created Lists",
|
|
||||||
current: "Current",
|
|
||||||
failed: "Failed",
|
|
||||||
locallyUpdated: "Local updated",
|
|
||||||
missingLists: "Missing Lists",
|
|
||||||
skipped: "Skipped",
|
|
||||||
unchanged: "Unchanged",
|
|
||||||
unstarred: "Unstarred",
|
|
||||||
validTagged: "Valid Tagged",
|
|
||||||
},
|
|
||||||
status: {
|
|
||||||
noChangesDetected: "No repo list changes detected.",
|
|
||||||
scanFailures:
|
|
||||||
"Membership scan partial failures: {{count}}. Preview may be partially incomplete.",
|
|
||||||
},
|
|
||||||
errors: {
|
|
||||||
missingPat: "GitHub PAT is missing. Please connect PAT first.",
|
|
||||||
previewNotReady:
|
|
||||||
"Preview is not ready yet. Please wait for plan generation to finish.",
|
|
||||||
previewFailed: "Preview failed.",
|
|
||||||
applyFailed: "Apply failed.",
|
|
||||||
},
|
|
||||||
confirmUnstarred:
|
|
||||||
"Found {{count}} unstarred repos that require list updates.\n\nClick OK to auto-star and continue.\nClick Cancel to skip those repos and continue.",
|
|
||||||
stage: {
|
|
||||||
idle: "Idle",
|
|
||||||
preparing_preview: "Preparing preview",
|
|
||||||
preparing_writeback: "Preparing writeback",
|
|
||||||
loading_local_classifications: "Loading local classifications",
|
|
||||||
fetching_star_lists: "Fetching Star Lists",
|
|
||||||
creating_missing_lists: "Creating missing lists",
|
|
||||||
resolving_repositories: "Resolving repositories",
|
|
||||||
scanning_existing_memberships: "Scanning existing memberships",
|
|
||||||
applying_updates: "Applying updates",
|
|
||||||
},
|
|
||||||
issueReasons: {
|
|
||||||
empty_tags: "Empty tags",
|
|
||||||
repo_not_found: "Repo not found",
|
|
||||||
invalid_repo_name: "Invalid repo name",
|
|
||||||
repo_meta_missing: "Repo metadata missing",
|
|
||||||
repo_meta_fetch_failed: "Repo metadata fetch failed",
|
|
||||||
missing_list: "Missing list",
|
|
||||||
create_list_failed: "Create list failed",
|
|
||||||
membership_scan_failed: "Membership scan failed",
|
|
||||||
no_changes: "No changes",
|
|
||||||
unstarred_requires_confirmation: "Unstarred requires confirmation",
|
|
||||||
add_star_failed: "Add star failed",
|
|
||||||
update_failed: "Update failed",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
progress: {
|
progress: {
|
||||||
@@ -358,7 +199,7 @@ export const resources = {
|
|||||||
"zh-CN": {
|
"zh-CN": {
|
||||||
translation: {
|
translation: {
|
||||||
common: {
|
common: {
|
||||||
appName: "Star Manager",
|
appName: "GitHub星标管理面板",
|
||||||
actions: {
|
actions: {
|
||||||
cancel: "取消",
|
cancel: "取消",
|
||||||
clear: "清空",
|
clear: "清空",
|
||||||
@@ -387,17 +228,13 @@ export const resources = {
|
|||||||
app: {
|
app: {
|
||||||
subtitle: "更安心地管理 GitHub Star Lists。",
|
subtitle: "更安心地管理 GitHub Star Lists。",
|
||||||
actions: {
|
actions: {
|
||||||
applyUpdates: "应用更新",
|
|
||||||
assignList: "分配列表",
|
assignList: "分配列表",
|
||||||
configureLlm: "配置 LLM",
|
|
||||||
connectPat: "连接 PAT",
|
connectPat: "连接 PAT",
|
||||||
|
manageLists: "管理列表",
|
||||||
retryFailedLists: "重试失败列表({{count}})",
|
retryFailedLists: "重试失败列表({{count}})",
|
||||||
runClassification: "运行分类",
|
|
||||||
syncStarLists: "同步 Star Lists",
|
syncStarLists: "同步 Star Lists",
|
||||||
},
|
},
|
||||||
sections: {
|
sections: {
|
||||||
batchActions: "批量操作",
|
|
||||||
llmClassification: "LLM 分类",
|
|
||||||
repositories: "仓库",
|
repositories: "仓库",
|
||||||
starLists: "Star 列表",
|
starLists: "Star 列表",
|
||||||
syncStatus: "同步状态",
|
syncStatus: "同步状态",
|
||||||
@@ -437,18 +274,18 @@ export const resources = {
|
|||||||
noFilteredTitle: "当前筛选条件下没有匹配仓库。",
|
noFilteredTitle: "当前筛选条件下没有匹配仓库。",
|
||||||
noFilteredHint: "尝试清空筛选,或先同步 Star 列表。",
|
noFilteredHint: "尝试清空筛选,或先同步 Star 列表。",
|
||||||
},
|
},
|
||||||
sidebar: {
|
|
||||||
llmDesc: "配置兼容 OpenAI 的接口,自动为仓库打标签。",
|
|
||||||
batchDesc: "一键将优化后的 Star Lists 写回 GitHub。",
|
|
||||||
},
|
|
||||||
values: {
|
values: {
|
||||||
noDescription: "暂无描述",
|
noDescription: "暂无描述",
|
||||||
},
|
},
|
||||||
|
nav: {
|
||||||
|
openStarLists: "分类",
|
||||||
|
closeListSidebar: "关闭分类侧栏",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
onboarding: {
|
onboarding: {
|
||||||
title: "README 抓取",
|
title: "README 抓取",
|
||||||
description1:
|
description1:
|
||||||
"我们可以抓取 README 片段来提升分类质量,但会增加 GitHub API 调用并延长同步时间。",
|
"同步时可抓取 README 片段,会增加 GitHub API 调用并延长同步时间。",
|
||||||
description2: "是否现在启用 README 抓取?你也可以稍后在设置中修改。",
|
description2: "是否现在启用 README 抓取?你也可以稍后在设置中修改。",
|
||||||
skip: "暂不启用",
|
skip: "暂不启用",
|
||||||
enable: "启用 README 抓取",
|
enable: "启用 README 抓取",
|
||||||
@@ -463,14 +300,12 @@ export const resources = {
|
|||||||
settings: {
|
settings: {
|
||||||
closeAria: "关闭设置",
|
closeAria: "关闭设置",
|
||||||
title: "设置",
|
title: "设置",
|
||||||
description: "管理 Token、LLM 配置、README 抓取和本地缓存。",
|
description: "管理 Token、README 抓取和本地缓存。",
|
||||||
sections: {
|
sections: {
|
||||||
language: "语言",
|
language: "语言",
|
||||||
localCache: "本地缓存",
|
localCache: "本地缓存",
|
||||||
llmConfiguration: "LLM 配置",
|
|
||||||
patManagement: "PAT 管理",
|
patManagement: "PAT 管理",
|
||||||
readmeFetching: "README 抓取",
|
readmeFetching: "README 抓取",
|
||||||
writeback: "写回",
|
|
||||||
},
|
},
|
||||||
language: {
|
language: {
|
||||||
appLanguage: "界面语言",
|
appLanguage: "界面语言",
|
||||||
@@ -492,114 +327,41 @@ export const resources = {
|
|||||||
validationFailed: "PAT 校验失败({{name}}):{{message}}",
|
validationFailed: "PAT 校验失败({{name}}):{{message}}",
|
||||||
cleared: "PAT 已清除。",
|
cleared: "PAT 已清除。",
|
||||||
},
|
},
|
||||||
llm: {
|
|
||||||
useExistingLists: "使用已有 Star Lists 作为上下文",
|
|
||||||
allowNewTags: "使用已有列表时允许新增标签",
|
|
||||||
currentMode: "当前模式",
|
|
||||||
modeBase: "基础模式:不参考已有 Star Lists 进行分类。",
|
|
||||||
modeExisting: "已有列表模式:优先使用已有列表,并允许新增标签。",
|
|
||||||
modeExistingOnly: "仅已有列表模式:仅使用已有列表,不新增标签。",
|
|
||||||
baseUrl: "Base URL",
|
|
||||||
apiKey: "API Key",
|
|
||||||
model: "模型",
|
|
||||||
temperature: "温度",
|
|
||||||
maxTokens: "最大 Tokens",
|
|
||||||
activePass1: "Pass 1 系统 Prompt(当前模式)",
|
|
||||||
activePass1Strict: "Pass 1 严格系统 Prompt(当前模式)",
|
|
||||||
activePass2: "Pass 2 系统 Prompt(当前模式)",
|
|
||||||
advancedSettings: "高级 Prompt 设置({{count}})",
|
|
||||||
advancedHelp: "可编辑非当前模式的 Prompt,这些值会保留但不在主视图展示。",
|
|
||||||
testLlm: "测试 LLM",
|
|
||||||
testing: "测试中...",
|
|
||||||
resetLlm: "重置 LLM",
|
|
||||||
missingBaseUrl: "缺少 Base URL。",
|
|
||||||
missingApiKey: "缺少 API Key。",
|
|
||||||
testOk: "{{elapsed}}ms 内成功 · {{response}}",
|
|
||||||
testError: "错误({{name}}),耗时 {{elapsed}}ms:{{message}}",
|
|
||||||
cleared: "LLM 配置已清除。",
|
|
||||||
promptLabels: {
|
|
||||||
pass1Prompt: "Pass 1 基础 Prompt",
|
|
||||||
pass1StrictPrompt: "Pass 1 严格基础 Prompt",
|
|
||||||
pass2Prompt: "Pass 2 基础 Prompt",
|
|
||||||
pass1PromptWithExisting: "Pass 1 含已有上下文 Prompt",
|
|
||||||
pass1PromptNoNewWithExisting: "Pass 1 仅已有列表 Prompt",
|
|
||||||
pass1StrictPromptWithExisting: "Pass 1 严格含已有上下文 Prompt",
|
|
||||||
pass1StrictNoNewWithExisting: "Pass 1 严格仅已有列表 Prompt",
|
|
||||||
pass2PromptWithExisting: "Pass 2 含已有上下文 Prompt",
|
|
||||||
pass1PromptZh: "Pass 1 基础 Prompt(中文)",
|
|
||||||
pass1StrictPromptZh: "Pass 1 严格基础 Prompt(中文)",
|
|
||||||
pass2PromptZh: "Pass 2 基础 Prompt(中文)",
|
|
||||||
pass1PromptWithExistingZh: "Pass 1 含已有上下文 Prompt(中文)",
|
|
||||||
pass1PromptNoNewWithExistingZh: "Pass 1 仅已有列表 Prompt(中文)",
|
|
||||||
pass1StrictPromptWithExistingZh:
|
|
||||||
"Pass 1 严格含已有上下文 Prompt(中文)",
|
|
||||||
pass1StrictNoNewWithExistingZh: "Pass 1 严格仅已有列表 Prompt(中文)",
|
|
||||||
pass2PromptWithExistingZh: "Pass 2 含已有上下文 Prompt(中文)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
readme: {
|
readme: {
|
||||||
enable: "同步时启用 README 片段",
|
enable: "同步时启用 README 片段",
|
||||||
},
|
},
|
||||||
writeback: {
|
|
||||||
refreshBeforeApply: "应用前刷新 GitHub 数据",
|
|
||||||
refreshHelp: "启用后,Apply Updates 会基于最新 GitHub 状态重新生成写回计划。",
|
|
||||||
},
|
|
||||||
cache: {
|
cache: {
|
||||||
help: "清空 IndexedDB 数据以重置本地缓存。",
|
help: "清空 IndexedDB 数据以重置本地缓存。",
|
||||||
clearButton: "清空本地缓存",
|
clearButton: "清空本地缓存",
|
||||||
cleared: "本地缓存已清空,正在刷新...",
|
cleared: "本地缓存已清空,正在刷新...",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
classification: {
|
listManage: {
|
||||||
closeAria: "关闭分类",
|
closeAria: "关闭列表管理",
|
||||||
title: "LLM 分类",
|
title: "管理 Star 列表",
|
||||||
description: "执行两阶段分类。第 2 阶段仅压缩标签以节省 token。",
|
intro: "在 GitHub 上新建、重命名或删除列表。更改会应用到你的账号并更新本地缓存。",
|
||||||
sections: {
|
createSection: "新建列表",
|
||||||
diffView: "差异视图",
|
editSection: "编辑列表",
|
||||||
preview: "预览",
|
existingSection: "已有列表",
|
||||||
runStatus: "运行状态",
|
nameLabel: "名称",
|
||||||
},
|
descriptionLabel: "描述",
|
||||||
actions: {
|
isPrivate: "私有列表",
|
||||||
run: "运行分类",
|
create: "创建",
|
||||||
running: "运行中...",
|
save: "保存",
|
||||||
},
|
cancelEdit: "取消编辑",
|
||||||
labels: {
|
edit: "编辑",
|
||||||
compareAgainst: "对比基准",
|
delete: "删除",
|
||||||
current: "当前",
|
reposColumn: "仓库数",
|
||||||
existing: "已有",
|
actionsColumn: "操作",
|
||||||
previous: "上次",
|
deleteConfirm: "确认在 GitHub 上删除列表「{{name}}」?不会取消收藏仓库,仅删除该列表。",
|
||||||
selectRun: "选择运行记录",
|
empty: "暂无列表。可在上方新建,或先同步导入已有列表。",
|
||||||
},
|
needPat: "请先连接 GitHub PAT。",
|
||||||
options: {
|
nameRequired: "名称不能为空。",
|
||||||
existingStarLists: "已有 Star Lists",
|
saveFailed: "保存列表失败。",
|
||||||
previousRun: "历史运行",
|
deleteFailed: "删除列表失败。",
|
||||||
selectRunPlaceholder: "选择一条运行记录",
|
|
||||||
reposSuffix: "个仓库",
|
|
||||||
testSuffix: "测试",
|
|
||||||
singleSuffix: "单标签",
|
|
||||||
},
|
|
||||||
toggles: {
|
|
||||||
strictSingleTag: "严格单标签(每仓库仅 1 个)",
|
|
||||||
testMode: "测试模式(仅前 5 个仓库)",
|
|
||||||
},
|
|
||||||
status: {
|
status: {
|
||||||
noResults: "暂无分类结果。",
|
creating: "创建中...",
|
||||||
noSavedRuns: "暂无保存的运行记录。",
|
saving: "保存中...",
|
||||||
noTagDiff: "未发现标签差异。",
|
|
||||||
noDiffFromExisting: "与已有列表无差异。",
|
|
||||||
},
|
|
||||||
errors: {
|
|
||||||
missingConfig: "LLM 配置不完整。",
|
|
||||||
noRepos: "没有可分类仓库,请先同步 Star Lists。",
|
|
||||||
classificationFailed: "分类失败",
|
|
||||||
},
|
|
||||||
stage: {
|
|
||||||
idle: "空闲",
|
|
||||||
preparing: "准备中",
|
|
||||||
classifying_repos: "正在分类仓库",
|
|
||||||
compressing_tags: "正在压缩标签",
|
|
||||||
completed: "已完成",
|
|
||||||
failed: "失败",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
assignList: {
|
assignList: {
|
||||||
@@ -614,77 +376,7 @@ export const resources = {
|
|||||||
saved: "已保存。",
|
saved: "已保存。",
|
||||||
saveFailed: "保存失败。",
|
saveFailed: "保存失败。",
|
||||||
saving: "保存中...",
|
saving: "保存中...",
|
||||||
},
|
needPat: "请先连接 GitHub PAT,才能将 Star 列表同步到 GitHub。",
|
||||||
},
|
|
||||||
apply: {
|
|
||||||
closeAria: "关闭应用更新",
|
|
||||||
title: "应用更新",
|
|
||||||
description: "将当前分类结果写回到 GitHub Star Lists。",
|
|
||||||
sections: {
|
|
||||||
applyResult: "应用结果",
|
|
||||||
issues: "问题",
|
|
||||||
planSummary: "计划摘要",
|
|
||||||
plannedRepoChanges: "计划中的仓库变更",
|
|
||||||
progress: "进度",
|
|
||||||
runControls: "运行控制",
|
|
||||||
},
|
|
||||||
controls: {
|
|
||||||
refreshBeforeApply: "应用前刷新 GitHub 数据",
|
|
||||||
refreshOn: "应用时会基于最新 GitHub 状态重新规划。",
|
|
||||||
refreshOff: "应用时会直接使用当前预览计划,不再重新规划。",
|
|
||||||
applyToGithub: "应用到 GitHub",
|
|
||||||
applying: "应用中...",
|
|
||||||
},
|
|
||||||
labels: {
|
|
||||||
actionable: "可执行",
|
|
||||||
after: "变更后",
|
|
||||||
applied: "已应用",
|
|
||||||
createdLists: "新建列表",
|
|
||||||
current: "当前",
|
|
||||||
failed: "失败",
|
|
||||||
locallyUpdated: "本地已更新",
|
|
||||||
missingLists: "缺失列表",
|
|
||||||
skipped: "跳过",
|
|
||||||
unchanged: "未变化",
|
|
||||||
unstarred: "未收藏",
|
|
||||||
validTagged: "有效标签仓库",
|
|
||||||
},
|
|
||||||
status: {
|
|
||||||
noChangesDetected: "未检测到仓库列表变更。",
|
|
||||||
scanFailures: "列表成员扫描部分失败:{{count}}。预览可能不完整。",
|
|
||||||
},
|
|
||||||
errors: {
|
|
||||||
missingPat: "缺少 GitHub PAT,请先连接 PAT。",
|
|
||||||
previewNotReady: "预览尚未就绪,请等待计划生成完成。",
|
|
||||||
previewFailed: "预览失败。",
|
|
||||||
applyFailed: "应用失败。",
|
|
||||||
},
|
|
||||||
confirmUnstarred:
|
|
||||||
"发现 {{count}} 个未收藏仓库需要更新列表。\n\n点击“确定”将自动收藏并继续。\n点击“取消”将跳过这些仓库并继续。",
|
|
||||||
stage: {
|
|
||||||
idle: "空闲",
|
|
||||||
preparing_preview: "正在准备预览",
|
|
||||||
preparing_writeback: "正在准备写回",
|
|
||||||
loading_local_classifications: "正在加载本地分类",
|
|
||||||
fetching_star_lists: "正在拉取 Star 列表",
|
|
||||||
creating_missing_lists: "正在创建缺失列表",
|
|
||||||
resolving_repositories: "正在解析仓库",
|
|
||||||
scanning_existing_memberships: "正在扫描已有成员关系",
|
|
||||||
applying_updates: "正在应用更新",
|
|
||||||
},
|
|
||||||
issueReasons: {
|
|
||||||
empty_tags: "标签为空",
|
|
||||||
repo_not_found: "仓库不存在",
|
|
||||||
invalid_repo_name: "仓库名格式无效",
|
|
||||||
repo_meta_missing: "仓库元数据缺失",
|
|
||||||
repo_meta_fetch_failed: "获取仓库元数据失败",
|
|
||||||
missing_list: "目标列表缺失",
|
|
||||||
create_list_failed: "创建列表失败",
|
|
||||||
membership_scan_failed: "成员扫描失败",
|
|
||||||
no_changes: "无变更",
|
|
||||||
unstarred_requires_confirmation: "未收藏需确认",
|
|
||||||
add_star_failed: "自动收藏失败",
|
|
||||||
update_failed: "更新失败",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
progress: {
|
progress: {
|
||||||
|
|||||||
@@ -95,6 +95,20 @@ type CreateUserListResponse = {
|
|||||||
} | null;
|
} | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type UpdateUserListResponse = {
|
||||||
|
updateUserList: {
|
||||||
|
list: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description?: string | null;
|
||||||
|
} | null;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type DeleteUserListResponse = {
|
||||||
|
deleteUserList: { clientMutationId: string | null } | null;
|
||||||
|
};
|
||||||
|
|
||||||
type RepositoryMetaResponse = {
|
type RepositoryMetaResponse = {
|
||||||
repository: RepositoryMeta | null;
|
repository: RepositoryMeta | null;
|
||||||
};
|
};
|
||||||
@@ -334,6 +348,50 @@ export async function updateUserListsForItem(
|
|||||||
await ghGraphql(config, query, { input: { itemId, listIds } });
|
await ghGraphql(config, query, { input: { itemId, listIds } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function updateUserListOnGitHub(
|
||||||
|
config: GitHubConfig,
|
||||||
|
listId: string,
|
||||||
|
patch: { name?: string; description?: string; isPrivate?: boolean }
|
||||||
|
): Promise<{ id: string; name: string; description: string }> {
|
||||||
|
const input: Record<string, unknown> = { listId };
|
||||||
|
if (patch.name !== undefined) input.name = patch.name;
|
||||||
|
if (patch.description !== undefined) input.description = patch.description;
|
||||||
|
if (patch.isPrivate !== undefined) input.isPrivate = patch.isPrivate;
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
mutation($input: UpdateUserListInput!) {
|
||||||
|
updateUserList(input: $input) {
|
||||||
|
list {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
description
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const data = await ghGraphql<UpdateUserListResponse>(config, query, { input });
|
||||||
|
const list = data.updateUserList?.list;
|
||||||
|
if (!list) {
|
||||||
|
throw new Error("Failed to update list");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: list.id,
|
||||||
|
name: list.name,
|
||||||
|
description: list.description ?? "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUserListOnGitHub(config: GitHubConfig, listId: string): Promise<void> {
|
||||||
|
const query = `
|
||||||
|
mutation($input: DeleteUserListInput!) {
|
||||||
|
deleteUserList(input: $input) {
|
||||||
|
clientMutationId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
await ghGraphql<DeleteUserListResponse>(config, query, { input: { listId } });
|
||||||
|
}
|
||||||
|
|
||||||
export async function buildRepoMembershipIndex(
|
export async function buildRepoMembershipIndex(
|
||||||
config: GitHubConfig,
|
config: GitHubConfig,
|
||||||
listIds: string[],
|
listIds: string[],
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
export type LLMConfig = {
|
|
||||||
baseUrl: string;
|
|
||||||
apiKey: string;
|
|
||||||
model: string;
|
|
||||||
temperature: number;
|
|
||||||
maxTokens: number;
|
|
||||||
pass1Prompt?: string;
|
|
||||||
pass1StrictPrompt?: string;
|
|
||||||
pass2Prompt?: string;
|
|
||||||
pass1PromptZh?: string;
|
|
||||||
pass1StrictPromptZh?: string;
|
|
||||||
pass2PromptZh?: string;
|
|
||||||
pass1PromptWithExisting?: string;
|
|
||||||
pass1PromptNoNewWithExisting?: string;
|
|
||||||
pass1StrictPromptWithExisting?: string;
|
|
||||||
pass1StrictNoNewWithExisting?: string;
|
|
||||||
pass1PromptWithExistingZh?: string;
|
|
||||||
pass1PromptNoNewWithExistingZh?: string;
|
|
||||||
pass1StrictPromptWithExistingZh?: string;
|
|
||||||
pass1StrictNoNewWithExistingZh?: string;
|
|
||||||
pass2PromptWithExisting?: string;
|
|
||||||
pass2PromptWithExistingZh?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type LLMMessage = {
|
|
||||||
role: "system" | "user" | "assistant";
|
|
||||||
content: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function requestCompletion(
|
|
||||||
config: LLMConfig,
|
|
||||||
messages: LLMMessage[],
|
|
||||||
signal?: AbortSignal
|
|
||||||
): Promise<string> {
|
|
||||||
const response = await fetch(`${config.baseUrl}/chat/completions`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `Bearer ${config.apiKey}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
model: config.model,
|
|
||||||
temperature: config.temperature,
|
|
||||||
max_tokens: config.maxTokens,
|
|
||||||
messages,
|
|
||||||
}),
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const text = await response.text();
|
|
||||||
throw new Error(text || `LLM request failed: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
|
||||||
choices?: { message?: { content?: string } }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
const content = data.choices?.[0]?.message?.content?.trim();
|
|
||||||
if (!content) {
|
|
||||||
throw new Error("LLM response missing content");
|
|
||||||
}
|
|
||||||
|
|
||||||
return content;
|
|
||||||
}
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { useCallback, useSyncExternalStore } from "react";
|
|
||||||
import type { LLMConfig } from "../services/llmClient";
|
|
||||||
|
|
||||||
type LlmConfigState = {
|
|
||||||
config: LLMConfig;
|
|
||||||
};
|
|
||||||
|
|
||||||
const STORAGE_KEY = "star-manager.llm-config";
|
|
||||||
|
|
||||||
const defaultConfig: LLMConfig = {
|
|
||||||
baseUrl: "https://api.openai.com/v1",
|
|
||||||
apiKey: "",
|
|
||||||
model: "gpt-4o-mini",
|
|
||||||
temperature: 0.3,
|
|
||||||
maxTokens: 120,
|
|
||||||
pass1Prompt: "You label GitHub repositories with 1-3 concise tags. Output only comma-separated tags.",
|
|
||||||
pass1StrictPrompt: "You label GitHub repositories with exactly 1 concise tag. Output only the tag text.",
|
|
||||||
pass2Prompt:
|
|
||||||
"You consolidate tag lists by merging synonyms and near-duplicates. Output only JSON mapping each original tag to a compressed tag. Do not invent new tags beyond the provided list.",
|
|
||||||
pass1PromptZh:
|
|
||||||
"你将 GitHub 仓库标注为 1-3 个简洁标签,仅输出逗号分隔的标签。",
|
|
||||||
pass1StrictPromptZh: "你将 GitHub 仓库标注为且仅标注 1 个简洁标签,仅输出标签文本。",
|
|
||||||
pass2PromptZh:
|
|
||||||
"你需要合并标签中的同义词或近似词,输出仅包含原始标签到压缩标签的 JSON 映射。不要创造列表外的新标签。",
|
|
||||||
pass1PromptWithExisting:
|
|
||||||
"You label GitHub repositories with 1-3 concise tags. Prefer existing Star Lists when they fit, but you may add a new tag if needed. Output only comma-separated tags.",
|
|
||||||
pass1PromptNoNewWithExisting:
|
|
||||||
"You label GitHub repositories with 1-3 concise tags. You must select from the existing Star Lists only. If none fit, output nothing. Output only comma-separated tags.",
|
|
||||||
pass1StrictPromptWithExisting:
|
|
||||||
"You label GitHub repositories with exactly 1 concise tag. Prefer existing Star Lists when they fit. Output only the tag text.",
|
|
||||||
pass1StrictNoNewWithExisting:
|
|
||||||
"You must select exactly 1 tag from the existing Star Lists. If none fit, output nothing. Output only the tag text.",
|
|
||||||
pass1PromptWithExistingZh:
|
|
||||||
"你将 GitHub 仓库标注为 1-3 个简洁标签,优先使用已有 Star Lists,如有必要可新增标签,仅输出逗号分隔的标签。",
|
|
||||||
pass1PromptNoNewWithExistingZh:
|
|
||||||
"你将 GitHub 仓库标注为 1-3 个简洁标签,只能从已有 Star Lists 中选择。如果没有合适标签,请输出空内容,仅输出逗号分隔的标签。",
|
|
||||||
pass1StrictPromptWithExistingZh:
|
|
||||||
"你将 GitHub 仓库标注为且仅标注 1 个简洁标签,优先使用已有 Star Lists,仅输出标签文本。",
|
|
||||||
pass1StrictNoNewWithExistingZh:
|
|
||||||
"你必须从已有 Star Lists 中选择且仅选择 1 个标签。如果没有合适的标签,请输出空内容,仅输出标签文本。",
|
|
||||||
pass2PromptWithExisting:
|
|
||||||
"You consolidate tag lists by merging synonyms and near-duplicates. Output only JSON mapping each original tag to a compressed tag. Do not invent new tags beyond the provided list.",
|
|
||||||
pass2PromptWithExistingZh:
|
|
||||||
"你需要合并标签中的同义词或近似词,输出仅包含原始标签到压缩标签的 JSON 映射。不要创造列表外的新标签。",
|
|
||||||
};
|
|
||||||
|
|
||||||
let cached = readFromStorage();
|
|
||||||
const listeners = new Set<() => void>();
|
|
||||||
|
|
||||||
function emitChange() {
|
|
||||||
for (const listener of listeners) {
|
|
||||||
listener();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function readFromStorage(): LlmConfigState {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return { config: { ...defaultConfig } };
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
|
||||||
if (!raw) return { config: { ...defaultConfig } };
|
|
||||||
const parsed = JSON.parse(raw) as Partial<LLMConfig>;
|
|
||||||
return {
|
|
||||||
config: {
|
|
||||||
...defaultConfig,
|
|
||||||
...parsed,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return { config: { ...defaultConfig } };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function persist(next: LlmConfigState) {
|
|
||||||
cached = next;
|
|
||||||
if (typeof window !== "undefined") {
|
|
||||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next.config));
|
|
||||||
}
|
|
||||||
emitChange();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useLlmConfigStore() {
|
|
||||||
const state = useSyncExternalStore(
|
|
||||||
(onStoreChange) => {
|
|
||||||
listeners.add(onStoreChange);
|
|
||||||
return () => listeners.delete(onStoreChange);
|
|
||||||
},
|
|
||||||
() => cached,
|
|
||||||
() => cached
|
|
||||||
);
|
|
||||||
|
|
||||||
const setConfig = useCallback((config: LLMConfig) => {
|
|
||||||
persist({ config });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const updateConfig = useCallback((partial: Partial<LLMConfig>) => {
|
|
||||||
persist({ config: { ...cached.config, ...partial } });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const clearConfig = useCallback(() => {
|
|
||||||
persist({ config: { ...defaultConfig, apiKey: "" } });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return {
|
|
||||||
config: state.config,
|
|
||||||
setConfig,
|
|
||||||
updateConfig,
|
|
||||||
clearConfig,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -7,9 +7,6 @@ type Preferences = {
|
|||||||
patToken: string;
|
patToken: string;
|
||||||
viewerLogin: string;
|
viewerLogin: string;
|
||||||
lastSyncedAt: string;
|
lastSyncedAt: string;
|
||||||
useExistingListsForClassification: boolean;
|
|
||||||
allowNewTagsWithExistingLists: boolean;
|
|
||||||
refreshBeforeApply: boolean;
|
|
||||||
uiLanguage: UiLanguagePreference;
|
uiLanguage: UiLanguagePreference;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -21,9 +18,6 @@ const defaultPreferences: Preferences = {
|
|||||||
patToken: "",
|
patToken: "",
|
||||||
viewerLogin: "",
|
viewerLogin: "",
|
||||||
lastSyncedAt: "",
|
lastSyncedAt: "",
|
||||||
useExistingListsForClassification: false,
|
|
||||||
allowNewTagsWithExistingLists: true,
|
|
||||||
refreshBeforeApply: true,
|
|
||||||
uiLanguage: "auto",
|
uiLanguage: "auto",
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -87,18 +81,6 @@ export function usePreferenceStore() {
|
|||||||
persist({ ...cached, lastSyncedAt: timestamp });
|
persist({ ...cached, lastSyncedAt: timestamp });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const setUseExistingListsForClassification = useCallback((value: boolean) => {
|
|
||||||
persist({ ...cached, useExistingListsForClassification: value });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setAllowNewTagsWithExistingLists = useCallback((value: boolean) => {
|
|
||||||
persist({ ...cached, allowNewTagsWithExistingLists: value });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setRefreshBeforeApply = useCallback((value: boolean) => {
|
|
||||||
persist({ ...cached, refreshBeforeApply: value });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setUiLanguage = useCallback((value: UiLanguagePreference) => {
|
const setUiLanguage = useCallback((value: UiLanguagePreference) => {
|
||||||
persist({ ...cached, uiLanguage: value });
|
persist({ ...cached, uiLanguage: value });
|
||||||
}, []);
|
}, []);
|
||||||
@@ -109,9 +91,6 @@ export function usePreferenceStore() {
|
|||||||
markOnboarded,
|
markOnboarded,
|
||||||
setPatToken,
|
setPatToken,
|
||||||
setLastSyncedAt,
|
setLastSyncedAt,
|
||||||
setUseExistingListsForClassification,
|
|
||||||
setAllowNewTagsWithExistingLists,
|
|
||||||
setRefreshBeforeApply,
|
|
||||||
setUiLanguage,
|
setUiLanguage,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1 +1 @@
|
|||||||
@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600&display=swap");
|
@import url("https://fonts.googleapis.com/css2?family=Source+Sans+3:wght@400;500;600&family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;1,8..60,400&display=swap");
|
||||||
|
|||||||
@@ -1,313 +0,0 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import {
|
|
||||||
applyWriteback,
|
|
||||||
planWriteback,
|
|
||||||
type WritebackPlan,
|
|
||||||
type WritebackProgress,
|
|
||||||
type WritebackResult,
|
|
||||||
} from "../core/githubWriteback";
|
|
||||||
import { usePreferenceStore } from "../store/preferences";
|
|
||||||
|
|
||||||
type ApplyUpdatesModalProps = {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
token: string;
|
|
||||||
onRequestToken: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const EMPTY_PROGRESS: WritebackProgress = {
|
|
||||||
stage: "idle",
|
|
||||||
current: 0,
|
|
||||||
total: 0,
|
|
||||||
failed: 0,
|
|
||||||
skipped: 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function ApplyUpdatesModal({
|
|
||||||
isOpen,
|
|
||||||
onClose,
|
|
||||||
token,
|
|
||||||
onRequestToken,
|
|
||||||
}: ApplyUpdatesModalProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const { preferences, setRefreshBeforeApply } = usePreferenceStore();
|
|
||||||
const [plan, setPlan] = useState<WritebackPlan | null>(null);
|
|
||||||
const [result, setResult] = useState<WritebackResult | null>(null);
|
|
||||||
const [progress, setProgress] = useState<WritebackProgress>(EMPTY_PROGRESS);
|
|
||||||
const [isPlanning, setIsPlanning] = useState(false);
|
|
||||||
const [isApplying, setIsApplying] = useState(false);
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const requestSeqRef = useRef(0);
|
|
||||||
|
|
||||||
const summary = useMemo(() => {
|
|
||||||
const activePlan = result?.plan ?? plan;
|
|
||||||
if (!activePlan) return null;
|
|
||||||
return {
|
|
||||||
actionableRepos: activePlan.actionableRepos,
|
|
||||||
unchangedRepos: activePlan.unchangedRepos,
|
|
||||||
validTaggedRepos: activePlan.validTaggedRepos,
|
|
||||||
unstarredRepos: activePlan.unstarredActionableRepos,
|
|
||||||
missingLists: activePlan.missingLists.length,
|
|
||||||
createdLists: activePlan.createdLists.length,
|
|
||||||
};
|
|
||||||
}, [plan, result]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isOpen) {
|
|
||||||
requestSeqRef.current += 1;
|
|
||||||
setPlan(null);
|
|
||||||
setResult(null);
|
|
||||||
setProgress(EMPTY_PROGRESS);
|
|
||||||
setIsPlanning(false);
|
|
||||||
setIsApplying(false);
|
|
||||||
setError("");
|
|
||||||
}
|
|
||||||
}, [isOpen]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isOpen) return;
|
|
||||||
const trimmedToken = token.trim();
|
|
||||||
if (!trimmedToken) {
|
|
||||||
setPlan(null);
|
|
||||||
setResult(null);
|
|
||||||
setProgress(EMPTY_PROGRESS);
|
|
||||||
setIsPlanning(false);
|
|
||||||
setError(t("apply.errors.missingPat"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestId = ++requestSeqRef.current;
|
|
||||||
setIsPlanning(true);
|
|
||||||
setError("");
|
|
||||||
setResult(null);
|
|
||||||
setProgress({
|
|
||||||
stage: "preparing_preview",
|
|
||||||
current: 0,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
planWriteback({ token: trimmedToken }, {}, setProgress)
|
|
||||||
.then((nextPlan) => {
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setPlan(nextPlan);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setError((err as Error).message || t("apply.errors.previewFailed"));
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setIsPlanning(false);
|
|
||||||
});
|
|
||||||
}, [isOpen, token, t]);
|
|
||||||
|
|
||||||
if (!isOpen) return null;
|
|
||||||
|
|
||||||
const ensureToken = (): boolean => {
|
|
||||||
if (token.trim()) return true;
|
|
||||||
setError(t("apply.errors.missingPat"));
|
|
||||||
onRequestToken();
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleApply = async () => {
|
|
||||||
if (!ensureToken()) return;
|
|
||||||
if (!preferences.refreshBeforeApply && !plan) {
|
|
||||||
setError(t("apply.errors.previewNotReady"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const requestId = ++requestSeqRef.current;
|
|
||||||
setIsApplying(true);
|
|
||||||
setError("");
|
|
||||||
setResult(null);
|
|
||||||
setProgress({
|
|
||||||
stage: "preparing_writeback",
|
|
||||||
current: 0,
|
|
||||||
total: 1,
|
|
||||||
failed: 0,
|
|
||||||
skipped: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const nextResult = await applyWriteback(
|
|
||||||
{ token: token.trim() },
|
|
||||||
{
|
|
||||||
createMissingListsAsPrivate: false,
|
|
||||||
reusePlan: preferences.refreshBeforeApply ? null : plan,
|
|
||||||
resolveAutoStarForUnstarred: (unstarredCount) =>
|
|
||||||
window.confirm(t("apply.confirmUnstarred", { count: unstarredCount })),
|
|
||||||
},
|
|
||||||
setProgress
|
|
||||||
);
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setResult(nextResult);
|
|
||||||
setPlan(nextResult.plan);
|
|
||||||
} catch (err) {
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setError((err as Error).message || t("apply.errors.applyFailed"));
|
|
||||||
} finally {
|
|
||||||
if (requestId !== requestSeqRef.current) return;
|
|
||||||
setIsApplying(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const disabled = isPlanning || isApplying;
|
|
||||||
const issues = result ? [...result.failed, ...result.skipped] : (plan?.skipped ?? []);
|
|
||||||
const changePreviewRows = (result?.plan.candidates ?? plan?.candidates ?? []).slice(0, 80);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="drawer" role="dialog" aria-modal="true">
|
|
||||||
<div className="drawer-panel settings">
|
|
||||||
<button className="panel-close" onClick={onClose} aria-label={t("apply.closeAria")}>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
<div className="settings-scroll">
|
|
||||||
<h3>{t("apply.title")}</h3>
|
|
||||||
<p>{t("apply.description")}</p>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.runControls")}</h4>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={preferences.refreshBeforeApply}
|
|
||||||
onChange={(event) => setRefreshBeforeApply(event.target.checked)}
|
|
||||||
disabled={disabled}
|
|
||||||
/>
|
|
||||||
{t("apply.controls.refreshBeforeApply")}
|
|
||||||
</label>
|
|
||||||
<p className="helper-text">
|
|
||||||
{preferences.refreshBeforeApply
|
|
||||||
? t("apply.controls.refreshOn")
|
|
||||||
: t("apply.controls.refreshOff")}
|
|
||||||
</p>
|
|
||||||
<div className="settings-actions">
|
|
||||||
<button className="button primary" onClick={handleApply} disabled={disabled}>
|
|
||||||
{isApplying ? t("apply.controls.applying") : t("apply.controls.applyToGithub")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.progress")}</h4>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.stage")}: {t(`apply.stage.${progress.stage}`, { defaultValue: progress.stage })}
|
|
||||||
</p>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.progress")}: {progress.current}/{progress.total} · {t("apply.labels.failed")}: {progress.failed} · {t("apply.labels.skipped")}: {progress.skipped}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{summary ? (
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.planSummary")}</h4>
|
|
||||||
<div className="writeback-summary-grid">
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.actionable")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.actionableRepos}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.unchanged")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.unchangedRepos}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.validTagged")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.validTaggedRepos}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.unstarred")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.unstarredRepos}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.missingLists")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.missingLists}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-summary-item">
|
|
||||||
<span className="writeback-summary-label">{t("apply.labels.createdLists")}</span>
|
|
||||||
<span className="writeback-summary-value">{summary.createdLists}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{plan?.scanFailures ? (
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("apply.status.scanFailures", { count: plan.scanFailures })}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{changePreviewRows.length > 0 ? (
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.plannedRepoChanges")}</h4>
|
|
||||||
<div className="writeback-preview-list">
|
|
||||||
{changePreviewRows.map((row) => (
|
|
||||||
<div className="writeback-preview-item" key={row.repoId}>
|
|
||||||
<div className="writeback-preview-title">{row.repoFullName}</div>
|
|
||||||
<div className="writeback-preview-row">
|
|
||||||
<span className="writeback-preview-label">{t("apply.labels.current")}</span>
|
|
||||||
<span>{row.currentListNames.join(", ") || t("common.values.none")}</span>
|
|
||||||
</div>
|
|
||||||
<div className="writeback-preview-row">
|
|
||||||
<span className="writeback-preview-label">{t("apply.labels.after")}</span>
|
|
||||||
<span>{row.finalListNames.join(", ") || t("common.values.none")}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : plan ? (
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.plannedRepoChanges")}</h4>
|
|
||||||
<p className="helper-text">{t("apply.status.noChangesDetected")}</p>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{result ? (
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.applyResult")}</h4>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("apply.labels.applied")}: {result.applied}
|
|
||||||
</p>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("apply.labels.locallyUpdated")}: {result.locallyUpdated}
|
|
||||||
</p>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("apply.labels.failed")}: {result.failed.length}
|
|
||||||
</p>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("apply.labels.skipped")}: {result.skipped.length}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{issues.length > 0 ? (
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("apply.sections.issues")}</h4>
|
|
||||||
<div className="writeback-issues">
|
|
||||||
{issues.slice(0, 60).map((issue, index) => (
|
|
||||||
<div key={`${issue.reason}-${issue.repoId || "global"}-${index}`} className="writeback-issue">
|
|
||||||
<span className="writeback-issue-reason">
|
|
||||||
{t(`apply.issueReasons.${issue.reason}`, { defaultValue: issue.reason })}
|
|
||||||
</span>
|
|
||||||
<span className="writeback-issue-msg">
|
|
||||||
{issue.repoFullName ? `${issue.repoFullName}: ` : ""}
|
|
||||||
{issue.message}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{error ? (
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.error")}: {error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { setRepoListMembership } from "../core/repoListAssignments";
|
import { setRepoListMembership } from "../core/repoListAssignments";
|
||||||
|
import { syncRepoListAssignmentToGitHub } from "../core/syncRepoListToGitHub";
|
||||||
import { db } from "../data/db";
|
import { db } from "../data/db";
|
||||||
import { useLiveQuery } from "../data/useLiveQuery";
|
import { useLiveQuery } from "../data/useLiveQuery";
|
||||||
|
|
||||||
@@ -8,10 +9,19 @@ type AssignListModalProps = {
|
|||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
repoId: string;
|
repoId: string;
|
||||||
repoName: string;
|
repoName: string;
|
||||||
|
patToken: string;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
onRequestToken?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AssignListModal({ isOpen, repoId, repoName, onClose }: AssignListModalProps) {
|
export function AssignListModal({
|
||||||
|
isOpen,
|
||||||
|
repoId,
|
||||||
|
repoName,
|
||||||
|
patToken,
|
||||||
|
onClose,
|
||||||
|
onRequestToken,
|
||||||
|
}: AssignListModalProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [selectedListIds, setSelectedListIds] = useState<string[]>([]);
|
const [selectedListIds, setSelectedListIds] = useState<string[]>([]);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
@@ -48,15 +58,21 @@ export function AssignListModal({ isOpen, repoId, repoName, onClose }: AssignLis
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
|
if (!patToken.trim()) {
|
||||||
|
setStatus(t("assignList.status.needPat"));
|
||||||
|
onRequestToken?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
setStatus("");
|
setStatus("");
|
||||||
try {
|
try {
|
||||||
|
await syncRepoListAssignmentToGitHub({ token: patToken }, repoId, selectedListIds);
|
||||||
await setRepoListMembership(repoId, selectedListIds);
|
await setRepoListMembership(repoId, selectedListIds);
|
||||||
setStatus(t("assignList.status.saved"));
|
|
||||||
} catch (error) {
|
|
||||||
setStatus((error as Error).message || t("assignList.status.saveFailed"));
|
|
||||||
} finally {
|
|
||||||
setIsSaving(false);
|
setIsSaving(false);
|
||||||
|
onClose();
|
||||||
|
} catch (error) {
|
||||||
|
setIsSaving(false);
|
||||||
|
setStatus((error as Error).message || t("assignList.status.saveFailed"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,331 +0,0 @@
|
|||||||
import { useMemo, useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { runTwoStageClassification } from "../core/llmClassification";
|
|
||||||
import { db } from "../data/db";
|
|
||||||
import { useLiveQuery } from "../data/useLiveQuery";
|
|
||||||
import { normalizeAppLanguage, toPromptLanguage } from "../i18n/language";
|
|
||||||
import { useLlmConfigStore } from "../store/llmConfig";
|
|
||||||
import { usePreferenceStore } from "../store/preferences";
|
|
||||||
|
|
||||||
type LlmClassificationModalProps = {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function LlmClassificationModal({ isOpen, onClose }: LlmClassificationModalProps) {
|
|
||||||
const { t, i18n } = useTranslation();
|
|
||||||
const { config } = useLlmConfigStore();
|
|
||||||
const { preferences } = usePreferenceStore();
|
|
||||||
const [stage, setStage] = useState("idle");
|
|
||||||
const [progress, setProgress] = useState({ current: 0, total: 0 });
|
|
||||||
const [isRunning, setIsRunning] = useState(false);
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const [isTestMode, setIsTestMode] = useState(false);
|
|
||||||
const [strictSingleTag, setStrictSingleTag] = useState(false);
|
|
||||||
const [selectedRunId, setSelectedRunId] = useState<string | null>(null);
|
|
||||||
const [compareMode, setCompareMode] = useState<"existing" | "run">("existing");
|
|
||||||
|
|
||||||
const repos = useLiveQuery(
|
|
||||||
async () => db.repos.toArray(),
|
|
||||||
[],
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const classifications = useLiveQuery(async () => db.classifications.toArray(), [], []);
|
|
||||||
const lists = useLiveQuery(async () => db.lists.toArray(), [], []);
|
|
||||||
const repoLists = useLiveQuery(async () => db.repoLists.toArray(), [], []);
|
|
||||||
|
|
||||||
const runs = useLiveQuery(
|
|
||||||
async () => db.classificationRuns.orderBy("createdAt").reverse().toArray(),
|
|
||||||
[],
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const selectedRunTags = useLiveQuery(
|
|
||||||
async () => {
|
|
||||||
if (!selectedRunId) return [];
|
|
||||||
return db.classificationTags.where("runId").equals(selectedRunId).toArray();
|
|
||||||
},
|
|
||||||
[selectedRunId],
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const previewRows = useMemo(() => {
|
|
||||||
const map = new Map(classifications.map((item) => [item.repoId, item.tags]));
|
|
||||||
return repos.slice(0, 12).map((repo) => ({
|
|
||||||
id: repo.id,
|
|
||||||
name: repo.fullName,
|
|
||||||
tags: map.get(repo.id) ?? [],
|
|
||||||
}));
|
|
||||||
}, [repos, classifications]);
|
|
||||||
|
|
||||||
const existingListMap = useMemo(() => {
|
|
||||||
const listMap = new Map(lists.map((list) => [list.id, list.name]));
|
|
||||||
const out = new Map<string, string[]>();
|
|
||||||
for (const row of repoLists) {
|
|
||||||
const names = row.listIds.map((listId) => listMap.get(listId)).filter(Boolean) as string[];
|
|
||||||
out.set(row.repoId, names);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}, [lists, repoLists]);
|
|
||||||
|
|
||||||
const diffRows = useMemo(() => {
|
|
||||||
if (compareMode === "run" && !selectedRunId) return [];
|
|
||||||
const runMap = new Map(selectedRunTags.map((item) => [item.repoId, item.tags]));
|
|
||||||
const currentMap = new Map(classifications.map((item) => [item.repoId, item.tags]));
|
|
||||||
const rows = repos.map((repo) => {
|
|
||||||
const current = currentMap.get(repo.id) ?? [];
|
|
||||||
const existing = existingListMap.get(repo.id) ?? [];
|
|
||||||
const previous = compareMode === "run" ? runMap.get(repo.id) ?? [] : existing;
|
|
||||||
const changed = previous.join("|") !== current.join("|");
|
|
||||||
return {
|
|
||||||
id: repo.id,
|
|
||||||
name: repo.fullName,
|
|
||||||
previous,
|
|
||||||
current,
|
|
||||||
existing,
|
|
||||||
changed,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return rows.filter((row) => row.changed).slice(0, 30);
|
|
||||||
}, [repos, classifications, selectedRunTags, existingListMap, compareMode, selectedRunId]);
|
|
||||||
|
|
||||||
if (!isOpen) return null;
|
|
||||||
|
|
||||||
const handleRun = async () => {
|
|
||||||
if (!config.apiKey || !config.baseUrl) {
|
|
||||||
setError(t("classification.errors.missingConfig"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (repos.length === 0) {
|
|
||||||
setError(t("classification.errors.noRepos"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const repoBatch = isTestMode ? repos.slice(0, 5) : repos;
|
|
||||||
const promptLanguage = toPromptLanguage(
|
|
||||||
normalizeAppLanguage(i18n.resolvedLanguage || i18n.language)
|
|
||||||
);
|
|
||||||
setError("");
|
|
||||||
setIsRunning(true);
|
|
||||||
setStage("preparing");
|
|
||||||
setProgress({ current: 0, total: repoBatch.length });
|
|
||||||
try {
|
|
||||||
const result = await runTwoStageClassification(
|
|
||||||
config,
|
|
||||||
repoBatch.map((repo) => ({
|
|
||||||
id: repo.id,
|
|
||||||
fullName: repo.fullName,
|
|
||||||
description: repo.description,
|
|
||||||
topics: repo.topics,
|
|
||||||
language: repo.language,
|
|
||||||
readmeExcerpt: repo.readmeExcerpt,
|
|
||||||
existingLists: existingListMap.get(repo.id) ?? [],
|
|
||||||
})),
|
|
||||||
{
|
|
||||||
strictSingleTag,
|
|
||||||
pass1Prompt: config.pass1Prompt,
|
|
||||||
pass1StrictPrompt: config.pass1StrictPrompt,
|
|
||||||
pass2Prompt: config.pass2Prompt,
|
|
||||||
useExistingLists: preferences.useExistingListsForClassification,
|
|
||||||
allowNewTagsWithExistingLists: preferences.allowNewTagsWithExistingLists,
|
|
||||||
language: promptLanguage,
|
|
||||||
},
|
|
||||||
(p) => {
|
|
||||||
setStage(p.stage);
|
|
||||||
setProgress({ current: p.current, total: p.total });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
await db.transaction(
|
|
||||||
"rw",
|
|
||||||
db.classifications,
|
|
||||||
db.tagCompression,
|
|
||||||
db.classificationRuns,
|
|
||||||
db.classificationTags,
|
|
||||||
async () => {
|
|
||||||
await db.classifications.clear();
|
|
||||||
await db.tagCompression.clear();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const rows = Object.entries(result.repoTags).map(([repoId, tags]) => ({
|
|
||||||
repoId,
|
|
||||||
tags,
|
|
||||||
lastRunAt: now,
|
|
||||||
}));
|
|
||||||
await db.classifications.bulkPut(rows);
|
|
||||||
await db.tagCompression.bulkPut(
|
|
||||||
Object.entries(result.tagMap).map(([tag, compressedTag]) => ({
|
|
||||||
tag,
|
|
||||||
compressedTag,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
await db.classificationRuns.add({
|
|
||||||
id: result.runId,
|
|
||||||
createdAt: now,
|
|
||||||
repoCount: repoBatch.length,
|
|
||||||
strictSingleTag,
|
|
||||||
testMode: isTestMode,
|
|
||||||
pass1Prompt: config.pass1Prompt || "",
|
|
||||||
pass1StrictPrompt: config.pass1StrictPrompt || "",
|
|
||||||
pass2Prompt: config.pass2Prompt || "",
|
|
||||||
});
|
|
||||||
await db.classificationTags.bulkPut(
|
|
||||||
Object.entries(result.repoTags).map(([repoId, tags]) => ({
|
|
||||||
id: `${result.runId}:${repoId}`,
|
|
||||||
runId: result.runId,
|
|
||||||
repoId,
|
|
||||||
tags,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
setStage("completed");
|
|
||||||
setSelectedRunId(result.runId);
|
|
||||||
} catch (err) {
|
|
||||||
setError((err as Error).message || t("classification.errors.classificationFailed"));
|
|
||||||
setStage("failed");
|
|
||||||
} finally {
|
|
||||||
setIsRunning(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="drawer" role="dialog" aria-modal="true">
|
|
||||||
<div className="drawer-panel settings">
|
|
||||||
<button className="panel-close" onClick={onClose} aria-label={t("classification.closeAria")}>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
<div className="settings-scroll">
|
|
||||||
<h3>{t("classification.title")}</h3>
|
|
||||||
<p>{t("classification.description")}</p>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("classification.sections.runStatus")}</h4>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.stage")}: {t(`classification.stage.${stage}`, { defaultValue: stage })}
|
|
||||||
</p>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.progress")}: {progress.current}/{progress.total}
|
|
||||||
</p>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={isTestMode}
|
|
||||||
onChange={(event) => setIsTestMode(event.target.checked)}
|
|
||||||
/>
|
|
||||||
{t("classification.toggles.testMode")}
|
|
||||||
</label>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={strictSingleTag}
|
|
||||||
onChange={(event) => setStrictSingleTag(event.target.checked)}
|
|
||||||
/>
|
|
||||||
{t("classification.toggles.strictSingleTag")}
|
|
||||||
</label>
|
|
||||||
{error ? (
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("common.labels.error")}: {error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
<div className="settings-actions">
|
|
||||||
<button className="button primary" onClick={handleRun} disabled={isRunning}>
|
|
||||||
{isRunning ? t("classification.actions.running") : t("classification.actions.run")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("classification.sections.preview")}</h4>
|
|
||||||
{previewRows.length === 0 ? (
|
|
||||||
<p className="helper-text">{t("classification.status.noResults")}</p>
|
|
||||||
) : (
|
|
||||||
<div className="preview-grid">
|
|
||||||
{previewRows.map((row) => (
|
|
||||||
<div key={row.id} className="preview-card">
|
|
||||||
<div className="preview-title">{row.name}</div>
|
|
||||||
<div className="preview-tags">
|
|
||||||
{row.tags.length === 0
|
|
||||||
? t("common.values.unclassified")
|
|
||||||
: row.tags.map((tag) => (
|
|
||||||
<span className="tag" key={tag}>
|
|
||||||
{tag}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("classification.sections.diffView")}</h4>
|
|
||||||
<div className="input-row">
|
|
||||||
<label htmlFor="diff-mode">{t("classification.labels.compareAgainst")}</label>
|
|
||||||
<select
|
|
||||||
id="diff-mode"
|
|
||||||
value={compareMode}
|
|
||||||
onChange={(event) => setCompareMode(event.target.value as "existing" | "run")}
|
|
||||||
>
|
|
||||||
<option value="existing">{t("classification.options.existingStarLists")}</option>
|
|
||||||
<option value="run">{t("classification.options.previousRun")}</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
{compareMode === "run" ? (
|
|
||||||
runs.length === 0 ? (
|
|
||||||
<p className="helper-text">{t("classification.status.noSavedRuns")}</p>
|
|
||||||
) : (
|
|
||||||
<div className="input-row">
|
|
||||||
<label htmlFor="run-select">{t("classification.labels.selectRun")}</label>
|
|
||||||
<select
|
|
||||||
id="run-select"
|
|
||||||
value={selectedRunId ?? ""}
|
|
||||||
onChange={(event) => setSelectedRunId(event.target.value || null)}
|
|
||||||
>
|
|
||||||
<option value="">{t("classification.options.selectRunPlaceholder")}</option>
|
|
||||||
{runs.map((run) => (
|
|
||||||
<option key={run.id} value={run.id}>
|
|
||||||
{new Date(run.createdAt).toLocaleString(i18n.language)} · {run.repoCount} {t("classification.options.reposSuffix")}
|
|
||||||
{run.testMode ? ` · ${t("classification.options.testSuffix")}` : ""}
|
|
||||||
{run.strictSingleTag ? ` · ${t("classification.options.singleSuffix")}` : ""}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
) : null}
|
|
||||||
{compareMode === "run" && selectedRunId && diffRows.length === 0 ? (
|
|
||||||
<p className="helper-text">{t("classification.status.noTagDiff")}</p>
|
|
||||||
) : null}
|
|
||||||
{compareMode === "existing" && diffRows.length === 0 ? (
|
|
||||||
<p className="helper-text">{t("classification.status.noDiffFromExisting")}</p>
|
|
||||||
) : null}
|
|
||||||
{diffRows.length > 0 ? (
|
|
||||||
<div className="diff-grid">
|
|
||||||
{diffRows.map((row) => (
|
|
||||||
<div key={row.id} className="diff-card">
|
|
||||||
<div className="preview-title">{row.name}</div>
|
|
||||||
<div className="diff-row">
|
|
||||||
<span className="diff-label">{t("classification.labels.existing")}</span>
|
|
||||||
<span>{row.existing.join(", ") || t("common.values.none")}</span>
|
|
||||||
</div>
|
|
||||||
{compareMode === "run" ? (
|
|
||||||
<div className="diff-row">
|
|
||||||
<span className="diff-label">{t("classification.labels.previous")}</span>
|
|
||||||
<span>{row.previous.join(", ") || t("common.values.unclassified")}</span>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className="diff-row">
|
|
||||||
<span className="diff-label">{t("classification.labels.current")}</span>
|
|
||||||
<span>{row.current.join(", ") || t("common.values.unclassified")}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
253
src/app/ui/ManageListsModal.tsx
Normal file
253
src/app/ui/ManageListsModal.tsx
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { purgeListFromLocalStores } from "../core/purgeListLocal";
|
||||||
|
import { db } from "../data/db";
|
||||||
|
import { useLiveQuery } from "../data/useLiveQuery";
|
||||||
|
import {
|
||||||
|
createUserList,
|
||||||
|
deleteUserListOnGitHub,
|
||||||
|
updateUserListOnGitHub,
|
||||||
|
} from "../services/githubStarLists";
|
||||||
|
|
||||||
|
type ManageListsModalProps = {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
patToken: string;
|
||||||
|
onRequestToken?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ManageListsModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
patToken,
|
||||||
|
onRequestToken,
|
||||||
|
}: ManageListsModalProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const listRows = useLiveQuery(async () => db.lists.orderBy("name").toArray(), [], []);
|
||||||
|
const repoListRows = useLiveQuery(async () => db.repoLists.toArray(), [], []);
|
||||||
|
|
||||||
|
const countByList = useMemo(() => {
|
||||||
|
const map = new Map<string, number>();
|
||||||
|
for (const row of repoListRows) {
|
||||||
|
for (const id of row.listIds) {
|
||||||
|
map.set(id, (map.get(id) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [repoListRows]);
|
||||||
|
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [isPrivate, setIsPrivate] = useState(false);
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return;
|
||||||
|
setError("");
|
||||||
|
setEditingId(null);
|
||||||
|
setName("");
|
||||||
|
setDescription("");
|
||||||
|
setIsPrivate(false);
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
|
const startEdit = (listId: string) => {
|
||||||
|
const row = listRows.find((l) => l.id === listId);
|
||||||
|
if (!row) return;
|
||||||
|
setEditingId(listId);
|
||||||
|
setName(row.name);
|
||||||
|
setDescription(row.description ?? "");
|
||||||
|
setIsPrivate(row.isPrivate);
|
||||||
|
setError("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelEdit = () => {
|
||||||
|
setEditingId(null);
|
||||||
|
setName("");
|
||||||
|
setDescription("");
|
||||||
|
setIsPrivate(false);
|
||||||
|
setError("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const requirePat = (): boolean => {
|
||||||
|
if (patToken.trim()) return true;
|
||||||
|
setError(t("listManage.needPat"));
|
||||||
|
onRequestToken?.();
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!requirePat()) return;
|
||||||
|
const trimmed = name.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
setError(t("listManage.nameRequired"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
if (editingId) {
|
||||||
|
const updated = await updateUserListOnGitHub(
|
||||||
|
{ token: patToken },
|
||||||
|
editingId,
|
||||||
|
{
|
||||||
|
name: trimmed,
|
||||||
|
description: description.trim(),
|
||||||
|
isPrivate,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
await db.lists.put({
|
||||||
|
id: updated.id,
|
||||||
|
name: updated.name,
|
||||||
|
description: updated.description,
|
||||||
|
isPrivate,
|
||||||
|
});
|
||||||
|
cancelEdit();
|
||||||
|
} else {
|
||||||
|
const ref = await createUserList({ token: patToken }, trimmed, isPrivate, description.trim());
|
||||||
|
await db.lists.put({
|
||||||
|
id: ref.id,
|
||||||
|
name: ref.name,
|
||||||
|
description: description.trim(),
|
||||||
|
isPrivate,
|
||||||
|
});
|
||||||
|
setName("");
|
||||||
|
setDescription("");
|
||||||
|
setIsPrivate(false);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message || t("listManage.saveFailed"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (listId: string, listName: string) => {
|
||||||
|
if (!requirePat()) return;
|
||||||
|
if (
|
||||||
|
!window.confirm(t("listManage.deleteConfirm", { name: listName }))
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await deleteUserListOnGitHub({ token: patToken }, listId);
|
||||||
|
await purgeListFromLocalStores(listId);
|
||||||
|
if (editingId === listId) cancelEdit();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message || t("listManage.deleteFailed"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="drawer" role="dialog" aria-modal="true">
|
||||||
|
<div className="drawer-panel settings">
|
||||||
|
<button className="panel-close" onClick={onClose} aria-label={t("listManage.closeAria")}>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
<div className="settings-scroll">
|
||||||
|
<h3>{t("listManage.title")}</h3>
|
||||||
|
<p>{t("listManage.intro")}</p>
|
||||||
|
|
||||||
|
<div className="settings-section">
|
||||||
|
<h4>{editingId ? t("listManage.editSection") : t("listManage.createSection")}</h4>
|
||||||
|
<div className="input-row">
|
||||||
|
<label htmlFor="list-name">{t("listManage.nameLabel")}</label>
|
||||||
|
<input
|
||||||
|
id="list-name"
|
||||||
|
type="text"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="input-row">
|
||||||
|
<label htmlFor="list-desc">{t("listManage.descriptionLabel")}</label>
|
||||||
|
<textarea
|
||||||
|
id="list-desc"
|
||||||
|
rows={2}
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<label className="checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={isPrivate}
|
||||||
|
onChange={(e) => setIsPrivate(e.target.checked)}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
{t("listManage.isPrivate")}
|
||||||
|
</label>
|
||||||
|
<div className="settings-actions">
|
||||||
|
<button className="button primary" type="button" onClick={handleSubmit} disabled={busy}>
|
||||||
|
{busy
|
||||||
|
? editingId
|
||||||
|
? t("listManage.status.saving")
|
||||||
|
: t("listManage.status.creating")
|
||||||
|
: editingId
|
||||||
|
? t("listManage.save")
|
||||||
|
: t("listManage.create")}
|
||||||
|
</button>
|
||||||
|
{editingId ? (
|
||||||
|
<button className="button" type="button" onClick={cancelEdit} disabled={busy}>
|
||||||
|
{t("listManage.cancelEdit")}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="settings-section">
|
||||||
|
<h4>{t("listManage.existingSection")}</h4>
|
||||||
|
{listRows.length === 0 ? (
|
||||||
|
<p className="helper-text">{t("listManage.empty")}</p>
|
||||||
|
) : (
|
||||||
|
<div className="list-manage-table">
|
||||||
|
<div className="list-manage-head">
|
||||||
|
<span>{t("listManage.nameLabel")}</span>
|
||||||
|
<span>{t("listManage.reposColumn")}</span>
|
||||||
|
<span>{t("listManage.actionsColumn")}</span>
|
||||||
|
</div>
|
||||||
|
{listRows.map((list) => (
|
||||||
|
<div className="list-manage-row" key={list.id}>
|
||||||
|
<span className="list-manage-name" title={list.description || undefined}>
|
||||||
|
{list.name}
|
||||||
|
</span>
|
||||||
|
<span>{countByList.get(list.id) ?? 0}</span>
|
||||||
|
<span className="list-manage-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
onClick={() => startEdit(list.id)}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
{t("listManage.edit")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button"
|
||||||
|
onClick={() => handleDelete(list.id, list.name)}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
{t("listManage.delete")}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error ? <p className="helper-text">{error}</p> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { resolvePrompts, type PromptFieldKey } from "../core/llmPromptResolver";
|
import { type UiLanguagePreference } from "../i18n/language";
|
||||||
import { normalizeAppLanguage, toPromptLanguage, type UiLanguagePreference } from "../i18n/language";
|
|
||||||
import { requestCompletion } from "../services/llmClient";
|
|
||||||
import type { LLMConfig } from "../services/llmClient";
|
|
||||||
import { validatePat } from "../services/githubAuth";
|
import { validatePat } from "../services/githubAuth";
|
||||||
import { useLlmConfigStore } from "../store/llmConfig";
|
|
||||||
import { usePreferenceStore } from "../store/preferences";
|
import { usePreferenceStore } from "../store/preferences";
|
||||||
|
|
||||||
type SettingsModalProps = {
|
type SettingsModalProps = {
|
||||||
@@ -13,161 +9,13 @@ type SettingsModalProps = {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
function getModeDescriptionKey(useExisting: boolean, allowNewTags: boolean): string {
|
|
||||||
if (!useExisting) {
|
|
||||||
return "settings.llm.modeBase";
|
|
||||||
}
|
|
||||||
if (allowNewTags) {
|
|
||||||
return "settings.llm.modeExisting";
|
|
||||||
}
|
|
||||||
return "settings.llm.modeExistingOnly";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
||||||
const { t, i18n } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const {
|
const { preferences, setReadmeOptIn, setPatToken, setUiLanguage } = usePreferenceStore();
|
||||||
preferences,
|
|
||||||
setReadmeOptIn,
|
|
||||||
setPatToken,
|
|
||||||
setUseExistingListsForClassification,
|
|
||||||
setAllowNewTagsWithExistingLists,
|
|
||||||
setRefreshBeforeApply,
|
|
||||||
setUiLanguage,
|
|
||||||
} = usePreferenceStore();
|
|
||||||
const { config, updateConfig, clearConfig } = useLlmConfigStore();
|
|
||||||
const [patTokenInput, setPatTokenInput] = useState(preferences.patToken);
|
const [patTokenInput, setPatTokenInput] = useState(preferences.patToken);
|
||||||
const [patLoginInput, setPatLoginInput] = useState(preferences.viewerLogin);
|
const [patLoginInput, setPatLoginInput] = useState(preferences.viewerLogin);
|
||||||
const [status, setStatus] = useState("");
|
const [status, setStatus] = useState("");
|
||||||
const [testStatus, setTestStatus] = useState("");
|
|
||||||
const [isSavingPat, setIsSavingPat] = useState(false);
|
const [isSavingPat, setIsSavingPat] = useState(false);
|
||||||
const [isTesting, setIsTesting] = useState(false);
|
|
||||||
|
|
||||||
const promptLanguage = toPromptLanguage(normalizeAppLanguage(i18n.resolvedLanguage || i18n.language));
|
|
||||||
|
|
||||||
const promptFieldMeta: Record<PromptFieldKey, { label: string; rows: number }> = useMemo(
|
|
||||||
() => ({
|
|
||||||
pass1Prompt: { label: t("settings.llm.promptLabels.pass1Prompt"), rows: 3 },
|
|
||||||
pass1StrictPrompt: { label: t("settings.llm.promptLabels.pass1StrictPrompt"), rows: 2 },
|
|
||||||
pass2Prompt: { label: t("settings.llm.promptLabels.pass2Prompt"), rows: 3 },
|
|
||||||
pass1PromptWithExisting: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1PromptWithExisting"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
pass1PromptNoNewWithExisting: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1PromptNoNewWithExisting"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
pass1StrictPromptWithExisting: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1StrictPromptWithExisting"),
|
|
||||||
rows: 2,
|
|
||||||
},
|
|
||||||
pass1StrictNoNewWithExisting: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1StrictNoNewWithExisting"),
|
|
||||||
rows: 2,
|
|
||||||
},
|
|
||||||
pass2PromptWithExisting: {
|
|
||||||
label: t("settings.llm.promptLabels.pass2PromptWithExisting"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
pass1PromptZh: { label: t("settings.llm.promptLabels.pass1PromptZh"), rows: 3 },
|
|
||||||
pass1StrictPromptZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1StrictPromptZh"),
|
|
||||||
rows: 2,
|
|
||||||
},
|
|
||||||
pass2PromptZh: { label: t("settings.llm.promptLabels.pass2PromptZh"), rows: 3 },
|
|
||||||
pass1PromptWithExistingZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1PromptWithExistingZh"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
pass1PromptNoNewWithExistingZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1PromptNoNewWithExistingZh"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
pass1StrictPromptWithExistingZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1StrictPromptWithExistingZh"),
|
|
||||||
rows: 2,
|
|
||||||
},
|
|
||||||
pass1StrictNoNewWithExistingZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass1StrictNoNewWithExistingZh"),
|
|
||||||
rows: 2,
|
|
||||||
},
|
|
||||||
pass2PromptWithExistingZh: {
|
|
||||||
label: t("settings.llm.promptLabels.pass2PromptWithExistingZh"),
|
|
||||||
rows: 3,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
[t]
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolvedPrompts = useMemo(
|
|
||||||
() =>
|
|
||||||
resolvePrompts(config, {
|
|
||||||
strictSingleTag: false,
|
|
||||||
useExistingLists: preferences.useExistingListsForClassification,
|
|
||||||
allowNewTagsWithExistingLists: preferences.allowNewTagsWithExistingLists,
|
|
||||||
language: promptLanguage,
|
|
||||||
}),
|
|
||||||
[
|
|
||||||
config,
|
|
||||||
preferences.useExistingListsForClassification,
|
|
||||||
preferences.allowNewTagsWithExistingLists,
|
|
||||||
promptLanguage,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
const activePromptFields = useMemo(
|
|
||||||
() => [
|
|
||||||
{
|
|
||||||
id: "llm-pass1-active",
|
|
||||||
key: resolvedPrompts.activeKeys.pass1,
|
|
||||||
label: t("settings.llm.activePass1"),
|
|
||||||
rows: promptFieldMeta[resolvedPrompts.activeKeys.pass1].rows,
|
|
||||||
value: resolvedPrompts.pass1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "llm-pass1-strict-active",
|
|
||||||
key: resolvedPrompts.activeKeys.pass1Strict,
|
|
||||||
label: t("settings.llm.activePass1Strict"),
|
|
||||||
rows: promptFieldMeta[resolvedPrompts.activeKeys.pass1Strict].rows,
|
|
||||||
value: resolvedPrompts.pass1Strict,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "llm-pass2-active",
|
|
||||||
key: resolvedPrompts.activeKeys.pass2,
|
|
||||||
label: t("settings.llm.activePass2"),
|
|
||||||
rows: promptFieldMeta[resolvedPrompts.activeKeys.pass2].rows,
|
|
||||||
value: resolvedPrompts.pass2,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[resolvedPrompts, promptFieldMeta, t]
|
|
||||||
);
|
|
||||||
|
|
||||||
const inactivePromptFields = useMemo(
|
|
||||||
() =>
|
|
||||||
resolvedPrompts.inactiveKeys.map((key) => ({
|
|
||||||
key,
|
|
||||||
id: `llm-${key}`,
|
|
||||||
label: promptFieldMeta[key].label,
|
|
||||||
rows: promptFieldMeta[key].rows,
|
|
||||||
value: config[key] || "",
|
|
||||||
})),
|
|
||||||
[config, promptFieldMeta, resolvedPrompts]
|
|
||||||
);
|
|
||||||
|
|
||||||
const modeDescription = useMemo(
|
|
||||||
() =>
|
|
||||||
t(
|
|
||||||
getModeDescriptionKey(
|
|
||||||
preferences.useExistingListsForClassification,
|
|
||||||
preferences.allowNewTagsWithExistingLists
|
|
||||||
)
|
|
||||||
),
|
|
||||||
[
|
|
||||||
preferences.useExistingListsForClassification,
|
|
||||||
preferences.allowNewTagsWithExistingLists,
|
|
||||||
t,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) return;
|
if (!isOpen) return;
|
||||||
@@ -177,39 +25,6 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
|||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
const handleTest = async () => {
|
|
||||||
if (!config.baseUrl.trim()) {
|
|
||||||
setTestStatus(t("settings.llm.missingBaseUrl"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!config.apiKey.trim()) {
|
|
||||||
setTestStatus(t("settings.llm.missingApiKey"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setIsTesting(true);
|
|
||||||
setTestStatus(t("settings.llm.testing"));
|
|
||||||
const startedAt = performance.now();
|
|
||||||
try {
|
|
||||||
const response = await requestCompletion(
|
|
||||||
config,
|
|
||||||
[
|
|
||||||
{ role: "system", content: "You are a helpful assistant." },
|
|
||||||
{ role: "user", content: "Reply with OK" },
|
|
||||||
]
|
|
||||||
);
|
|
||||||
const elapsed = Math.round(performance.now() - startedAt);
|
|
||||||
setTestStatus(t("settings.llm.testOk", { elapsed, response }));
|
|
||||||
} catch (error) {
|
|
||||||
const elapsed = Math.round(performance.now() - startedAt);
|
|
||||||
const err = error as Error;
|
|
||||||
const name = err?.name || "Error";
|
|
||||||
const message = err?.message || "Test failed";
|
|
||||||
setTestStatus(t("settings.llm.testError", { elapsed, name, message }));
|
|
||||||
} finally {
|
|
||||||
setIsTesting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSavePat = async () => {
|
const handleSavePat = async () => {
|
||||||
const token = patTokenInput.trim();
|
const token = patTokenInput.trim();
|
||||||
if (!token) {
|
if (!token) {
|
||||||
@@ -233,15 +48,6 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const updatePromptField = (key: PromptFieldKey, value: string) => {
|
|
||||||
updateConfig({ [key]: value } as Partial<LLMConfig>);
|
|
||||||
};
|
|
||||||
|
|
||||||
const promptLanguageLabel =
|
|
||||||
promptLanguage === "zh"
|
|
||||||
? t("settings.language.promptLanguageChinese")
|
|
||||||
: t("settings.language.promptLanguageEnglish");
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="drawer" role="dialog" aria-modal="true">
|
<div className="drawer" role="dialog" aria-modal="true">
|
||||||
<div className="drawer-panel settings">
|
<div className="drawer-panel settings">
|
||||||
@@ -308,128 +114,6 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("settings.sections.llmConfiguration")}</h4>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={preferences.useExistingListsForClassification}
|
|
||||||
onChange={(event) =>
|
|
||||||
setUseExistingListsForClassification(event.target.checked)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{t("settings.llm.useExistingLists")}
|
|
||||||
</label>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={preferences.allowNewTagsWithExistingLists}
|
|
||||||
onChange={(event) =>
|
|
||||||
setAllowNewTagsWithExistingLists(event.target.checked)
|
|
||||||
}
|
|
||||||
disabled={!preferences.useExistingListsForClassification}
|
|
||||||
/>
|
|
||||||
{t("settings.llm.allowNewTags")}
|
|
||||||
</label>
|
|
||||||
<p className="helper-text">
|
|
||||||
{t("settings.language.promptLanguage", { language: promptLanguageLabel })}
|
|
||||||
</p>
|
|
||||||
<div className="prompt-mode-card">
|
|
||||||
<p className="prompt-mode-title">{t("settings.llm.currentMode")}</p>
|
|
||||||
<p className="prompt-mode-value">{modeDescription}</p>
|
|
||||||
</div>
|
|
||||||
<div className="input-row">
|
|
||||||
<label htmlFor="llm-base">{t("settings.llm.baseUrl")}</label>
|
|
||||||
<input
|
|
||||||
id="llm-base"
|
|
||||||
type="text"
|
|
||||||
value={config.baseUrl}
|
|
||||||
onChange={(event) => updateConfig({ baseUrl: event.target.value })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="input-row">
|
|
||||||
<label htmlFor="llm-key">{t("settings.llm.apiKey")}</label>
|
|
||||||
<input
|
|
||||||
id="llm-key"
|
|
||||||
type="password"
|
|
||||||
value={config.apiKey}
|
|
||||||
onChange={(event) => updateConfig({ apiKey: event.target.value })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="input-row">
|
|
||||||
<label htmlFor="llm-model">{t("settings.llm.model")}</label>
|
|
||||||
<input
|
|
||||||
id="llm-model"
|
|
||||||
type="text"
|
|
||||||
value={config.model}
|
|
||||||
onChange={(event) => updateConfig({ model: event.target.value })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="input-row inline">
|
|
||||||
<div>
|
|
||||||
<label htmlFor="llm-temp">{t("settings.llm.temperature")}</label>
|
|
||||||
<input
|
|
||||||
id="llm-temp"
|
|
||||||
type="number"
|
|
||||||
step="0.1"
|
|
||||||
value={config.temperature}
|
|
||||||
onChange={(event) => updateConfig({ temperature: Number(event.target.value) })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label htmlFor="llm-max">{t("settings.llm.maxTokens")}</label>
|
|
||||||
<input
|
|
||||||
id="llm-max"
|
|
||||||
type="number"
|
|
||||||
step="1"
|
|
||||||
value={config.maxTokens}
|
|
||||||
onChange={(event) => updateConfig({ maxTokens: Number(event.target.value) })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{activePromptFields.map((field) => (
|
|
||||||
<div className="input-row" key={field.id}>
|
|
||||||
<label htmlFor={field.id}>{field.label}</label>
|
|
||||||
<textarea
|
|
||||||
id={field.id}
|
|
||||||
rows={field.rows}
|
|
||||||
value={field.value}
|
|
||||||
onChange={(event) => updatePromptField(field.key, event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<details className="advanced-prompts">
|
|
||||||
<summary>{t("settings.llm.advancedSettings", { count: inactivePromptFields.length })}</summary>
|
|
||||||
<p className="helper-text">{t("settings.llm.advancedHelp")}</p>
|
|
||||||
{inactivePromptFields.map((field) => (
|
|
||||||
<div className="input-row" key={field.id}>
|
|
||||||
<label htmlFor={field.id}>{field.label}</label>
|
|
||||||
<textarea
|
|
||||||
id={field.id}
|
|
||||||
rows={field.rows}
|
|
||||||
value={field.value}
|
|
||||||
onChange={(event) => updatePromptField(field.key, event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</details>
|
|
||||||
<div className="settings-actions">
|
|
||||||
<button className="button" onClick={handleTest} disabled={isTesting}>
|
|
||||||
{isTesting ? t("settings.llm.testing") : t("settings.llm.testLlm")}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="button"
|
|
||||||
onClick={() => {
|
|
||||||
clearConfig();
|
|
||||||
setTestStatus(t("settings.llm.cleared"));
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t("settings.llm.resetLlm")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{testStatus ? <p className="helper-text">{testStatus}</p> : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
<div className="settings-section">
|
||||||
<h4>{t("settings.sections.readmeFetching")}</h4>
|
<h4>{t("settings.sections.readmeFetching")}</h4>
|
||||||
<label className="checkbox">
|
<label className="checkbox">
|
||||||
@@ -442,19 +126,6 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="settings-section">
|
|
||||||
<h4>{t("settings.sections.writeback")}</h4>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={preferences.refreshBeforeApply}
|
|
||||||
onChange={(event) => setRefreshBeforeApply(event.target.checked)}
|
|
||||||
/>
|
|
||||||
{t("settings.writeback.refreshBeforeApply")}
|
|
||||||
</label>
|
|
||||||
<p className="helper-text">{t("settings.writeback.refreshHelp")}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="settings-section">
|
<div className="settings-section">
|
||||||
<h4>{t("settings.sections.localCache")}</h4>
|
<h4>{t("settings.sections.localCache")}</h4>
|
||||||
<p className="helper-text">{t("settings.cache.help")}</p>
|
<p className="helper-text">{t("settings.cache.help")}</p>
|
||||||
|
|||||||
Reference in New Issue
Block a user