⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: show the running version and available updates in the sidebar (#31)
Croff74885d354112
diff --git a/apps/api/src/god/__tests__/integration/god-updates.test.ts b/apps/api/src/god/__tests__/integration/god-updates.test.tsnew file mode 100644index 00000000..0741d5ee--- /dev/null+++ b/apps/api/src/god/__tests__/integration/god-updates.test.ts@@ -0,0 +1,76 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { resetDb } from '../../../__tests__/helpers/db';+import { addUser, setup } from '../helpers';++// The update check under god mode. Only the instance owner may read it — they are+// the one who upgrades — while the running version alone is open to any signed-in+// user, because the sidebar shows it to everyone.+//+// Under NODE_ENV=test nothing is fetched, so the releases are the changelog of this+// build. The parsers have unit tests.++describe('god updates', () => {+ beforeEach(async () => {+ await resetDb();+ });++ describe('access', () => {+ it('refuses both routes for a user who is not the instance owner', async () => {+ await setup();+ const outsider = await addUser();++ expect((await outsider.api.god.updates.get()).status).toBe(403);+ expect((await outsider.api.god.updates.check.post()).status).toBe(403);+ });++ it('serves the running version to any signed-in user', async () => {+ const { god } = await setup();+ const member = await addUser();++ const res = await member.api.settings.version.get();+ const owner = await god.api.god.updates.get();++ expect(res.status).toBe(200);+ expect(res.data?.version).toMatch(/^\d+\.\d+\.\d+$/);+ expect(res.data?.version).toBe(owner.data!.currentVersion);+ });+ });++ describe('status — GET /god/updates', () => {+ it('offers no update while no check has succeeded', async () => {+ const { god } = await setup();++ const res = await god.api.god.updates.get();++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({+ latestVersion: null,+ updateAvailable: false,+ checkedAt: null,+ });+ });++ it('serves the release history from the changelog of this build', async () => {+ const { god } = await setup();++ const res = await god.api.god.updates.get();+ const running = res.data!.releases.find((r) => r.version === res.data!.currentVersion);++ // Every release the build knows about is at or below the version it runs.+ expect(res.data!.releases.length).toBeGreaterThan(0);+ expect(running).toMatchObject({ notesFormat: 'markdown', url: null });+ expect(running!.notes.length).toBeGreaterThan(0);+ });+ });++ describe('check — POST /god/updates/check', () => {+ it('answers with the status even when the feed cannot be read', async () => {+ const { god } = await setup();++ const res = await god.api.god.updates.check.post();++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ updateAvailable: false });+ });+ });+});diff --git a/apps/api/src/god/routes.ts b/apps/api/src/god/routes.tsindex 67c8bcf2..b6e0a61a 100644--- a/apps/api/src/god/routes.ts+++ b/apps/api/src/god/routes.ts@@ -28,6 +28,7 @@ import {import { getInstanceBotSettings, setInstanceBotSettings } from '../telegram/store';import { getStorageSettings, setStorageSettings, StorageSettingsSchema } from '../settings/storage';import { getHotkeySettings, setHotkeySettings, HotkeyCombosSchema } from '../settings/hotkeys';+import { getUpdateStatus, UpdateStatusSchema } from '../settings/updates';// God mode: instance-wide administration, open only to the "god" user (the first// registered account). It covers how people may register, the mail provider that@@ -365,6 +366,28 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},})+ // Whether a newer release is published, and the notes of the releases around the+ // running one. Owner-only: they are the one who upgrades the instance, and the+ // sidebar hides the indicator from everyone else. The version alone is readable by+ // any signed-in user (/settings/version).+ .get('/god/updates', () => getUpdateStatus(), {+ response: { 200: UpdateStatusSchema, 401: ErrorResponse, 403: ErrorResponse },+ detail: {+ summary: 'Get the update status',+ description:+ 'Get the running version, the newest published one, and the release notes. The upstream check is cached for six hours.',+ },+ })++ .post('/god/updates/check', () => getUpdateStatus(true), {+ response: { 200: UpdateStatusSchema, 401: ErrorResponse, 403: ErrorResponse },+ detail: {+ summary: 'Check for updates now',+ description:+ 'Read the published releases again, ignoring the cache. Returns the update status either way: a failed check answers from the previous result.',+ },+ })+.get('/god/telegram-settings', () => getInstanceBotSettings(), {response: { 200: TelegramSettingsResponse, 401: ErrorResponse, 403: ErrorResponse },detail: {diff --git a/apps/api/src/settings/__tests__/unit/updates.test.ts b/apps/api/src/settings/__tests__/unit/updates.test.tsnew file mode 100644index 00000000..19dbd65c--- /dev/null+++ b/apps/api/src/settings/__tests__/unit/updates.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect } from 'bun:test';+import { parseVersion, compareVersions, parseReleasesAtom, parseChangelog } from '../../updates';++// Version handling and the two note sources: the atom feed and the changelog of the+// build. No network or DB — the fetch itself reads the live feed.++describe('parseVersion', () => {+ it('reads a tag with and without the leading v', () => {+ expect(parseVersion('v1.2.3')).toEqual([1, 2, 3]);+ expect(parseVersion('1.2.3')).toEqual([1, 2, 3]);+ });++ it('rejects a prerelease', () => {+ expect(parseVersion('1.2.3-rc.1')).toBeNull();+ expect(parseVersion('v2.0.0-beta')).toBeNull();+ });++ it('rejects anything that is not major.minor.patch', () => {+ for (const value of ['1.2', 'nightly', '', 'v1.2.3.4']) {+ expect(parseVersion(value)).toBeNull();+ }+ });+});++describe('compareVersions', () => {+ it('orders by major, then minor, then patch', () => {+ expect(compareVersions('1.0.0', '2.0.0')).toBeLessThan(0);+ expect(compareVersions('1.3.0', '1.2.9')).toBeGreaterThan(0);+ expect(compareVersions('1.2.10', '1.2.9')).toBeGreaterThan(0);+ });++ it('treats equal versions as equal, whatever the leading v', () => {+ expect(compareVersions('v0.2.0', '0.2.0')).toBe(0);+ });++ it('reports no difference when a value is unparseable, so no update is offered', () => {+ expect(compareVersions('1.2.3-rc.1', '1.0.0')).toBe(0);+ expect(compareVersions('nightly', '1.0.0')).toBe(0);+ });+});++function feed(entries: string): string {+ return `<?xml version="1.0" encoding="UTF-8"?>\n<feed xmlns="http://www.w3.org/2005/Atom">\n<title>Release notes from itsaplan</title>\n${entries}\n</feed>`;+}++function entry(tag: string, updated: string, content: string): string {+ return ` <entry>+ <id>tag:github.com,2008:Repository/1/${tag}</id>+ <updated>${updated}</updated>+ <link rel="alternate" type="text/html" href="https://github.com/croffasia/itsaplan/releases/tag/${tag}"/>+ <title>${tag}</title>+ <content type="html">${content}</content>+ <author><name>croffasia</name></author>+ </entry>`;+}++describe('parseReleasesAtom', () => {+ it('reads the tag, version, date, url and notes of every entry', () => {+ const xml = feed(entry('v0.2.0', '2026-07-23T10:42:42Z', '<p>Notes</p>'));+ expect(parseReleasesAtom(xml)).toEqual([+ {+ tag: 'v0.2.0',+ version: '0.2.0',+ publishedAt: '2026-07-23T10:42:42Z',+ url: 'https://github.com/croffasia/itsaplan/releases/tag/v0.2.0',+ notes: '<p>Notes</p>',+ notesFormat: 'html',+ },+ ]);+ });++ it('sorts newest version first, whatever the feed order', () => {+ const xml = feed(+ [+ entry('v0.1.0', '2026-07-22T00:00:00Z', ''),+ entry('v0.10.0', '2026-08-01T00:00:00Z', ''),+ entry('v0.2.0', '2026-07-23T00:00:00Z', ''),+ ].join('\n'),+ );+ expect(parseReleasesAtom(xml).map((r) => r.version)).toEqual(['0.10.0', '0.2.0', '0.1.0']);+ });++ it('skips prereleases so they are never offered as an update', () => {+ const xml = feed(+ [+ entry('v0.3.0-rc.1', '2026-08-02T00:00:00Z', ''),+ entry('v0.2.0', '2026-07-23T00:00:00Z', ''),+ ].join('\n'),+ );+ expect(parseReleasesAtom(xml).map((r) => r.version)).toEqual(['0.2.0']);+ });++ it('resolves one level of escaping, leaving the entities the HTML itself carries', () => {+ const content =+ '<a href="https://example.com/a?b=1&amp;c=2">What's new</a>';+ const xml = feed(entry('v0.2.0', '2026-07-23T00:00:00Z', content));+ expect(parseReleasesAtom(xml)[0].notes).toBe(+ '<a href="https://example.com/a?b=1&c=2">What\'s new</a>',+ );+ });++ it('returns an empty list for a feed with no releases', () => {+ expect(parseReleasesAtom(feed(''))).toEqual([]);+ });+});++describe('parseChangelog', () => {+ const changelog = `# Changelog++## [0.2.0](https://github.com/croffasia/itsaplan/compare/v0.1.0...v0.2.0) (2026-07-23)+++### Features++* **notes:** add sticky-note boards ([#18](https://example.com/18))++## 0.1.0 (2026-07-22)+++### Features++* initial commit+`;++ it('reads both heading forms release-please writes', () => {+ expect(parseChangelog(changelog).map((r) => [r.tag, r.version, r.publishedAt])).toEqual([+ ['v0.2.0', '0.2.0', '2026-07-23'],+ ['v0.1.0', '0.1.0', '2026-07-22'],+ ]);+ });++ it('takes the section body as markdown, up to the next release', () => {+ const [latest] = parseChangelog(changelog);+ expect(latest.notesFormat).toBe('markdown');+ expect(latest.url).toBeNull();+ expect(latest.notes).toBe(+ '### Features\n\n* **notes:** add sticky-note boards ([#18](https://example.com/18))',+ );+ });++ it('returns an empty list when the file holds no releases', () => {+ expect(parseChangelog('# Changelog\n\nNothing released yet.\n')).toEqual([]);+ });+});diff --git a/apps/api/src/settings/routes.ts b/apps/api/src/settings/routes.tsindex 8e9564db..0499002e 100644--- a/apps/api/src/settings/routes.ts+++ b/apps/api/src/settings/routes.ts@@ -1,8 +1,9 @@-import { Elysia } from 'elysia';+import { Elysia, t } from 'elysia';import { authContext } from '../shared/auth-context';import { ErrorResponse } from '../shared/responses';import { getStorageSettings, StorageSettingsSchema } from './storage';import { getHotkeySettings, HotkeyCombosSchema } from './hotkeys';+import { getAppVersion } from './updates';// Routes for global instance settings (app_setting): a key-value store not scoped// to a project. The MCP toggle is per-project (see projects/routes.ts), not here.@@ -29,4 +30,16 @@ export const settingsRoutes = new Elysia({description:'Get the keyboard shortcut overrides that apply to everyone on this instance. Every signed-in user reads them; changing them is god mode.',},+ })++ // The running version, shown in the sidebar to everyone. Whether a newer one+ // exists is god mode (/god/updates), and so is the release history. A session is+ // required: the version tells an anonymous visitor which release to look up+ // vulnerabilities for.+ .get('/settings/version', () => ({ version: getAppVersion() }), {+ response: { 200: t.Object({ version: t.String() }), 401: ErrorResponse },+ detail: {+ summary: 'Get the running version',+ description: 'Get the version of the app this instance runs.',+ },});diff --git a/apps/api/src/settings/updates.ts b/apps/api/src/settings/updates.tsnew file mode 100644index 00000000..831f38dc--- /dev/null+++ b/apps/api/src/settings/updates.ts@@ -0,0 +1,247 @@+import { t } from 'elysia';+import { getSetting, setSetting } from '@repo/db';+import pkg from '../../../../package.json';++// Whether a newer release is published, plus the notes to show. Two sources split+// by version: the CHANGELOG.md of this build up to the running version, the+// repository's releases atom feed above it.+//+// The feed is github.com web content, not the REST API, so no token and no+// 60/hour limit (agent-skills/skill-format.ts reads github.com atom the same way).+// Its result is cached in app_setting for CACHE_TTL_MS and refreshed on read, so an+// instance makes one outbound request per interval whatever the number of tabs and+// whether or not the feed can be read. A failed check keeps the previous result and+// leaves the local history intact.++const UPDATES_CACHE_KEY = 'updates.latest';+const CACHE_TTL_MS = 6 * 60 * 60 * 1000;+const FETCH_TIMEOUT_MS = 10_000;++// Fixed: an instance checks the project it is built from, so there is nothing to+// configure.+const FEED_URL = 'https://github.com/croffasia/itsaplan/releases.atom';++const CHANGELOG_PATH = `${import.meta.dir}/../../../../CHANGELOG.md`;++export interface Release {+ tag: string;+ version: string;+ // An ISO datetime from the feed, a "YYYY-MM-DD" date from the changelog.+ publishedAt: string;+ // The release page. Changelog entries carry no such link.+ url: string | null;+ notes: string;+ notesFormat: 'html' | 'markdown';+}++export interface UpdateStatus {+ currentVersion: string;+ // The newest published version, or null when no check has succeeded yet.+ latestVersion: string | null;+ updateAvailable: boolean;+ checkedAt: string | null;+ // Newest first.+ releases: Release[];+}++const ReleaseSchema = t.Object({+ tag: t.String(),+ version: t.String(),+ publishedAt: t.String(),+ url: t.Nullable(t.String()),+ notes: t.String(),+ notesFormat: t.UnionEnum(['html', 'markdown']),+});++export const UpdateStatusSchema = t.Object({+ currentVersion: t.String(),+ latestVersion: t.Nullable(t.String()),+ updateAvailable: t.Boolean(),+ checkedAt: t.Nullable(t.String()),+ releases: t.Array(ReleaseSchema),+});++interface UpdateCache {+ // When a check last ran, successful or not — the TTL is measured against this.+ attemptedAt: string;+ // Null while no check has succeeded.+ checkedAt: string | null;+ releases: Release[];+}++export function getAppVersion(): string {+ return pkg.version;+}++// Null for anything that is not a plain major.minor.patch, prereleases included:+// those are never offered as an update.+export function parseVersion(value: string): [number, number, number] | null {+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(value.trim());+ if (!match) return null;+ return [Number(match[1]), Number(match[2]), Number(match[3])];+}++// 0 when equal or either side is unparseable.+export function compareVersions(a: string, b: string): number {+ const left = parseVersion(a);+ const right = parseVersion(b);+ if (!left || !right) return 0;+ for (let i = 0; i < 3; i++) {+ if (left[i] !== right[i]) return left[i] - right[i];+ }+ return 0;+}++// '&' last, so a double-escaped sequence does not decode twice.+function decodeEntities(value: string): string {+ return value+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code)))+ .replace(/&/g, '&');+}++// Regular expressions rather than an XML dependency: the feed is a fixed shape.+// Newest first.+export function parseReleasesAtom(xml: string): Release[] {+ const releases: Release[] = [];+ for (const [, entry] of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {+ const link = /href="([^"]*\/releases\/tag\/([^"]+))"/.exec(entry);+ if (!link) continue;+ const tag = decodeURIComponent(link[2]);+ const version = tag.replace(/^v/, '');+ if (!parseVersion(version)) continue;+ const updated = /<updated>([^<]+)<\/updated>/.exec(entry);+ const content = /<content[^>]*>([\s\S]*?)<\/content>/.exec(entry);+ releases.push({+ tag,+ version,+ publishedAt: updated?.[1] ?? '',+ url: decodeEntities(link[1]),+ notes: content ? decodeEntities(content[1]).trim() : '',+ notesFormat: 'html',+ });+ }+ return releases.sort((a, b) => compareVersions(b.version, a.version));+}++// release-please writes both heading forms: "## [0.2.0](compare-link) (2026-07-23)"+// and, for the first release, "## 0.1.0 (2026-07-22)".+export function parseChangelog(markdown: string): Release[] {+ const heading = /^## \[?(\d+\.\d+\.\d+)\]?(?:\([^)]*\))?\s*\((\d{4}-\d{2}-\d{2})\)$/gm;+ const found = [...markdown.matchAll(heading)];+ return found.map((match, i) => {+ const start = match.index + match[0].length;+ const end = i + 1 < found.length ? found[i + 1].index : markdown.length;+ return {+ tag: `v${match[1]}`,+ version: match[1],+ publishedAt: match[2],+ url: null,+ notes: markdown.slice(start, end).trim(),+ notesFormat: 'markdown' as const,+ };+ });+}++let changelog: Release[] | null = null;++// The file ships with the build and never changes at runtime, so it is read once.+async function localHistory(): Promise<Release[]> {+ if (changelog) return changelog;+ try {+ changelog = parseChangelog(await Bun.file(CHANGELOG_PATH).text());+ } catch (err) {+ console.error('[updates] changelog unreadable:', err);+ changelog = [];+ }+ return changelog;+}++// One refresh at a time: concurrent readers of an expired cache share the request.+let inFlight: Promise<UpdateCache | null> | null = null;++async function readFeed(): Promise<Release[]> {+ const res = await fetch(FEED_URL, {+ headers: { 'User-Agent': 'itsaplan' },+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),+ });+ if (!res.ok) throw new Error(`feed returned ${res.status}`);+ return parseReleasesAtom(await res.text());+}++// A failed attempt is stored too, so an unreachable feed costs one connection per+// interval rather than one per read.+async function check(previous: UpdateCache | null): Promise<UpdateCache | null> {+ // The suite must not depend on github.com being reachable, and the same+ // NODE_ENV already gates the db reset helper.+ if (process.env.NODE_ENV === 'test') return null;+ const attemptedAt = new Date().toISOString();+ let cache: UpdateCache = {+ attemptedAt,+ checkedAt: previous?.checkedAt ?? null,+ releases: previous?.releases ?? [],+ };+ try {+ cache = { attemptedAt, checkedAt: attemptedAt, releases: await readFeed() };+ } catch (err) {+ console.error('[updates] check failed:', err);+ }+ try {+ await setSetting(UPDATES_CACHE_KEY, cache);+ } catch (err) {+ console.error('[updates] cache write failed:', err);+ }+ return cache;+}++function refresh(previous: UpdateCache | null): Promise<UpdateCache | null> {+ inFlight ??= check(previous).finally(() => {+ inFlight = null;+ });+ return inFlight;+}++// Every field UpdateStatusSchema requires: a row that would fail response validation+// is re-checked instead of served as a 500.+function usableRelease(r: Release): boolean {+ return (+ typeof r.tag === 'string' &&+ typeof r.version === 'string' &&+ typeof r.publishedAt === 'string' &&+ (r.url === null || typeof r.url === 'string') &&+ typeof r.notes === 'string' &&+ (r.notesFormat === 'html' || r.notesFormat === 'markdown')+ );+}++function usable(cache: UpdateCache | null): cache is UpdateCache {+ if (!cache || typeof cache.attemptedAt !== 'string') return false;+ if (cache.checkedAt !== null && typeof cache.checkedAt !== 'string') return false;+ if (!Array.isArray(cache.releases)) return false;+ return cache.releases.every(usableRelease);+}++// Refreshes an expired cache, or always when `force` is set ("check now").+export async function getUpdateStatus(force = false): Promise<UpdateStatus> {+ const stored = await getSetting<UpdateCache>(UPDATES_CACHE_KEY);+ const cached = usable(stored) ? stored : null;+ // Negated so an unreadable timestamp counts as expired instead of fresh forever,+ // which is what comparing NaN would do.+ const expired = !cached || !(Date.now() - Date.parse(cached.attemptedAt) < CACHE_TTL_MS);+ const cache = force || expired ? ((await refresh(cached)) ?? cached) : cached;++ const currentVersion = getAppVersion();+ const published = cache?.releases ?? [];+ const latestVersion = published[0]?.version ?? null;+ const newer = published.filter((r) => compareVersions(r.version, currentVersion) > 0);+ return {+ currentVersion,+ latestVersion,+ updateAvailable: newer.length > 0,+ checkedAt: cache?.checkedAt ?? null,+ releases: [...newer, ...(await localHistory())],+ };+}diff --git a/apps/web/src/components/brand/SidebarBrandFooter.tsx b/apps/web/src/components/brand/SidebarBrandFooter.tsxindex 4f92810d..a9961934 100644--- a/apps/web/src/components/brand/SidebarBrandFooter.tsx+++ b/apps/web/src/components/brand/SidebarBrandFooter.tsx@@ -1,19 +1,78 @@+'use client';++import { useEffect, useState } from 'react';import ItsAPlanMark from '@/components/brand/ItsAPlanMark';+import UpdatesDialog from '@/components/layout/UpdatesDialog';+import { useSession } from '@/lib/auth-client';+import { cn } from '@/lib/utils';+import { useAppVersionQuery, useUpdateStatusQuery } from '@/services/updates.service';-// The product mark at the bottom of both sidebars. Collapses to the mark alone-// when the sidebar is in icon mode.+// The product mark at the bottom of both sidebars, with the running version under+// it. Collapses to the mark alone when the sidebar is in icon mode.+//+// The instance owner also sees whether a newer release is published and opens the+// release notes from here — they are the one who upgrades the instance, so the+// check is theirs alone (GET /god/updates). Everyone else sees the version only.export default function SidebarBrandFooter() {- return (- <div className="flex items-center gap-2.5 px-2 pt-2 pb-1.5 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0">+ const { data: session } = useSession();+ // The session store can already be filled by the time React hydrates, while the+ // server rendered without it. Reading it only after mount keeps the server and+ // the first client render identical.+ const [mounted, setMounted] = useState(false);+ useEffect(() => setMounted(true), []);+ const isGod = mounted && session?.user.role === 'god';++ const { data: appVersion } = useAppVersionQuery();+ const { data: status } = useUpdateStatusQuery(isGod);+ const [showUpdates, setShowUpdates] = useState(false);++ const version = appVersion?.version ?? status?.currentVersion;+ // The version to offer, or null when the running one is the newest known.+ const newerVersion = status?.updateAvailable ? status.latestVersion : null;++ const layout =+ 'flex w-full items-center gap-2.5 px-2 pt-2 pb-1.5 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0';++ const content = (+ <><ItsAPlanMark className="size-9 shrink-0 text-sidebar-foreground" />- <div className="grid leading-none group-data-[collapsible=icon]:hidden">+ <div className="grid text-left leading-none group-data-[collapsible=icon]:hidden"><span className="text-base font-semibold tracking-tight text-sidebar-foreground">It's a Plan</span>- <span className="mt-1 text-[10px] font-medium tracking-wider text-muted-foreground uppercase">- Self-hosted- </span>+ {newerVersion ? (+ <span className="mt-1 flex items-center gap-1.5 text-[10px] font-medium tracking-wider text-primary uppercase">+ {/* A pulsing ring around the dot, so the update is noticed in a footer+ nobody looks at. */}+ <span className="relative flex size-1.5" aria-hidden>+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-500 opacity-75" />+ <span className="relative inline-flex size-1.5 rounded-full bg-emerald-500" />+ </span>+ {`v${newerVersion} available`}+ </span>+ ) : (+ <span className="mt-1 text-[10px] font-medium tracking-wider text-muted-foreground uppercase">+ {version ? `v${version}` : 'Self-hosted'}+ </span>+ )}</div>- </div>+ </>+ );++ // Without the owner's release data there is nothing to open, so the footer stays+ // the plain mark it is for everyone else.+ if (!status) return <div className={layout}>{content}</div>;++ return (+ <>+ <button+ type="button"+ className={cn(layout, 'rounded-md hover:bg-sidebar-accent')}+ onClick={() => setShowUpdates(true)}+ >+ {content}+ </button>+ {showUpdates && <UpdatesDialog status={status} onClose={() => setShowUpdates(false)} />}+ </>);}diff --git a/apps/web/src/components/layout/ReleaseNotes.tsx b/apps/web/src/components/layout/ReleaseNotes.tsxnew file mode 100644index 00000000..3bd2d959--- /dev/null+++ b/apps/web/src/components/layout/ReleaseNotes.tsx@@ -0,0 +1,44 @@+import { useMemo } from 'react';+import type { Release } from '@/lib/api';+import { renderMarkdown, sanitizeHtml } from '@/lib/markdown';+import { formatDate } from '@/utils/dates';+import { Badge } from '@/components/ui/badge';++// One release in the updates dialog. Feed notes arrive as rendered HTML, changelog+// notes as markdown; both end up sanitized.+export default function ReleaseNotes({ release, badge }: { release: Release; badge?: string }) {+ const html = useMemo(() => {+ const options = { newTabLinks: true };+ return release.notesFormat === 'html'+ ? sanitizeHtml(release.notes, options)+ : renderMarkdown(release.notes, options);+ }, [release.notes, release.notesFormat]);++ return (+ <section className="border-t border-border pt-4 first:border-t-0 first:pt-0">+ <div className="mb-2 flex items-center gap-2">+ {release.url ? (+ <a+ href={release.url}+ target="_blank"+ rel="noreferrer"+ className="font-semibold hover:underline"+ >+ {release.tag}+ </a>+ ) : (+ <span className="font-semibold">{release.tag}</span>+ )}+ {badge && <Badge variant="secondary">{badge}</Badge>}+ {release.publishedAt && (+ <span className="text-xs text-muted-foreground">{formatDate(release.publishedAt)}</span>+ )}+ </div>+ {html ? (+ <div className="md-content" dangerouslySetInnerHTML={{ __html: html }} />+ ) : (+ <p className="text-sm text-muted-foreground">This release has no notes.</p>+ )}+ </section>+ );+}diff --git a/apps/web/src/components/layout/UpdatesDialog.tsx b/apps/web/src/components/layout/UpdatesDialog.tsxnew file mode 100644index 00000000..eb33d490--- /dev/null+++ b/apps/web/src/components/layout/UpdatesDialog.tsx@@ -0,0 +1,117 @@+'use client';++import { useState } from 'react';+import { ChevronRight, ExternalLink, RefreshCw } from 'lucide-react';+import type { UpdateStatus } from '@/lib/api';+import Modal from '@/components/common/overlay/Modal';+import ReleaseNotes from '@/components/layout/ReleaseNotes';+import { Button } from '@/components/ui/button';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+import { useCheckForUpdates } from '@/services/updates.service';+import { formatDateTime } from '@/utils/dates';+import { isNewerVersion } from '@/utils/version';+import { cn } from '@/lib/utils';++// Without a successful check, calling the running version the latest would claim+// more than is known.+function summary(status: UpdateStatus): string {+ if (status.updateAvailable) {+ return `You're running ${status.currentVersion}. Latest is ${status.latestVersion}.`;+ }+ if (!status.latestVersion) {+ return `You're running ${status.currentVersion}. Latest release unknown.`;+ }+ return `You're running ${status.currentVersion}, the latest release.`;+}++// The release notes behind the sidebar version. With a newer release published,+// the ones above the running version are expanded and the history sits behind a+// toggle; otherwise it is the history alone, with the running version marked.+export default function UpdatesDialog({+ status,+ onClose,+}: {+ status: UpdateStatus;+ onClose: () => void;+}) {+ const check = useCheckForUpdates();+ const [showEarlier, setShowEarlier] = useState(false);++ const newer = status.releases.filter((r) => isNewerVersion(r.version, status.currentVersion));+ const earlier = status.releases.filter((r) => !isNewerVersion(r.version, status.currentVersion));+ // Derived from a release link, so the repository is not hardcoded here. Only feed+ // entries carry one.+ const tagUrl = status.releases.find((r) => r.url)?.url;+ const allReleasesUrl = tagUrl?.replace(/\/tag\/[^/]*$/, '') ?? null;++ const earlierList = earlier.map((release) => (+ <ReleaseNotes+ key={release.tag}+ release={release}+ badge={release.version === status.currentVersion ? 'Running' : undefined}+ />+ ));++ return (+ <Modal+ title={status.updateAvailable ? 'Update available' : 'Release history'}+ description={summary(status)}+ onClose={onClose}+ wide+ >+ <div className="space-y-4">+ {status.releases.length === 0 && (+ <p className="text-sm text-muted-foreground">No release notes shipped with this build.</p>+ )}++ {newer.map((release) => (+ <ReleaseNotes key={release.tag} release={release} badge="New" />+ ))}++ {newer.length > 0 && earlier.length > 0 ? (+ <Collapsible open={showEarlier} onOpenChange={setShowEarlier}>+ <CollapsibleTrigger className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">+ <ChevronRight+ className={cn('size-4 transition-transform', showEarlier && 'rotate-90')}+ />+ Earlier releases+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-4 space-y-4">{earlierList}</CollapsibleContent>+ </Collapsible>+ ) : (+ earlierList+ )}+ </div>++ <div className="flex items-center justify-between gap-3 border-t border-border pt-4">+ <div className="flex items-center gap-3">+ <Button+ variant="outline"+ size="sm"+ onClick={() => check.mutate()}+ disabled={check.isPending}+ >+ <RefreshCw className={cn('size-4', check.isPending && 'animate-spin')} />+ {check.isPending ? 'Checking' : 'Check for updates'}+ </Button>+ {status.checkedAt && (+ <span className="text-xs text-muted-foreground">+ Last checked {formatDateTime(status.checkedAt)}+ </span>+ )}+ </div>+ {allReleasesUrl && (+ <a+ href={allReleasesUrl}+ target="_blank"+ rel="noreferrer"+ className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"+ >+ All releases+ <ExternalLink className="size-3.5" />+ </a>+ )}+ </div>+ </Modal>+ );+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex bff16a3c..b9059c51 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -642,6 +642,28 @@ export interface StorageSettings {export type StorageSettingsPatch = Partial<StorageSettings>;+// One release. The ones above the running version come from the repository's feed+// and carry HTML notes; the ones up to it come from this build's changelog and+// carry markdown.+export interface Release {+ tag: string;+ version: string;+ publishedAt: string;+ url: string | null;+ notes: string;+ notesFormat: 'html' | 'markdown';+}++// How the running version compares to what is published. `latestVersion` and+// `checkedAt` are null until an upstream check has succeeded.+export interface UpdateStatus {+ currentVersion: string;+ latestVersion: string | null;+ updateAvailable: boolean;+ checkedAt: string | null;+ releases: Release[];+}+// ── Instance administration (god mode) ────────────────────────────────────────// Who may create an account on this instance.@@ -2436,6 +2458,14 @@ export const api = {body: JSON.stringify(combos),}),+ // The running version, shown in the sidebar to every signed-in user.+ getAppVersion: () => request<{ version: string }>('/settings/version'),++ // Whether a newer release exists, and the release notes behind it. God mode: the+ // instance owner is the one who upgrades.+ getUpdateStatus: () => request<UpdateStatus>('/god/updates'),+ checkForUpdates: () => request<UpdateStatus>('/god/updates/check', { method: 'POST' }),+getInstanceStorageSettings: () => request<StorageSettings>('/god/storage-settings'),updateInstanceStorageSettings: (patch: StorageSettingsPatch) =>request<StorageSettings>('/god/storage-settings', {diff --git a/apps/web/src/lib/markdown.ts b/apps/web/src/lib/markdown.tsindex e85733be..f0fe83ba 100644--- a/apps/web/src/lib/markdown.ts+++ b/apps/web/src/lib/markdown.ts@@ -1,13 +1,38 @@import { marked } from 'marked';import DOMPurify from 'isomorphic-dompurify';+// Content that links away from the app (release notes) asks for newTabLinks, so a+// link does not replace the app with GitHub.+export interface HtmlOptions {+ newTabLinks?: boolean;+}++function newTab(node: Element): void {+ if (node.tagName === 'A' && node.hasAttribute('href')) {+ node.setAttribute('target', '_blank');+ node.setAttribute('rel', 'noreferrer');+ }+}++// HTML that arrives already rendered, made safe for dangerouslySetInnerHTML. Used+// for release notes, which GitHub renders and the api passes through unchanged.+export function sanitizeHtml(html: string, options?: HtmlOptions): string {+ if (!options?.newTabLinks) return DOMPurify.sanitize(html);+ DOMPurify.addHook('afterSanitizeAttributes', newTab);+ try {+ return DOMPurify.sanitize(html);+ } finally {+ DOMPurify.removeHook('afterSanitizeAttributes');+ }+}+// Markdown to display-ready HTML. `marked` passes raw HTML in the source// through untouched, so the result is sanitized before it reaches// dangerouslySetInnerHTML — markdown values are written by project members and// agents, and would otherwise be a script injection into every viewer's session.// breaks:true so a single newline becomes a line break, matching the// MarkdownEditor used in the issue detail (tiptap-markdown breaks:true).-export function renderMarkdown(value: string): string {+export function renderMarkdown(value: string, options?: HtmlOptions): string {const html = marked.parse(value, { async: false, breaks: true }) as string;- return DOMPurify.sanitize(html);+ return sanitizeHtml(html, options);}diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex 58bb62e1..286030c0 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -124,6 +124,9 @@ export const qk = {instanceStorageSettings: ['instanceStorageSettings'] as const,// The upload limits as read by the upload UI (open to any signed-in user).storageSettings: ['storageSettings'] as const,+ // The running version (any signed-in user) and the upstream release check (god).+ appVersion: ['appVersion'] as const,+ updateStatus: ['updateStatus'] as const,// The bindings every client resolves from, and the god-mode editor's copy.hotkeySettings: ['hotkeySettings'] as const,instanceHotkeySettings: ['hotkeySettings', 'god'] as const,diff --git a/apps/web/src/services/updates.service.ts b/apps/web/src/services/updates.service.tsnew file mode 100644index 00000000..5ee2b37a--- /dev/null+++ b/apps/web/src/services/updates.service.ts@@ -0,0 +1,42 @@+'use client';++import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { api } from '@/lib/api';+import { useSession } from '@/lib/auth-client';+import { qk } from '@/services/queryKeys';++// The running version and the upstream release check behind the sidebar footer.+// The version is read by every signed-in user; the check is owner-only, so the+// query is disabled for everyone else instead of asking and taking a 403.++export function useAppVersionQuery() {+ const { data: session } = useSession();+ return useQuery({+ queryKey: qk.appVersion,+ queryFn: () => api.getAppVersion(),+ // The route needs a session; the login and invite screens have none.+ enabled: Boolean(session),+ // Fixed for the life of the process: it only changes when the instance restarts+ // on a new build, which reloads the page anyway.+ staleTime: Infinity,+ });+}++export function useUpdateStatusQuery(enabled: boolean) {+ return useQuery({+ queryKey: qk.updateStatus,+ queryFn: () => api.getUpdateStatus(),+ enabled,+ // The api caches the upstream check for six hours; refetching sooner would only+ // re-read the same cached answer.+ staleTime: 30 * 60_000,+ });+}++export function useCheckForUpdates() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: () => api.checkForUpdates(),+ onSuccess: (data) => qc.setQueryData(qk.updateStatus, data),+ });+}diff --git a/apps/web/src/utils/version.ts b/apps/web/src/utils/version.tsnew file mode 100644index 00000000..167ec25d--- /dev/null+++ b/apps/web/src/utils/version.ts@@ -0,0 +1,20 @@+// Version comparison for the release list. The api decides whether an update+// exists; this splits the releases it returns into the ones above the running+// version and the ones at or below it.++function parts(value: string): [number, number, number] | null {+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(value.trim());+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;+}++// Whether `value` is a later release than `other`. Anything that is not a plain+// major.minor.patch counts as not newer, so it never lands in the "new" group.+export function isNewerVersion(value: string, other: string): boolean {+ const a = parts(value);+ const b = parts(other);+ if (!a || !b) return false;+ for (let i = 0; i < 3; i++) {+ if (a[i] !== b[i]) return a[i] > b[i];+ }+ return false;+}