From d3843eef6e7be6d92477b04ba6e793449189a38d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:34:36 -0500 Subject: [PATCH] feat(themes): update already-shared Showcase themes in place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sharing an edited theme that was already accepted into the Showcase previously allocated a new `-2` folder, creating a duplicate entry instead of updating the existing theme. This adds an in-place update path across contracts, server, web UI, and the Showcase check script: - Adds `updateSlug` on Showcase submissions, `slug` and `isUpdate` on submission records, and a `themeShowcaseUpdate` server capability so older servers stay on the existing new-share flow. - Updates `ThemeShowcase.submit` to refresh the Showcase list, verify ownership and changes against the live file digest, and commit only `theme.threadlines-theme` and `thumbnail.png` so `meta.json` (`sharedBy`, `featured`) and `NOTICE.md` stay untouched on `main`. - Records `update_base_sha` and `published_file_sha` in migration 125 so in-review updates (including rename-only and prompt-only changes) stay in review until their own merge and index rebuild land, and taking back an update closes only the update PR. - Adds a Showcase target picker to `ThemeShareDialog` when the signed-in account owns Showcase themes (defaulting to the matching folder across computers and renames, seeding credits from the live listing, and letting the user switch to sharing as a new theme), plus `Update in Showcase…` and `Take back update…` menu labels and digest-keyed Showcase thumbnail caching. - Fixes `scripts/theme-showcase.ts` so an outside author can update their own already-featured theme without tripping the maintainer-only `featured` check. --- .../environment/Layers/ServerEnvironment.ts | 1 + apps/server/src/guide/topics.ts | 2 +- apps/server/src/persistence/Migrations.ts | 2 + .../125_ThemeShowcaseUpdateBaseSha.ts | 16 ++ apps/server/src/themes/ThemeShowcase.test.ts | 183 ++++++++++++++++++ apps/server/src/themes/ThemeShowcase.ts | 152 ++++++++++++--- .../src/themes/ThemeShowcaseRepository.ts | 16 +- .../theme/ui/ThemeCreditsFields.tsx | 26 ++- .../components/theme/ui/ThemeSettingsRows.tsx | 28 ++- .../theme/ui/ThemeShareDialog.browser.tsx | 157 ++++++++++++++- .../components/theme/ui/ThemeShareDialog.tsx | 157 +++++++++++++-- .../components/theme/ui/ThemeShowcaseView.tsx | 2 +- apps/web/src/themeLibrary/themeShowcase.ts | 70 +++++-- docs/design/custom-themes.md | 17 ++ packages/contracts/src/environment.ts | 6 + packages/contracts/src/themeShowcase.ts | 9 + scripts/theme-showcase.test.ts | 25 +++ scripts/theme-showcase.ts | 7 +- 18 files changed, 807 insertions(+), 69 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/125_ThemeShowcaseUpdateBaseSha.ts diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index 9d2b7c584..7235f883f 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -102,6 +102,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function themes: true, themeShowcase: true, themeShowcaseTakeBack: true, + themeShowcaseUpdate: true, themeVsCode: true, eventTasks: true, threadMove: true, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 6d85120aa..aee39e1be 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -589,7 +589,7 @@ System follows the computer's light or dark setting. In {place:appearance.system An agent makes one with preview_theme (screenshots of the app wearing it, its readability checks and what its art costs) and offers it with show_theme: a row in the chat with Try it. Trying shows a bar at the top of the window, Keep or Undo, and it switches back by itself after 15 seconds (for a new version of a theme already kept from the same offer in that chat, the bar asks to Update that copy, with Keep both to add another); Esc, a reload or closing the window undo it too (while the /theme picker is open, a preview waits for its ✕ or Esc instead). The Settings gallery, the composer's /theme and an imported ${THEME_FILE_EXTENSION} file start the same trial. New theme, in /theme or in Settings, puts the start of a request in the message box ("Make me a Threadlines theme that feels like") with a few ideas to finish it (Settings opens a general chat for it); sending it asks the agent for one. In Settings, the options on a theme's picture rename it, duplicate it to change a copy, export a file to share, copy the request it was made from, or delete it; starters can be duplicated and exported. An exported file never says which thread made the theme and leaves the request out unless the user includes it; its author can add a credit (name, link, CC BY or CC0), which importing shows, and a theme that already has one keeps it. -The Showcase, beside Your themes in {place:settings.appearance}, lists themes people shared, reviewed before they're listed; clicking one starts the same trial. Share to Showcase…, in a theme's options, opens a public pull request to the Threadlines/themes repository from the GitHub account this computer is signed in to with gh, after showing what gets published. It's public the moment it's shared, under that account's name but without its email. It needs a CC BY or CC0 license, fonts that carry their own copyright and license, and no parts this version doesn't know; the theme's picture then says In review, In the Showcase, Taken back or Not added. Until it's added, Take back from Showcase…, in the same options, closes the pull request; GitHub keeps the closed one. Agents can't share or take back for the user. +The Showcase, beside Your themes in {place:settings.appearance}, lists themes people shared, reviewed before they're listed; clicking one starts the same trial. Share to Showcase…, in a theme's options, opens a public pull request to the Threadlines/themes repository from the GitHub account this computer is signed in to with gh, after showing what gets published. It's public the moment it's shared, under that account's name but without its email. It needs a CC BY or CC0 license, fonts that carry their own copyright and license, and no parts this version doesn't know; the theme's picture then says In review, In the Showcase, Taken back or Not added. For a theme you already shared, Update in Showcase… (or picking it in the share dialog) opens a pull request that updates its folder in place instead of adding a duplicate, leaving its metadata untouched. Until a share or update is merged, Take back from Showcase… (or Take back update…), in the same options, closes the pull request; GitHub keeps the closed one. Agents can't share or take back for the user. Edit colors…, in a theme's options in {place:settings.appearance} (Light and Dark too) or "Edit theme colors…" in the command palette, opens a panel beside the app with the theme's own colors (background, text, quiet text, accent, text on accent, and the optional borders, status, code background and selected text). Every change shows across the app at once; Cancel or Esc puts back what was there. Each color says where it's hard to read, and Fix for me moves those colors a little until they read. Pick from the app, then a click anywhere, says which of those colors paints that spot. Save updates a theme in the library; any other is saved as a new theme. diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 0e377f4c2..9c0f6cb3f 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -144,6 +144,7 @@ import Migration0121 from "./Migrations/121_ProjectionThreadSecretRequests.ts"; import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; import Migration0123 from "./Migrations/123_ProjectNotes.ts"; import Migration0124 from "./Migrations/124_ChildAccessAndStopColumns.ts"; +import Migration0125 from "./Migrations/125_ThemeShowcaseUpdateBaseSha.ts"; /** * Migration loader with all migrations defined inline. @@ -280,6 +281,7 @@ export const migrationEntries = [ [122, "ProjectBriefs", Migration0122], [123, "ProjectNotes", Migration0123], [124, "ChildAccessAndStopColumns", Migration0124], + [125, "ThemeShowcaseUpdateBaseSha", Migration0125], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/125_ThemeShowcaseUpdateBaseSha.ts b/apps/server/src/persistence/Migrations/125_ThemeShowcaseUpdateBaseSha.ts new file mode 100644 index 000000000..285105ba4 --- /dev/null +++ b/apps/server/src/persistence/Migrations/125_ThemeShowcaseUpdateBaseSha.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * When a Showcase share updates an already-listed theme (docs/design/custom-themes.md, + * "Showcase"): `update_base_sha` records the SHA-256 of the theme file on `main` + * when the update started (null for shares that add a new theme), and + * `published_file_sha` records the SHA-256 of the file this share writes. + * + * New columns only; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE theme_showcase_submissions ADD COLUMN update_base_sha TEXT`; + yield* sql`ALTER TABLE theme_showcase_submissions ADD COLUMN published_file_sha TEXT`; +}); diff --git a/apps/server/src/themes/ThemeShowcase.test.ts b/apps/server/src/themes/ThemeShowcase.test.ts index bb1edf9f0..812dba886 100644 --- a/apps/server/src/themes/ThemeShowcase.test.ts +++ b/apps/server/src/themes/ThemeShowcase.test.ts @@ -155,6 +155,8 @@ const github = { number: number; url: string; head: string; + title?: string; + body?: string; state: string; merged: boolean; closedBy?: string; @@ -227,6 +229,8 @@ const execute: GitHubCli.GitHubCliShape["execute"] = (input) => { number, url: `https://github.com/Threadlines/themes/pull/${number}`, head: body.head, + title: body.title, + body: body.body, state: "open", merged: false, }; @@ -539,6 +543,8 @@ it.layer(TestLayer)("ThemeShowcase", (it) => { pullRequestUrl: null, state: "inReview", takenBack: null, + updateBaseSha: null, + publishedFileSha: null, createdAt: "2026-11-09T12:00:00.000Z", checkedAt: null, }); @@ -756,4 +762,181 @@ it.layer(TestLayer)("ThemeShowcase", (it) => { assert.isTrue(ready.problems.some((problem) => problem.includes("VS Code"))); }), ); + + it.effect( + "updates an already-listed Showcase theme in place without touching meta.json, and tracks review until rebuilt", + () => + Effect.gen(function* () { + const showcase = yield* ThemeShowcase; + const library = yield* ThemeLibrary; + const original: ThemeManifest = { + ...harbor, + name: "Harbor Glow", + colors: { ...harbor.colors, accent: "#3b9eff" }, + credits: { author: "Octo", license: "CC-BY-4.0" }, + }; + const saved = yield* library.save({ manifest: original }); + const originalFile = new TextEncoder().encode(`${JSON.stringify(original, null, 2)}\n`); + const listedEntry = { + ...(yield* Effect.promise(() => entryFor("harbor-glow", original, originalFile))), + sharedBy: "octocat", + featured: true, + }; + const someoneElses = { + ...(yield* Effect.promise(() => + entryFor( + "other-glow", + { ...original, name: "Other Glow", colors: { ...harbor.colors, accent: "#ff77aa" } }, + originalFile, + ), + )), + sharedBy: "sam", + }; + setIndex([listedEntry, someoneElses]); + + // Unchanged theme is refused without opening a pull request. + const writesBefore = github.writes.length; + const unchanged = yield* failure( + showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000001", + login: "octocat", + updateSlug: "harbor-glow", + }), + ); + assert.match(unchanged.detail, /already up to date/); + assert.deepStrictEqual(github.writes.slice(writesBefore), []); + + // Updating another account's folder is refused before writing anything. + const notOwner = yield* failure( + showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000002", + login: "octocat", + updateSlug: "other-glow", + }), + ); + assert.match(notOwner.detail, /Only @sam can update Other Glow/); + assert.deepStrictEqual(github.writes.slice(writesBefore), []); + + // Updating a missing folder is refused. + const missing = yield* failure( + showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000003", + login: "octocat", + updateSlug: "gone-theme", + }), + ); + assert.match(missing.detail, /isn't in the Showcase anymore/); + + // Edit the accent color and update in place. + const edited: ThemeManifest = { + ...original, + colors: { ...original.colors, accent: "#3b76ff" }, + }; + yield* library.replace({ entryId: saved.entryId, manifest: edited }); + const treesBefore = github.trees.length; + const updated = yield* showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000004", + login: "octocat", + updateSlug: "harbor-glow", + }); + assert.strictEqual(updated.state, "inReview"); + assert.strictEqual(updated.slug, "harbor-glow"); + assert.strictEqual(updated.isUpdate, true); + const tree = github.trees[treesBefore]!; + assert.deepStrictEqual( + tree.tree.map((item) => item.path), + ["themes/harbor-glow/theme.threadlines-theme", "themes/harbor-glow/thumbnail.png"], + ); + const pull = github.pulls.find((candidate) => candidate.url === updated.pullRequestUrl)!; + assert.strictEqual(pull.title, "Update Harbor Glow"); + assert.match(pull.body ?? "", /^Updates \*\*Harbor Glow\*\* in the Showcase/); + assert.deepInclude(recorded.at(-1), { event: "theme.showcase.shared" }); + assert.strictEqual((recorded.at(-1)?.properties as { updated?: boolean }).updated, true); + + // Merged, before the index rebuilds: still in review because the old file digest is still on main. + pull.state = "closed"; + pull.merged = true; + clock += 10 * 60_000; + const beforeRebuild = (yield* showcase.submissions).submissions.find( + (row) => row.submissionId === "update000004", + )!; + assert.strictEqual(beforeRebuild.state, "inReview"); + + // Taking back an already-merged update says the update is already in the Showcase. + const alreadyMerged = yield* failure(showcase.takeBack({ submissionId: "update000004" })); + assert.match(alreadyMerged.detail, /update is already in the Showcase/); + + // Once the index rebuilds with the new file digest, the update becomes listed. + const editedFile = github.blobs.find((b) => b.sha === tree.tree[0]!.sha)!.bytes; + const rebuiltEntry = { + ...(yield* Effect.promise(() => entryFor("harbor-glow", edited, editedFile))), + sharedBy: "octocat", + featured: true, + }; + setIndex([rebuiltEntry]); + clock += 40 * 60_000; + const afterRebuild = (yield* showcase.submissions).submissions.find( + (row) => row.submissionId === "update000004", + )!; + assert.strictEqual(afterRebuild.state, "listed"); + + // A rename-only update keeps the same content hash but changes the file digest: + // it must stay in review while open, even if another rename lands on main. + yield* library.rename({ entryId: saved.entryId, name: "Harbor Deep" }); + const renamed = yield* showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000005", + login: "octocat", + updateSlug: "harbor-glow", + }); + assert.strictEqual(renamed.state, "inReview"); + assert.strictEqual(renamed.publishedHash, rebuiltEntry.hash); + const otherRenameFile = new TextEncoder().encode( + `${JSON.stringify({ ...edited, name: "Harbor Other" }, null, 2)}\n`, + ); + const otherRenameEntry = { + ...(yield* Effect.promise(() => + entryFor("harbor-glow", { ...edited, name: "Harbor Other" }, otherRenameFile), + )), + sharedBy: "octocat", + featured: true, + }; + setIndex([otherRenameEntry]); + clock += 40 * 60_000; + const renameStillOpen = (yield* showcase.submissions).submissions.find( + (row) => row.submissionId === "update000005", + )!; + assert.strictEqual(renameStillOpen.state, "inReview"); + + // A second rename while the first rename PR is open opens a new PR instead of returning the first. + yield* library.rename({ entryId: saved.entryId, name: "Harbor Midnight" }); + const renamedAgain = yield* showcase.submit({ + entryId: saved.entryId, + credits: null, + includePrompt: false, + submissionId: "update000006", + login: "octocat", + updateSlug: "harbor-glow", + }); + assert.notStrictEqual(renamedAgain.pullRequestUrl, renamed.pullRequestUrl); + + // Taking back the open rename update closes only the update PR. + const takenBack = yield* showcase.takeBack({ submissionId: "update000005" }); + assert.deepInclude(takenBack, { state: "notAdded", takenBack: true, isUpdate: true }); + }), + ); }); diff --git a/apps/server/src/themes/ThemeShowcase.ts b/apps/server/src/themes/ThemeShowcase.ts index 40ea8dcca..324544781 100644 --- a/apps/server/src/themes/ThemeShowcase.ts +++ b/apps/server/src/themes/ThemeShowcase.ts @@ -260,10 +260,12 @@ const toSubmission = (row: ThemeShowcaseSubmissionRow): ThemeShowcaseSubmission entryId: row.entryId, sourceHash: row.sourceHash, publishedHash: row.publishedHash, + slug: row.slug, login: row.login, pullRequestUrl: row.pullRequestUrl, state: row.state, ...(row.state === "notAdded" && row.takenBack === true ? { takenBack: true } : {}), + ...(row.updateBaseSha !== null ? { isUpdate: true } : {}), createdAt: row.createdAt, }; @@ -272,11 +274,14 @@ function pullRequestBody(input: { readonly manifest: ThemeManifest; readonly fonts: ReadonlyArray; readonly submissionId: string; + readonly isUpdate: boolean; }): string { const { manifest, fonts } = input; const credits = manifest.credits; const lines = [ - `Adds **${manifest.name}** to the Showcase, shared from Threadlines.`, + input.isUpdate + ? `Updates **${manifest.name}** in the Showcase, shared from Threadlines.` + : `Adds **${manifest.name}** to the Showcase, shared from Threadlines.`, "", `- License: ${credits?.license ?? "none"}`, `- Credit: ${[credits?.author, credits?.link].filter(Boolean).join(", ") || "none"}`, @@ -789,6 +794,15 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( const own = rows.find((row) => row.submissionId === input.submissionId); const settled = own === undefined ? null : toSubmission(own); if (settled !== null) return settled; + if ( + own !== undefined && + ((own.updateBaseSha !== null) !== (input.updateSlug !== undefined) || + (own.updateBaseSha !== null && own.slug !== input.updateSlug)) + ) { + return yield* showcaseError( + "This share already started for a different Showcase target.", + ); + } const share = yield* buildShare(input); if (share.problems.length > 0 || share.pictureBytes === null) { @@ -797,7 +811,8 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( ); } // The list says which folders are taken and what's already there: share only against a fresh one. - const showcase = yield* list({}); + // An update refreshes the list so it checks the latest owner and file digest on main. + const showcase = yield* list(input.updateSlug === undefined ? {} : { refresh: true }); if (showcase.issue !== null) { return yield* showcaseError( showcase.issue === "updateNeeded" @@ -805,14 +820,48 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( : "Couldn't reach the Showcase. Check your connection and try again.", ); } - if (showcase.themes.some((entry) => entry.hash === share.hash)) { + const encode = (text: string) => new TextEncoder().encode(text); + const fileBytes = encode(themeFileText(share.manifest)); + const fileSha = yield* Effect.promise(() => sha256Hex(fileBytes)); + const target = + input.updateSlug === undefined + ? null + : (showcase.themes.find((entry) => entry.id === input.updateSlug) ?? null); + if (input.updateSlug !== undefined && target === null) { + return yield* showcaseError("That theme isn't in the Showcase anymore."); + } + if (target !== null) { + if (target.sharedBy === null) { + return yield* showcaseError( + `${target.name} wasn't shared from a GitHub account, so it can't be updated here.`, + ); + } + if (target.sharedBy.toLowerCase() !== input.login.toLowerCase()) { + return yield* showcaseError( + `Only @${target.sharedBy} can update ${target.name} in the Showcase.`, + ); + } + if ( + showcase.themes.some((entry) => entry.id !== target.id && entry.hash === share.hash) + ) { + return yield* showcaseError("This theme is already in the Showcase."); + } + if (share.hash === target.hash && fileSha === target.file.sha256) { + return yield* showcaseError("This theme is already up to date in the Showcase."); + } + } else if (showcase.themes.some((entry) => entry.hash === share.hash)) { return yield* showcaseError("This theme is already in the Showcase."); } const inReview = rows.find( (row) => - row.publishedHash === share.hash && row.state === "inReview" && - row.pullRequestUrl !== null, + row.pullRequestUrl !== null && + (row.publishedFileSha !== null + ? row.publishedFileSha === fileSha + : row.publishedHash === share.hash) && + (target === null + ? row.updateBaseSha === null + : row.slug === target.id && row.updateBaseSha !== null), ); const reviewing = inReview === undefined ? null : toSubmission(inReview); if (reviewing !== null) return reviewing; @@ -822,13 +871,32 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( // and the pull request GitHub may have opened from it, are found, not made twice. const before = own ?? - rows.find((row) => row.pullRequestUrl === null && row.entryId === share.entry.entryId); + rows.find( + (row) => + row.pullRequestUrl === null && + row.entryId === share.entry.entryId && + (target === null + ? row.updateBaseSha === null + : row.slug === target.id && row.updateBaseSha !== null), + ); const submissionId = before?.submissionId ?? input.submissionId; const branch = `showcase/${submissionId}`; const account = yield* expectLogin(input.login, { uncertain: before !== undefined }); + if ( + target !== null && + target.sharedBy !== null && + target.sharedBy.toLowerCase() !== account.login.toLowerCase() + ) { + return yield* showcaseError( + `Only @${target.sharedBy} can update ${target.name} in the Showcase.`, + ); + } const slug = + target?.id ?? before?.slug ?? showcaseSlugFor(share.manifest.name, new Set(showcase.themes.map((entry) => entry.id))); + const updateBaseSha = + target === null ? null : (before?.updateBaseSha ?? target.file.sha256); const row: ThemeShowcaseSubmissionRow = { submissionId, entryId: share.entry.entryId, @@ -840,6 +908,8 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( pullRequestUrl: null, state: "inReview", takenBack: null, + updateBaseSha, + publishedFileSha: fileSha, createdAt: before?.createdAt ?? (yield* nowIso), checkedAt: null, }; @@ -860,6 +930,7 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( ...themeAnalyticsProperties(share.manifest), license: share.manifest.credits?.license ?? "none", prompt: share.manifest.prompt !== undefined, + ...(holds.updateBaseSha !== null ? { updated: true } : {}), }); return toSubmission(done) ?? (yield* showcaseError(REASONS.unreachable)); }); @@ -875,32 +946,39 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( yield* storedShares(submissionsRepo.put(row)); const fork = yield* forkFor(input.login); - const encode = (text: string) => new TextEncoder().encode(text); + const isUpdate = updateBaseSha !== null; + const actionTitle = isUpdate + ? `Update ${share.manifest.name}` + : `Add ${share.manifest.name}`; + // An update leaves meta.json (sharedBy, featured) and NOTICE.md alone on main. + const files = [ + { path: `themes/${slug}/theme.threadlines-theme`, bytes: fileBytes }, + { path: `themes/${slug}/thumbnail.png`, bytes: share.pictureBytes }, + ...(isUpdate + ? [] + : [ + { + path: `themes/${slug}/meta.json`, + bytes: encode(`${JSON.stringify({ sharedBy: fork.owner }, null, 2)}\n`), + }, + ]), + ]; yield* pushBranch({ fork: fork.name, branch, - message: `Add ${share.manifest.name}`, + message: actionTitle, author: account, - files: [ - { - path: `themes/${slug}/theme.threadlines-theme`, - bytes: encode(themeFileText(share.manifest)), - }, - { path: `themes/${slug}/thumbnail.png`, bytes: share.pictureBytes }, - { - path: `themes/${slug}/meta.json`, - bytes: encode(`${JSON.stringify({ sharedBy: fork.owner }, null, 2)}\n`), - }, - ], + files, }); const pullRequest = yield* openPullRequest({ login: input.login, head: `${fork.owner}:${branch}`, - title: `Add ${share.manifest.name}`, + title: actionTitle, body: pullRequestBody({ manifest: share.manifest, fonts: share.fonts, submissionId, + isUpdate, }), }); return yield* settle(pullRequest, row); @@ -938,12 +1016,27 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( */ const recheck = ( row: ThemeShowcaseSubmissionRow, - listed: { readonly hashes: ReadonlySet; readonly ids: ReadonlySet }, + listed: { + readonly hashes: ReadonlySet; + readonly byId: ReadonlyMap; + }, ) => Effect.gen(function* () { const known = { state: row.state, takenBack: row.takenBack }; - if (listed.hashes.has(row.publishedHash)) - return { state: "listed", takenBack: null } as const; + if (row.updateBaseSha === null) { + if (listed.hashes.has(row.publishedHash)) { + return { state: "listed", takenBack: null } as const; + } + } else { + const entry = listed.byId.get(row.slug); + if ( + entry !== undefined && + row.publishedFileSha !== null && + entry.file.sha256 === row.publishedFileSha + ) { + return { state: "listed", takenBack: null } as const; + } + } if (row.pullRequestNumber === null) return known; const pulls = `repos/${THEME_SHOWCASE_REPOSITORY}/pulls/${row.pullRequestNumber}`; const pull = Option.getOrUndefined( @@ -954,8 +1047,13 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( if (pull === undefined) return known; // Merged but not in the list yet (the list rebuilds after a merge): still on its way. if (pull.merged) { + const entry = listed.byId.get(row.slug); + const landed = + row.updateBaseSha === null + ? entry !== undefined + : entry !== undefined && entry.file.sha256 !== row.updateBaseSha; return { - state: listed.ids.has(row.slug) ? "listed" : "inReview", + state: landed ? "listed" : "inReview", takenBack: null, } as const; } @@ -977,7 +1075,7 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( const showcase = yield* list({}); const listed = { hashes: new Set(showcase.themes.map((entry) => entry.hash)), - ids: new Set(showcase.themes.map((entry) => entry.id)), + byId: new Map(showcase.themes.map((entry) => [entry.id, entry])), }; const checkedAt = yield* nowIso; yield* Effect.forEach( @@ -1014,7 +1112,9 @@ export const makeThemeShowcase = Effect.fn("ThemeShowcase.make")(function* ( if (row.state === "notAdded" && row.takenBack !== null) return settled; const added = () => showcaseError( - "It's already in the Showcase. To have it removed, open a takedown request in the Threadlines/themes repository on GitHub.", + row.updateBaseSha !== null + ? "That update is already in the Showcase." + : "It's already in the Showcase. To have it removed, open a takedown request in the Threadlines/themes repository on GitHub.", ); if (row.state === "listed") return yield* added(); // Only the account that opened the pull request (or a maintainer) can close it. diff --git a/apps/server/src/themes/ThemeShowcaseRepository.ts b/apps/server/src/themes/ThemeShowcaseRepository.ts index 9ecbd9faa..d1f04c972 100644 --- a/apps/server/src/themes/ThemeShowcaseRepository.ts +++ b/apps/server/src/themes/ThemeShowcaseRepository.ts @@ -41,6 +41,13 @@ export const ThemeShowcaseSubmissionRow = Schema.Struct({ * its pull request. Null while that isn't known (or doesn't apply). */ takenBack: Schema.NullOr(Schema.BooleanFromBit), + /** + * For a share that updates an already-listed Showcase theme: the SHA-256 of + * the theme file on `main` when the update started. Null for new themes. + */ + updateBaseSha: Schema.NullOr(Schema.String), + /** SHA-256 of the exact `theme.threadlines-theme` bytes this share writes; null on older rows. */ + publishedFileSha: Schema.NullOr(Schema.String), createdAt: Schema.String, /** When the pull request's state was last looked up. */ checkedAt: Schema.NullOr(Schema.String), @@ -88,6 +95,8 @@ const make = Effect.gen(function* () { pull_request_url AS "pullRequestUrl", state AS "state", taken_back AS "takenBack", + update_base_sha AS "updateBaseSha", + published_file_sha AS "publishedFileSha", created_at AS "createdAt", checked_at AS "checkedAt" FROM theme_showcase_submissions @@ -114,7 +123,8 @@ const make = Effect.gen(function* () { sql` INSERT INTO theme_showcase_submissions ( submission_id, entry_id, source_hash, published_hash, slug, login, - pull_request_number, pull_request_url, state, taken_back, created_at, checked_at + pull_request_number, pull_request_url, state, taken_back, update_base_sha, + published_file_sha, created_at, checked_at ) VALUES ( ${row.submissionId}, ${row.entryId}, @@ -126,6 +136,8 @@ const make = Effect.gen(function* () { ${row.pullRequestUrl}, ${row.state}, ${row.takenBack === null ? null : row.takenBack ? 1 : 0}, + ${row.updateBaseSha}, + ${row.publishedFileSha}, ${row.createdAt}, ${row.checkedAt} ) @@ -139,6 +151,8 @@ const make = Effect.gen(function* () { pull_request_url = excluded.pull_request_url, state = excluded.state, taken_back = excluded.taken_back, + update_base_sha = excluded.update_base_sha, + published_file_sha = excluded.published_file_sha, created_at = excluded.created_at, checked_at = excluded.checked_at `.pipe(Effect.asVoid, wrap("put")); diff --git a/apps/web/src/components/theme/ui/ThemeCreditsFields.tsx b/apps/web/src/components/theme/ui/ThemeCreditsFields.tsx index e71151dec..924d422b5 100644 --- a/apps/web/src/components/theme/ui/ThemeCreditsFields.tsx +++ b/apps/web/src/components/theme/ui/ThemeCreditsFields.tsx @@ -45,6 +45,8 @@ export function useThemeCreditsDraft( manifest: ThemeManifest, /** What to say under credits a theme keeps. */ keepsLine: string, + /** Credits from an existing Showcase theme being updated, used until the person edits them. */ + fallbackCredits?: ThemeCredits | null, ): ThemeCreditsDraft { const [remembered, setRemembered] = useLocalStorage( REMEMBERED_CREDITS_KEY, @@ -52,13 +54,17 @@ export function useThemeCreditsDraft( ThemeCredits, ); const own = cleanThemeCredits(manifest.credits); - const [author, setAuthor] = useState(remembered.author ?? ""); - const [link, setLink] = useState(remembered.link ?? ""); - const [license, setLicense] = useState( - remembered.license !== undefined && remembered.license !== "MIT" - ? remembered.license - : "CC-BY-4.0", - ); + const [draft, setDraft] = useState<{ + readonly author: string; + readonly link: string; + readonly license: ThemeLicense; + } | null>(null); + const base = cleanThemeCredits(fallbackCredits) ?? remembered; + const baseLicense: ThemeLicense = + base.license !== undefined && base.license !== "MIT" ? base.license : "CC-BY-4.0"; + const author = draft?.author ?? base.author ?? ""; + const link = draft?.link ?? base.link ?? ""; + const license = draft?.license ?? baseLicense; const given = cleanThemeCredits({ ...(author.trim() ? { author } : {}), ...(link.trim() ? { link } : {}), @@ -81,7 +87,7 @@ export function useThemeCreditsDraft( value={author} maxLength={60} placeholder="Your name" - onChange={(event) => setAuthor(event.target.value)} + onChange={(event) => setDraft({ author: event.target.value, link, license })} /> setLink(event.target.value)} + onChange={(event) => setDraft({ author, link: event.target.value, license })} /> { + if (next === null || uncertain || sending.state === "sending") return; + setPickedTarget( + next === NEW_SHOWCASE_TARGET + ? NEW_SHOWCASE_TARGET + : (next as ThemeShowcaseSlug), + ); + if (sending.state === "idle") { + setSubmissionId(newShowcaseSubmissionId()); + setSending({ state: "idle", error: null, uncertain: false }); + } + }} + > + + + {target !== null ? `Update ${target.name}` : "Share as a new theme"} + + + + Share as a new theme + {owned.map((entry) => ( + + Update {entry.name} + + ))} + + + + ) : null} {credits.fields} @@ -404,6 +530,7 @@ export function ThemeTakeBackDialog({ }) { const [taking, setTaking] = useState(false); const [error, setError] = useState(null); + const isUpdate = submission.isUpdate === true; const takeBack = () => { setTaking(true); setError(null); @@ -412,7 +539,12 @@ export function ThemeTakeBackDialog({ // A maintainer may have closed it first: then it wasn't taken back, and the tile says so. toastManager.add( taken.takenBack === true - ? { type: "success", title: `${name} was taken back from the Showcase` } + ? { + type: "success", + title: isUpdate + ? `Update to ${name} was taken back` + : `${name} was taken back from the Showcase`, + } : { type: "info", title: `${name}'s pull request was already closed` }, ); onClose(); @@ -430,10 +562,13 @@ export function ThemeTakeBackDialog({ (open ? undefined : onClose())}> - Take {name} back? + + {isUpdate ? `Take back update to ${name}?` : `Take ${name} back?`} + - It won't be added to the Showcase, and you can share it again any time. Its closed pull - request stays on GitHub. + {isUpdate + ? "The current version stays in the Showcase, and you can send an update again any time. Its closed pull request stays on GitHub." + : "It won't be added to the Showcase, and you can share it again any time. Its closed pull request stays on GitHub."} {error !== null ? ( diff --git a/apps/web/src/components/theme/ui/ThemeShowcaseView.tsx b/apps/web/src/components/theme/ui/ThemeShowcaseView.tsx index 1040bd2cb..be21ba843 100644 --- a/apps/web/src/components/theme/ui/ThemeShowcaseView.tsx +++ b/apps/web/src/components/theme/ui/ThemeShowcaseView.tsx @@ -49,7 +49,7 @@ function ShowcaseTile({ readonly entry: ThemeShowcaseEntry; readonly selected: boolean; }) { - const picture = useShowcasePicture(environmentId, entry.id); + const picture = useShowcasePicture(environmentId, entry.id, entry.thumbnail.sha256); const [opening, setOpening] = useState(false); return ( (); /** A theme's picture, fetched once it's asked for; null until then, "failed" if it couldn't be. */ -export function useShowcasePicture(environmentId: EnvironmentId | null, id: string): string | null { - const picture = useShowcaseStore((state) => state.pictures[id] ?? null); +export function useShowcasePicture( + environmentId: EnvironmentId | null, + id: string, + /** The thumbnail's digest from `index.json`, so an updated theme fetches its new picture. */ + digest: string, +): string | null { + const key = `${id}:${digest}`; + const picture = useShowcaseStore((state) => state.pictures[key] ?? null); useEffect(() => { - if (environmentId === null || picture !== null || asked.has(id)) return; - asked.add(id); + if (environmentId === null || picture !== null || asked.has(key)) return; + asked.add(key); void clientOf(environmentId) .picture({ id }) .then(({ dataUrl }) => dataUrl) .catch(() => "failed") .then((value) => { - if (value === "failed") asked.delete(id); - useShowcaseStore.setState((state) => ({ pictures: { ...state.pictures, [id]: value } })); + if (value === "failed") asked.delete(key); + useShowcaseStore.setState((state) => ({ pictures: { ...state.pictures, [key]: value } })); }); - }, [environmentId, id, picture]); + }, [environmentId, id, key, picture]); return picture; } @@ -126,6 +134,19 @@ export function readShowcaseAccount( })); } +/** Fresh Showcase entries for matching an existing theme to update; falls back to cached entries offline. */ +export async function readShowcaseEntries( + environmentId: EnvironmentId, +): Promise> { + try { + const listing = await clientOf(environmentId).list({ refresh: true }); + useShowcaseStore.setState({ listing }); + return listing.themes; + } catch { + return useShowcaseStore.getState().listing?.themes ?? []; + } +} + /** What sharing a library theme would publish, worked out on a computer that holds it. */ export function prepareShowcaseShare( environmentId: EnvironmentId, @@ -134,10 +155,10 @@ export function prepareShowcaseShare( return clientOf(environmentId).prepare(input); } -/** Shares it: a pull request from the GitHub account the person saw (`login`). */ +/** Shares or updates a theme: a pull request from the GitHub account the person saw (`login`). */ export async function submitShowcaseShare( environmentId: EnvironmentId, - input: ThemeShowcaseShareInput & { readonly submissionId: string; readonly login: string }, + input: ThemeShowcaseSubmitInput, ): Promise { const submission = await clientOf(environmentId).submit(input); useShowcaseStore.setState((state) => ({ @@ -181,6 +202,8 @@ export const newShowcaseSubmissionId = () => randomUUID().replaceAll("-", "").sl export interface ShowcaseShare { readonly submission: ThemeShowcaseSubmission; readonly environmentId: EnvironmentId; + /** The folder this theme was previously listed under, if known on any connected computer. */ + readonly listedSlug?: ThemeShowcaseSlug; } /** @@ -204,6 +227,10 @@ export function useShowcaseShares(): ReadonlyMap { }, [environments]); return useMemo(() => { const newest = new Map(); + const listed = new Map< + string, + { readonly slug: ThemeShowcaseSlug; readonly createdAt: string } + >(); for (const [environmentId, list] of Object.entries(shares)) { for (const submission of list) { const seen = newest.get(submission.entryId); @@ -213,6 +240,24 @@ export function useShowcaseShares(): ReadonlyMap { environmentId: environmentId as EnvironmentId, }); } + if ( + submission.slug !== undefined && + (submission.state === "listed" || submission.isUpdate === true) + ) { + const prior = listed.get(submission.entryId); + if (prior === undefined || submission.createdAt > prior.createdAt) { + listed.set(submission.entryId, { + slug: submission.slug, + createdAt: submission.createdAt, + }); + } + } + } + } + for (const [entryId, share] of newest) { + const slug = listed.get(entryId)?.slug; + if (slug !== undefined) { + newest.set(entryId, { ...share, listedSlug: slug }); } } return newest; @@ -221,14 +266,17 @@ export function useShowcaseShares(): ReadonlyMap { /** What a shared theme's tile says under its name. */ export function showcaseShareWords( - share: Pick, + share: Pick, ): string { switch (share.state) { case "inReview": - return "In review for the Showcase"; + return share.isUpdate === true ? "Update in review" : "In review for the Showcase"; case "listed": return "In the Showcase"; case "notAdded": + if (share.isUpdate === true) { + return share.takenBack === true ? "Update taken back" : "Update not added"; + } return share.takenBack === true ? "Taken back from the Showcase" : "Not added to the Showcase"; diff --git a/docs/design/custom-themes.md b/docs/design/custom-themes.md index 66f8cb111..3346c2f07 100644 --- a/docs/design/custom-themes.md +++ b/docs/design/custom-themes.md @@ -996,6 +996,23 @@ that do this, and that share without the email, report `themeShowcaseTakeBack`; for an older one the menu item is hidden and the share dialog adds a line saying the email shows. +**Updating a listed theme** (`ThemeShowcaseSubmitInput.updateSlug`, capability +`themeShowcaseUpdate`, `update_base_sha` and `published_file_sha` in migration +125). When the signed-in GitHub account already owns themes in the Showcase +(`sharedBy` matches), the share dialog offers a Showcase picker defaulting to +updating the matching folder (by the entry's prior listed submission or by its +base slug) while still letting the user share as a new theme. A library theme +already listed shows Update in Showcase… in its menu. An update commit touches +only `themes//theme.threadlines-theme` and `themes//thumbnail.png`, +leaving `meta.json` (`sharedBy`, `featured`) and `NOTICE.md` intact on main, +and refuses if nothing changed on disk or another account owns the folder. +Recording both the pre-update digest (`update_base_sha`) and the submitted file +digest (`published_file_sha`) keeps an in-review update (even a rename-only or +prompt-only one) in review until its own merge and index rebuild land, and +Take back update… closes only the update pull request without affecting the +live theme. Showcase tiles key their cached thumbnail by `(slug, digest)` so an +updated theme's new thumbnail appears as soon as the index refreshes. + **Takedown.** An issue form in the repository; maintainers remove the folder. ## Editing colors diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 86dd48660..d4e7a4d0d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -85,6 +85,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * the GitHub account's email. Absent on servers from before both. */ themeShowcaseTakeBack: Schema.optionalKey(Schema.Boolean), + /** + * The server updates an already-listed Showcase theme in place + * (`ThemeShowcaseSubmitInput.updateSlug`). Absent on older servers, which + * always open a new folder. + */ + themeShowcaseUpdate: Schema.optionalKey(Schema.Boolean), /** The server searches the Open VSX store for VS Code themes (`themeVsCode.*`). */ themeVsCode: Schema.optionalKey(Schema.Boolean), /** The server moves threads to linked computers. Absent until a server ships it. */ diff --git a/packages/contracts/src/themeShowcase.ts b/packages/contracts/src/themeShowcase.ts index 3f51aa4c1..30de3ab38 100644 --- a/packages/contracts/src/themeShowcase.ts +++ b/packages/contracts/src/themeShowcase.ts @@ -148,6 +148,11 @@ export const ThemeShowcaseSubmitInput = Schema.Struct({ submissionId: ThemeShowcaseSubmissionId, /** The account the person saw; the server refuses to post as anyone else. */ login: GitHubLogin, + /** + * When updating a theme already in the Showcase, its folder (`id` in the + * Showcase list). Omitted for a new share. + */ + updateSlug: Schema.optional(ThemeShowcaseSlug), }); export type ThemeShowcaseSubmitInput = typeof ThemeShowcaseSubmitInput.Type; @@ -162,11 +167,15 @@ export const ThemeShowcaseSubmission = Schema.Struct({ /** The library theme it came from, and the file it published (credits and still added). */ sourceHash: ThemeContentHash, publishedHash: ThemeContentHash, + /** The Showcase folder this share targeted; older servers omit it. */ + slug: Schema.optional(ThemeShowcaseSlug), login: GitHubLogin, pullRequestUrl: Schema.String, state: ThemeShowcaseSubmissionState, /** Not added because the person who shared it closed its pull request (Take back, or on GitHub). */ takenBack: Schema.optional(Schema.Boolean), + /** True when this share updates an already-listed Showcase theme instead of adding one. */ + isUpdate: Schema.optional(Schema.Boolean), createdAt: Schema.String, }); export type ThemeShowcaseSubmission = typeof ThemeShowcaseSubmission.Type; diff --git a/scripts/theme-showcase.test.ts b/scripts/theme-showcase.test.ts index 62566afa5..bba6a3527 100644 --- a/scripts/theme-showcase.test.ts +++ b/scripts/theme-showcase.test.ts @@ -143,4 +143,29 @@ describe("theme-showcase", () => { (await checkShowcaseRepository(repo, { base, author: "will", trusted: true })).size, ).toBe(0); }); + + it("lets an outside author update their own featured theme without changing featured", async () => { + fresh(); + writeTheme("harbor", harbor, { sharedBy: "sam", featured: true }); + const base = commit(); + + // Editing theme.threadlines-theme while leaving featured: true intact passes. + writeTheme( + "harbor", + { ...harbor, colors: { ...harbor.colors, accent: "#3b76ff" } }, + { sharedBy: "sam", featured: true }, + ); + commit(); + expect((await checkShowcaseRepository(repo, { base, author: "sam" })).size).toBe(0); + + // Flipping featured off is still refused for an outside author. + writeTheme( + "harbor", + { ...harbor, colors: { ...harbor.colors, accent: "#3b76ff" } }, + { sharedBy: "sam", featured: false }, + ); + commit(); + const problems = await checkShowcaseRepository(repo, { base, author: "sam" }); + expect(problems.get("themes/harbor")).toEqual(["Only maintainers feature a theme."]); + }); }); diff --git a/scripts/theme-showcase.ts b/scripts/theme-showcase.ts index 9be7a07aa..a53cb71c6 100644 --- a/scripts/theme-showcase.ts +++ b/scripts/theme-showcase.ts @@ -260,7 +260,8 @@ export async function checkShowcaseRepository( } catch { // A new folder. } - if (before !== null && readMeta(before).meta.sharedBy?.toLowerCase() !== author) { + const beforeMeta = before === null ? null : readMeta(before).meta; + if (beforeMeta !== null && beforeMeta.sharedBy?.toLowerCase() !== author) { note(`themes/${slug}`, "Only the person who shared a theme may change it."); } const theme = themes.get(slug); @@ -276,7 +277,9 @@ export async function checkShowcaseRepository( `meta.json says @${theme.meta.sharedBy} shared it, but @${options.author} opened this.`, ); } - if (theme.meta.featured) note(`themes/${slug}`, "Only maintainers feature a theme."); + if (theme.meta.featured !== (beforeMeta?.featured ?? false)) { + note(`themes/${slug}`, "Only maintainers feature a theme."); + } } } return found;