LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: automatic update check via GitHub Releases API
nash_su98ac9e9a935b
diff --git a/src/App.tsx b/src/App.tsxindex 971909ce..7069e1c7 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -29,6 +29,57 @@ function App() {startClipWatcher()}, [])+ // Background update check — hydrate persisted user preferences, then+ // hit GitHub at most once every UPDATE_CHECK_CACHE_MS. Runs 5 s after+ // mount so it doesn't contend with startup work. Silent on failure;+ // the UI in Settings → About surfaces the result.+ useEffect(() => {+ let cancelled = false+ const timer = setTimeout(async () => {+ if (cancelled) return+ try {+ const { loadUpdateCheckState, saveUpdateCheckState } = await import(+ "@/lib/project-store"+ )+ const { useUpdateStore } = await import("@/stores/update-store")+ const { checkForUpdates, UPDATE_CHECK_CACHE_MS } = await import(+ "@/lib/update-check"+ )++ const persisted = await loadUpdateCheckState()+ if (persisted) useUpdateStore.getState().hydrate(persisted)++ const state = useUpdateStore.getState()+ if (!state.enabled) return++ const now = Date.now()+ const fresh =+ state.lastCheckedAt !== null &&+ now - state.lastCheckedAt < UPDATE_CHECK_CACHE_MS+ if (fresh) return++ useUpdateStore.getState().setChecking(true)+ const result = await checkForUpdates({+ currentVersion: __APP_VERSION__,+ repo: "nashsu/llm_wiki",+ })+ if (cancelled) return+ useUpdateStore.getState().setResult(result, Date.now())+ await saveUpdateCheckState({+ enabled: useUpdateStore.getState().enabled,+ lastCheckedAt: Date.now(),+ dismissedVersion: useUpdateStore.getState().dismissedVersion,+ })+ } catch {+ // Silent — Settings → About lets the user retry manually.+ }+ }, 5000)+ return () => {+ cancelled = true+ clearTimeout(timer)+ }+ }, [])+// Auto-open last project on startupuseEffect(() => {async function init() {diff --git a/src/components/layout/icon-sidebar.tsx b/src/components/layout/icon-sidebar.tsxindex 87a9b1d2..eb2e9652 100644--- a/src/components/layout/icon-sidebar.tsx+++ b/src/components/layout/icon-sidebar.tsx@@ -6,6 +6,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/compimport { useWikiStore } from "@/stores/wiki-store"import { useReviewStore } from "@/stores/review-store"import { useResearchStore } from "@/stores/research-store"+import { useUpdateStore, shouldShowUpdateBanner } from "@/stores/update-store"import { useTranslation } from "react-i18next"import logoImg from "@/assets/logo.jpg"import type { WikiState } from "@/stores/wiki-store"@@ -33,6 +34,7 @@ export function IconSidebar({ onSwitchProject }: IconSidebarProps) {const researchPanelOpen = useResearchStore((s) => s.panelOpen)const researchActiveCount = useResearchStore((s) => s.tasks.filter((t) => t.status !== "done" && t.status !== "error").length)const toggleResearchPanel = useResearchStore((s) => s.setPanelOpen)+ const updateBannerVisible = useUpdateStore((s) => shouldShowUpdateBanner(s))// Daemon health checkconst [daemonStatus, setDaemonStatus] = useState<string>("starting")@@ -131,15 +133,27 @@ export function IconSidebar({ onSwitchProject }: IconSidebarProps) {<Tooltip><TooltipTriggeronClick={() => setActiveView("settings")}- className={`flex h-10 w-10 items-center justify-center rounded-md transition-colors ${+ className={`relative flex h-10 w-10 items-center justify-center rounded-md transition-colors ${activeView === "settings"? "bg-accent text-accent-foreground": "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"}`}><Settings className="h-5 w-5" />+ {updateBannerVisible && (+ // Small dot at the top-right of the Settings icon when+ // a new release is available; dismissed versions clear+ // it automatically via shouldShowUpdateBanner.+ <span+ className="absolute right-1 top-1 h-2 w-2 rounded-full bg-primary ring-2 ring-muted/50"+ title="有可用更新"+ />+ )}</TooltipTrigger>- <TooltipContent side="right">{t("nav.settings")}</TooltipContent>+ <TooltipContent side="right">+ {t("nav.settings")}+ {updateBannerVisible ? " · 有更新" : ""}+ </TooltipContent></Tooltip><Tooltip><TooltipTriggerdiff --git a/src/components/settings/sections/about-section.tsx b/src/components/settings/sections/about-section.tsxindex e30005e5..9cb0ca6b 100644--- a/src/components/settings/sections/about-section.tsx+++ b/src/components/settings/sections/about-section.tsx@@ -1,8 +1,14 @@-import { useEffect, useState } from "react"+import { useEffect, useState, useCallback } from "react"+import { Download, RefreshCw, CheckCircle2, AlertCircle, Sparkles } from "lucide-react"import { clipServerStatus } from "@/commands/fs"+import { Button } from "@/components/ui/button"+import { useUpdateStore, shouldShowUpdateBanner } from "@/stores/update-store"+import { checkForUpdates } from "@/lib/update-check"+import { saveUpdateCheckState } from "@/lib/project-store"export function AboutSection() {const [clipStatus, setClipStatus] = useState<string>("...")+ const updateStore = useUpdateStore()useEffect(() => {let alive = true@@ -18,11 +24,56 @@ export function AboutSection() {}}, [])+ const handleCheckNow = useCallback(async () => {+ useUpdateStore.getState().setChecking(true)+ const result = await checkForUpdates({+ currentVersion: __APP_VERSION__,+ repo: "nashsu/llm_wiki",+ })+ const now = Date.now()+ useUpdateStore.getState().setResult(result, now)+ // On a manual check, wipe any prior "dismissed" memo so that if+ // the user re-clicks they see the banner again for the same+ // version — a manual check implies "I want to see this now".+ useUpdateStore.getState().setDismissed(null)+ await saveUpdateCheckState({+ enabled: useUpdateStore.getState().enabled,+ lastCheckedAt: now,+ dismissedVersion: null,+ })+ }, [])++ const handleDismiss = useCallback(async () => {+ const result = useUpdateStore.getState().lastResult+ if (result?.kind !== "available") return+ useUpdateStore.getState().setDismissed(result.remote)+ await saveUpdateCheckState({+ enabled: useUpdateStore.getState().enabled,+ lastCheckedAt: useUpdateStore.getState().lastCheckedAt ?? Date.now(),+ dismissedVersion: result.remote,+ })+ }, [])++ const handleToggleAutoCheck = useCallback(async () => {+ const next = !useUpdateStore.getState().enabled+ useUpdateStore.getState().setEnabled(next)+ await saveUpdateCheckState({+ enabled: next,+ lastCheckedAt: useUpdateStore.getState().lastCheckedAt,+ dismissedVersion: useUpdateStore.getState().dismissedVersion,+ })+ }, [])+const rows: Array<{ label: string; value: string; mono?: boolean }> = [{ label: "版本", value: `v${__APP_VERSION__}`, mono: true },{ label: "Clip Server", value: `${clipStatus} @ 127.0.0.1:19827`, mono: true },]+ const showBanner = shouldShowUpdateBanner(updateStore)+ const lastCheckedLabel = updateStore.lastCheckedAt+ ? formatRelative(updateStore.lastCheckedAt)+ : "从未"+return (<div className="space-y-6"><div>@@ -41,6 +92,64 @@ export function AboutSection() {))}</div>+ {/* ── Update check card ──────────────────────────────────── */}+ <div className="space-y-3 rounded-md border p-4">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="text-sm font-medium">更新检查</div>+ <div className="mt-0.5 text-xs text-muted-foreground">+ 上次检查:{lastCheckedLabel}+ </div>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={handleCheckNow}+ disabled={updateStore.checking}+ className="shrink-0 gap-1.5"+ >+ <RefreshCw+ className={`h-3.5 w-3.5 ${updateStore.checking ? "animate-spin" : ""}`}+ />+ {updateStore.checking ? "检查中…" : "立即检查"}+ </Button>+ </div>++ {showBanner && updateStore.lastResult?.kind === "available" && (+ <UpdateAvailableBanner+ remote={updateStore.lastResult.remote}+ releaseUrl={updateStore.lastResult.release.html_url}+ releaseName={updateStore.lastResult.release.name}+ releaseBody={updateStore.lastResult.release.body}+ onDismiss={handleDismiss}+ />+ )}++ {!showBanner && updateStore.lastResult?.kind === "up-to-date" && (+ <div className="flex items-center gap-2 rounded border border-emerald-500/30 bg-emerald-500/5 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-400">+ <CheckCircle2 className="h-4 w-4 shrink-0" />+ 已是最新版本(v{updateStore.lastResult.local})。+ </div>+ )}++ {updateStore.lastResult?.kind === "error" && (+ <div className="flex items-start gap-2 rounded border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-700 dark:text-amber-400">+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />+ <span>{updateStore.lastResult.message}</span>+ </div>+ )}++ <label className="flex items-center gap-2 text-xs text-muted-foreground">+ <input+ type="checkbox"+ checked={updateStore.enabled}+ onChange={handleToggleAutoCheck}+ className="h-3.5 w-3.5"+ />+ 应用启动时自动检查更新(每 6 小时最多一次)+ </label>+ </div>+<div className="rounded-md border p-4 text-sm"><div className="font-medium">LLM Wiki</div><p className="mt-1 text-xs text-muted-foreground">@@ -59,3 +168,68 @@ export function AboutSection() {</div>)}++interface UpdateAvailableBannerProps {+ remote: string+ releaseUrl: string+ releaseName: string+ releaseBody: string+ onDismiss: () => void+}++function UpdateAvailableBanner({+ remote,+ releaseUrl,+ releaseName,+ releaseBody,+ onDismiss,+}: UpdateAvailableBannerProps) {+ const handleOpen = () => {+ // window.open with target=_blank delegates to the system browser+ // in Tauri via the opener plugin registered in src-tauri/src/lib.rs.+ // Works identically in a regular browser during dev mode.+ window.open(releaseUrl, "_blank", "noopener,noreferrer")+ }++ const preview = releaseBody.slice(0, 400)+ const truncated = releaseBody.length > preview.length++ return (+ <div className="rounded border border-primary/40 bg-primary/5 p-3">+ <div className="flex items-center gap-2 text-sm font-medium text-primary">+ <Sparkles className="h-4 w-4 shrink-0" />+ 有可用更新:v{remote.replace(/^v/, "")}+ </div>+ {releaseName && releaseName !== `v${remote.replace(/^v/, "")}` && (+ <div className="mt-1 text-xs text-muted-foreground">{releaseName}</div>+ )}+ {preview.trim().length > 0 && (+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-background/60 px-2 py-1.5 text-[11px] leading-relaxed text-foreground/80">+ {preview}+ {truncated && " …"}+ </pre>+ )}+ <div className="mt-3 flex items-center gap-2">+ <Button size="sm" onClick={handleOpen} className="gap-1.5">+ <Download className="h-3.5 w-3.5" />+ 打开下载页+ </Button>+ <Button size="sm" variant="ghost" onClick={onDismiss}>+ 稍后+ </Button>+ </div>+ </div>+ )+}++function formatRelative(timestamp: number): string {+ const delta = Date.now() - timestamp+ if (delta < 0) return "just now"+ const mins = Math.floor(delta / 60_000)+ if (mins < 1) return "刚刚"+ if (mins < 60) return `${mins} 分钟前`+ const hours = Math.floor(mins / 60)+ if (hours < 24) return `${hours} 小时前`+ const days = Math.floor(hours / 24)+ return `${days} 天前`+}diff --git a/src/lib/project-store.ts b/src/lib/project-store.tsindex 4672990f..e0f268a3 100644--- a/src/lib/project-store.ts+++ b/src/lib/project-store.ts@@ -128,3 +128,32 @@ export async function loadOutputLanguage(): Promise<OutputLanguage | null> {const store = await getStore()return (await store.get<OutputLanguage>(OUTPUT_LANGUAGE_KEY)) ?? null}++// ── Update-check persistence ──────────────────────────────────────────────+// Small slice of state the UI-layer update store hydrates from on boot.+// Only fields that should persist across launches: the user's "enable+// auto-check" toggle, the timestamp we last checked (so the 6-hour cache+// survives restarts), and the version the user explicitly dismissed+// (so we don't re-nag on every restart until a newer version is out).++const UPDATE_CHECK_STATE_KEY = "updateCheckState"++export interface PersistedUpdateCheckState {+ enabled: boolean+ lastCheckedAt: number | null+ dismissedVersion: string | null+}++export async function saveUpdateCheckState(+ state: PersistedUpdateCheckState,+): Promise<void> {+ const store = await getStore()+ await store.set(UPDATE_CHECK_STATE_KEY, state)+}++export async function loadUpdateCheckState(): Promise<PersistedUpdateCheckState | null> {+ const store = await getStore()+ return (+ (await store.get<PersistedUpdateCheckState>(UPDATE_CHECK_STATE_KEY)) ?? null+ )+}diff --git a/src/lib/update-check.test.ts b/src/lib/update-check.test.tsnew file mode 100644index 00000000..95f0b098--- /dev/null+++ b/src/lib/update-check.test.ts@@ -0,0 +1,69 @@+/**+ * Tests for the update-checker's pure logic. The network call itself+ * (`fetchLatestRelease`) is covered via `checkForUpdates` mocking the+ * fetch layer — we don't exercise it against real GitHub in CI.+ */+import { describe, it, expect } from "vitest"+import { isNewer } from "./update-check"++describe("isNewer — semver comparison", () => {+ it("remote > local on patch", () => {+ expect(isNewer("0.3.10", "0.3.9")).toBe(true)+ })++ it("remote > local on minor", () => {+ expect(isNewer("0.4.0", "0.3.99")).toBe(true)+ })++ it("remote > local on major", () => {+ expect(isNewer("1.0.0", "0.99.99")).toBe(true)+ })++ it("remote equal to local is NOT newer", () => {+ expect(isNewer("0.3.9", "0.3.9")).toBe(false)+ })++ it("remote < local is NOT newer (user on a nightly build)", () => {+ expect(isNewer("0.3.8", "0.3.9")).toBe(false)+ })++ it("tolerates leading 'v' on remote tag", () => {+ expect(isNewer("v0.3.10", "0.3.9")).toBe(true)+ })++ it("tolerates leading 'v' on local too", () => {+ expect(isNewer("v0.4.0", "v0.3.9")).toBe(true)+ })++ it("handles missing components as zero", () => {+ // Weirdly short tag like "v1" — treat as 1.0.0.+ expect(isNewer("v1", "0.3.9")).toBe(true)+ expect(isNewer("v1.0", "1.0.0")).toBe(false)+ })++ it("does not false-positive on lexicographic comparison", () => {+ // "0.3.9" comes AFTER "0.3.10" alphabetically — the check must be+ // numeric, not string-based. If this ever regressed to .localeCompare+ // or similar, users on 0.3.10 would be told there's a newer 0.3.9.+ expect(isNewer("0.3.9", "0.3.10")).toBe(false)+ expect(isNewer("0.3.10", "0.3.9")).toBe(true)+ })++ it("double-digit minor/patch compare correctly", () => {+ expect(isNewer("0.10.0", "0.9.99")).toBe(true)+ expect(isNewer("0.10.5", "0.10.4")).toBe(true)+ expect(isNewer("0.10.4", "0.10.5")).toBe(false)+ })++ it("non-numeric garbage in a slot collapses to 0 (can't sneak through an upgrade)", () => {+ // Defense against a malformed remote tag like "v0.3.foo" — don't+ // treat "foo" as infinity and tell the user to upgrade to nothing.+ expect(isNewer("v0.3.foo", "0.3.9")).toBe(false)+ expect(isNewer("v0.foo.0", "0.3.0")).toBe(false)+ })++ it("empty string treated as 0.0.0", () => {+ expect(isNewer("", "0.3.9")).toBe(false)+ expect(isNewer("0.3.9", "")).toBe(true)+ })+})diff --git a/src/lib/update-check.ts b/src/lib/update-check.tsnew file mode 100644index 00000000..7e65d51e--- /dev/null+++ b/src/lib/update-check.ts@@ -0,0 +1,142 @@+/**+ * Lightweight update checker: hits the GitHub Releases API for the+ * repo's `latest` release, compares against the app's build-time+ * version, and returns a status the UI can surface. We intentionally+ * don't download or install — the user gets a "new version available"+ * hint in Settings → About and a button that opens the GitHub+ * release page in their browser. See `update-store.ts` for the UI+ * state layer and `about-section.tsx` for the surfacing.+ *+ * Why not tauri-plugin-updater: a real auto-install flow needs Tauri-+ * signed release manifests plus a paid Windows code-signing cert to+ * avoid SmartScreen warnings. Worth doing later, but for a free OSS+ * distribution a polite "here's the new version, click to download"+ * covers 95% of the value.+ */++import { getHttpFetch, isFetchNetworkError } from "./tauri-fetch"++/** The subset of the GitHub release API response we care about. */+export interface GithubRelease {+ tag_name: string // e.g. "v0.3.10"+ name: string // display title+ body: string // markdown release notes+ html_url: string // browser URL for the release page+ published_at: string // ISO timestamp+}++export type UpdateStatus =+ | { kind: "available"; local: string; remote: string; release: GithubRelease }+ | { kind: "up-to-date"; local: string; remote: string }+ | { kind: "error"; local: string; message: string }++/**+ * Strict semver-ish comparison of two "MAJOR.MINOR.PATCH" strings.+ * We don't use pre-release tags or build metadata in this project, so+ * a plain three-component numeric compare is enough and avoids pulling+ * in the `semver` npm package just for this.+ *+ * Returns true iff `remote` is strictly greater than `local`. A leading+ * `v` on either side is tolerated; anything non-numeric in a slot+ * defaults to 0 (so a weirdly-shaped remote tag can't trigger a false+ * upgrade).+ */+export function isNewer(remote: string, local: string): boolean {+ const parse = (s: string): [number, number, number] => {+ const [a = 0, b = 0, c = 0] = s+ .replace(/^v/, "")+ .split(".")+ .map((n) => {+ const v = parseInt(n, 10)+ return Number.isFinite(v) ? v : 0+ })+ return [a, b, c]+ }+ const [ra, rb, rc] = parse(remote)+ const [la, lb, lc] = parse(local)+ if (ra !== la) return ra > la+ if (rb !== lb) return rb > lb+ return rc > lc+}++/**+ * Fetch the latest release from a GitHub repo. Returns null on any+ * failure (network / rate-limit / 404 when no release exists yet).+ * Doesn't throw — the caller's job is to render the failure as an+ * "error" status, not to log it or alert the user.+ *+ * Routes through the Tauri HTTP plugin so it stays consistent with the+ * rest of the app's third-party traffic and doesn't depend on the+ * webview's CORS policy for api.github.com (which is permissive today+ * but might not always be).+ */+export async function fetchLatestRelease(+ repo: string,+): Promise<GithubRelease | null> {+ const url = `https://api.github.com/repos/${repo}/releases/latest`+ try {+ const httpFetch = await getHttpFetch()+ const resp = await httpFetch(url, {+ method: "GET",+ headers: {+ Accept: "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ },+ })+ if (!resp.ok) return null+ const data = await resp.json()+ // Duck-type the response shape — GitHub occasionally adds fields+ // but the ones below have been stable since the API's v3 days.+ if (+ typeof data?.tag_name === "string" &&+ typeof data?.html_url === "string"+ ) {+ return {+ tag_name: data.tag_name,+ name: typeof data.name === "string" ? data.name : data.tag_name,+ body: typeof data.body === "string" ? data.body : "",+ html_url: data.html_url,+ published_at:+ typeof data.published_at === "string" ? data.published_at : "",+ }+ }+ return null+ } catch (err) {+ if (isFetchNetworkError(err)) return null+ return null+ }+}++/**+ * End-to-end check: fetch + compare + package into a renderable+ * status. Callers pass in `currentVersion` from the build-time define+ * and `repo` from the project config — the module itself stays free+ * of environment coupling so it's easy to unit-test.+ */+export async function checkForUpdates(opts: {+ currentVersion: string+ repo: string+}): Promise<UpdateStatus> {+ const { currentVersion, repo } = opts+ const release = await fetchLatestRelease(repo)+ if (!release) {+ return {+ kind: "error",+ local: currentVersion,+ message: "Could not reach GitHub Releases API.",+ }+ }+ const remote = release.tag_name+ if (isNewer(remote, currentVersion)) {+ return {+ kind: "available",+ local: currentVersion,+ remote,+ release,+ }+ }+ return { kind: "up-to-date", local: currentVersion, remote }+}++/** Cache duration: don't re-hit the API if we checked more recently than this. */+export const UPDATE_CHECK_CACHE_MS = 6 * 60 * 60 * 1000 // 6 hoursdiff --git a/src/stores/update-store.ts b/src/stores/update-store.tsnew file mode 100644index 00000000..bc2627ca--- /dev/null+++ b/src/stores/update-store.ts@@ -0,0 +1,62 @@+import { create } from "zustand"+import type { UpdateStatus } from "@/lib/update-check"++/**+ * UI-side state for the update-check feature. Persistence (user-level+ * "auto check enabled" flag, "dismissed this version" memo, and last-+ * checked timestamp) lives in plugin-store via src/lib/project-store.ts.+ * The store mirrors the persisted values at runtime and lets the UI+ * subscribe to them without awaiting the store read every render.+ */+export interface UpdateStoreState {+ /** True while a check-for-updates HTTP call is in flight. */+ checking: boolean+ /** The most recent result (null if never checked this session). */+ lastResult: UpdateStatus | null+ /** Unix ms timestamp of the last successful (or attempted) check. */+ lastCheckedAt: number | null+ /**+ * Remote version the user clicked "later" on. If the remote version+ * later becomes something different, the "available" UI returns.+ * null = no dismissal active.+ */+ dismissedVersion: string | null+ /** User preference: run the automatic check on app startup. */+ enabled: boolean++ setChecking: (b: boolean) => void+ setResult: (result: UpdateStatus, at: number) => void+ setDismissed: (version: string | null) => void+ setEnabled: (b: boolean) => void+ hydrate: (partial: Partial<UpdateStoreState>) => void+}++export const useUpdateStore = create<UpdateStoreState>((set) => ({+ checking: false,+ lastResult: null,+ lastCheckedAt: null,+ dismissedVersion: null,+ enabled: true,++ setChecking: (checking) => set({ checking }),+ setResult: (lastResult, lastCheckedAt) =>+ set({ lastResult, lastCheckedAt, checking: false }),+ setDismissed: (dismissedVersion) => set({ dismissedVersion }),+ setEnabled: (enabled) => set({ enabled }),+ hydrate: (partial) => set(partial),+}))++/**+ * Helper the UI uses to decide whether to show the "update available"+ * surface. Suppresses the surface when the user has explicitly+ * dismissed this exact version; reappears naturally when a newer one+ * ships because `dismissedVersion` no longer matches `result.remote`.+ */+export function shouldShowUpdateBanner(state: UpdateStoreState): boolean {+ if (!state.lastResult) return false+ if (state.lastResult.kind !== "available") return false+ if (state.dismissedVersion && state.dismissedVersion === state.lastResult.remote) {+ return false+ }+ return true+}