TypeScript
feat(web): ask for a GitHub star when idle, and star in one click (#29922)
Theo Browne5d3d78ab932b
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 7bb8bf8a34c..17940b83717 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -142,6 +142,7 @@ const RPC_AGGREGATES = {[WS_METHODS.sourceControlSignInCancel]: "source-control",[WS_METHODS.sourceControlAppAccess]: "source-control",[WS_METHODS.sourceControlStarred]: "source-control",+ [WS_METHODS.sourceControlStar]: "source-control",[WS_METHODS.projectCloneStart]: "source-control",[WS_METHODS.projectCloneCancel]: "source-control",[WS_METHODS.projectCloneRetry]: "source-control",diff --git a/apps/server/src/sourceControl/SourceControlSignIn.ts b/apps/server/src/sourceControl/SourceControlSignIn.tsindex 3dd9ca03e20..31f7837322f 100644--- a/apps/server/src/sourceControl/SourceControlSignIn.ts+++ b/apps/server/src/sourceControl/SourceControlSignIn.ts@@ -28,6 +28,7 @@ export class SourceControlSignIn extends Context.Service<) => Effect.Effect<void, SourceControlSignInError>;readonly access: (input: SourceControlAppAccessInput) => Effect.Effect<SourceControlAppAccess>;readonly starred: (input: SourceControlStarredInput) => Effect.Effect<boolean>;+ readonly star: (input: SourceControlStarredInput) => Effect.Effect<boolean>;}>()("t3/sourceControl/SourceControlSignIn") {}@@ -70,6 +71,11 @@ const make = Effect.gen(function* () {.isRepositoryStarred;return isStarred === undefined ? false : yield* isStarred(input.host, input.repository);}),+ star: Effect.fn("SourceControlSignIn.star")(function* (input) {+ const star = drivers.find(({ driver }) => driver.kind === input.provider)?.instance+ .starRepository;+ return star === undefined ? false : yield* star(input.host, input.repository);+ }),});});diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 0016aa0063b..492764c6ae5 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -2749,6 +2749,7 @@ export const layerWsRpc = ([WS_METHODS.sourceControlSignInCancel]: (input) => sourceControlSignIn.cancel(input),[WS_METHODS.sourceControlAppAccess]: (input) => sourceControlSignIn.access(input),[WS_METHODS.sourceControlStarred]: (input) => sourceControlSignIn.starred(input),+ [WS_METHODS.sourceControlStar]: (input) => sourceControlSignIn.star(input),[WS_METHODS.projectCloneStart]: (input) =>projectCloneTracker.start(input, {createProject: (project) =>diff --git a/apps/web/src/components/GitHubStarPrompt.test.ts b/apps/web/src/components/GitHubStarPrompt.test.tsindex 9dbe023b2d5..f45229d5ce8 100644--- a/apps/web/src/components/GitHubStarPrompt.test.ts+++ b/apps/web/src/components/GitHubStarPrompt.test.ts@@ -3,29 +3,54 @@ import { describe, expect, it, vi } from "vite-plus/test";import type { toastManager } from "./ui/toast";-const { add, starred } = vi.hoisted(() => ({+const { add, update, openExternal, commands, starred, page } = vi.hoisted(() => ({add: vi.fn<typeof toastManager.add>(),- starred: { value: false, failed: false, duringCheck: () => {} },+ update: vi.fn<typeof toastManager.update>(),+ openExternal: vi.fn(async (_url: string) => {}),+ commands: { checkStarred: {}, star: {} },+ starred: { value: false, failed: false, starWorks: true, duringCheck: () => {} },+ page: {+ focused: true,+ activeElement: null as { matches: (selector: string) => boolean } | null,+ events: new EventTarget(),+ },}));-vi.mock("./ui/toast", () => ({ toastManager: { add, close: vi.fn() } }));+vi.mock("./ui/toast", () => ({ toastManager: { add, update, close: vi.fn() } }));+vi.mock("../localApi", () => ({ readLocalApi: () => ({ shell: { openExternal } }) }));vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));-vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: { checkStarred: {} } }));+vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: commands }));vi.mock("@t3tools/client-runtime/state/runtime", () => ({- runAtomCommand: async () => {+ runAtomCommand: async (_registry: unknown, command: unknown) => {+ if (command === commands.star) return { _tag: "Success", value: starred.starWorks };starred.duringCheck();return starred.failed ? { _tag: "Failure" } : { _tag: "Success", value: starred.value };},}));const environmentId = EnvironmentId.make("environment-1");+const IDLE_MS = 30_000;function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) {add.mockReset();+ update.mockReset();+ openExternal.mockClear();starred.value = alreadyStarred;starred.failed = false;+ starred.starWorks = true;starred.duringCheck = () => {};+ page.focused = true;+ page.activeElement = null;+ page.events = new EventTarget();const store = new Map([["t3code:github-star-prompt:sent", String(sent)]]);+ vi.stubGlobal("document", {+ hasFocus: () => page.focused,+ get activeElement() {+ return page.activeElement;+ },+ });vi.stubGlobal("window", {+ addEventListener: page.events.addEventListener.bind(page.events),+ removeEventListener: page.events.removeEventListener.bind(page.events),localStorage: {getItem: (key: string) => store.get(key) ?? null,setItem: (key: string, value: string) => {@@ -41,10 +66,48 @@ function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) {async function startSession() {vi.resetModules();const session = await import("./GitHubStarPrompt");- return { send: () => session.recordPromptSent(environmentId) };+ return {+ // Sends a prompt, then leaves the page idle long enough to ask.+ send: async () => {+ const sent = session.recordPromptSent(environmentId);+ await vi.advanceTimersByTimeAsync(IDLE_MS);+ await sent;+ },+ sendWithoutWaiting: () => void session.recordPromptSent(environmentId),+ };}+// The toast's handlers ignore their click event.+const click = (props: unknown) => (props as { onClick: () => unknown }).onClick();+describe("recordPromptSent", () => {+ vi.useFakeTimers();++ it("asks only after the focused page is idle", async () => {+ setup({ sent: 5 });+ (await startSession()).sendWithoutWaiting();+ await vi.advanceTimersByTimeAsync(IDLE_MS - 1);+ page.events.dispatchEvent(new Event("keydown"));+ await vi.advanceTimersByTimeAsync(IDLE_MS - 1);+ expect(add).not.toHaveBeenCalled();++ page.focused = false;+ await vi.advanceTimersByTimeAsync(IDLE_MS);+ expect(add).not.toHaveBeenCalled();++ page.focused = true;+ page.activeElement = { matches: (selector) => selector.includes("iframe") };+ page.events.dispatchEvent(new Event("focus"));+ await vi.advanceTimersByTimeAsync(IDLE_MS);+ expect(add).not.toHaveBeenCalled();++ page.activeElement = null;+ page.events.dispatchEvent(new Event("pointerdown"));+ await vi.advanceTimersByTimeAsync(IDLE_MS);+ expect(add).toHaveBeenCalledOnce();+ vi.unstubAllGlobals();+ });+it("asks after five prompts, once per session, and never again once closed", async () => {setup();let session = await startSession();@@ -101,4 +164,35 @@ describe("recordPromptSent", () => {expect(add).not.toHaveBeenCalled();vi.unstubAllGlobals();});+ it("stars on click, opens GitHub when starring fails, and asks for a click once the click expired", async () => {+ setup({ sent: 5 });+ await (await startSession()).send();+ click(add.mock.lastCall?.[0].actionProps);+ await vi.advanceTimersByTimeAsync(0);+ expect(add.mock.lastCall?.[0].title).toBe("Thanks for the star!");+ expect(openExternal).not.toHaveBeenCalled();++ setup({ sent: 5 });+ starred.starWorks = false;+ await (await startSession()).send();+ click(add.mock.lastCall?.[0].actionProps);+ await vi.advanceTimersByTimeAsync(0);+ expect(openExternal).toHaveBeenCalledWith("https://github.com/pingdotgg/t3code");+ expect(update.mock.lastCall?.[1]).not.toMatchObject({+ actionProps: { children: "Open GitHub" },+ });++ setup({ sent: 5 });+ starred.starWorks = false;+ vi.stubGlobal("navigator", { userActivation: { isActive: false } });+ await (await startSession()).send();+ click(add.mock.lastCall?.[0].actionProps);+ await vi.advanceTimersByTimeAsync(0);+ const fallback = update.mock.lastCall?.[1];+ expect(fallback).toMatchObject({ actionProps: { children: "Open GitHub" } });+ expect(openExternal).not.toHaveBeenCalled();+ click(typeof fallback === "object" ? fallback.actionProps : undefined);+ expect(openExternal).toHaveBeenCalledOnce();+ vi.unstubAllGlobals();+ });});diff --git a/apps/web/src/components/GitHubStarPrompt.tsx b/apps/web/src/components/GitHubStarPrompt.tsxindex db8ddb4de20..f79714d7a89 100644--- a/apps/web/src/components/GitHubStarPrompt.tsx+++ b/apps/web/src/components/GitHubStarPrompt.tsx@@ -14,6 +14,9 @@ const SENT_KEY = "t3code:github-star-prompt:sent";const DISMISSED_KEY = "t3code:github-star-prompt:dismissed";const REPOSITORY = "pingdotgg/t3code";const PROMPTS_BEFORE_ASKING = 5;+const IDLE_MS = 30_000;+// User-driven actions (send, navigate, type, scroll) start with one of these; touch fires pointerdown.+const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "focus"] as const;let shownThisSession = false;@@ -24,22 +27,32 @@ function dismiss() {}// Every close path, including both buttons, runs `onClose`, which saves the dismissal.-function showStarPrompt() {+function showStarPrompt(environmentId: EnvironmentId) {const close = () => toastManager.close(id);+ const openInBrowser = () => {+ close();+ void readLocalApi()+ ?.shell.openExternal(`https://github.com/${REPOSITORY}`)+ .catch(() => undefined);+ };+ const starInPlace = async () => {+ toastManager.update(id, { actionProps: { children: "Starring…", disabled: true } });+ if (await starRepository(environmentId)) {+ close();+ toastManager.add({ type: "success", title: "Thanks for the star!", timeout: 4_000 });+ return;+ }+ // Browsers block new tabs once the click's activation expires; desktop opens through its bridge.+ if (window.desktopBridge || navigator.userActivation?.isActive !== false)+ return openInBrowser();+ toastManager.update(id, { actionProps: { children: "Open GitHub", onClick: openInBrowser } });+ };const id = toastManager.add({title: "Enjoying T3 Code?",description: "Give us a star on GitHub to let us know!",timeout: 0,onClose: dismiss,- actionProps: {- children: "Star on GitHub",- onClick: () => {- close();- void readLocalApi()- ?.shell.openExternal(`https://github.com/${REPOSITORY}`)- .catch(() => undefined);- },- },+ actionProps: { children: "Star on GitHub", onClick: () => void starInPlace() },data: {actionLayout: "stacked-end",leadingIcon: <StarIcon aria-hidden className="size-4 text-warning-foreground" />,@@ -49,27 +62,59 @@ function showStarPrompt() {});}+// Resolves after IDLE_MS without input while this window has focus.+function waitForIdle() {+ return new Promise<void>((resolve) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const restart = () => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ // Input inside another app or an embedded frame never reaches us; the next focus restarts.+ if (!document.hasFocus() || document.activeElement?.matches("iframe, webview")) return;+ for (const type of ACTIVITY_EVENTS) window.removeEventListener(type, restart, true);+ resolve();+ }, IDLE_MS);+ };+ for (const type of ACTIVITY_EVENTS) {+ window.addEventListener(type, restart, { capture: true, passive: true });+ }+ restart();+ });+}+// The server's GitHub account stands in for the user's; it may not be theirs on a shared server.+const starInput = (environmentId: EnvironmentId) => ({+ environmentId,+ input: {+ provider: SourceControlProviderKind.make("github"),+ host: "github.com",+ repository: REPOSITORY,+ },+});+async function alreadyStarred(environmentId: EnvironmentId) {const result = await runAtomCommand(appAtomRegistry,sourceControlEnvironment.checkStarred,- {- environmentId,- input: {- provider: SourceControlProviderKind.make("github"),- host: "github.com",- repository: REPOSITORY,- },- },+ starInput(environmentId),{ label: "check GitHub star", reportFailure: false, reportDefect: false },);return result._tag === "Success" ? result.value : undefined;}+async function starRepository(environmentId: EnvironmentId) {+ const result = await runAtomCommand(+ appAtomRegistry,+ sourceControlEnvironment.star,+ starInput(environmentId),+ { label: "star on GitHub", reportFailure: false, reportDefect: false },+ );+ return result._tag === "Success" && result.value;+}+/*** Counts a sent prompt. After more than five, asks once per session for a star until dismissed,- * unless the environment's GitHub account already starred the repo.+ * unless the environment's GitHub account already starred the repo. Waits until the user is idle.*/export async function recordPromptSent(environmentId: EnvironmentId): Promise<void> {if (shownThisSession) return;@@ -86,11 +131,12 @@ export async function recordPromptSent(environmentId: EnvironmentId): Promise<voconst starred = await alreadyStarred(environmentId);if (starred === undefined) return;if (starred) return dismiss();+ await waitForIdle();try {- // Another tab can dismiss while the check runs.+ // Another tab can dismiss while the check or the idle wait runs.if (getLocalStorageItem(DISMISSED_KEY, Schema.Boolean)) return;} catch {return;}- showStarPrompt();+ showStarPrompt(environmentId);}diff --git a/packages/client-runtime/src/state/sourceControl.ts b/packages/client-runtime/src/state/sourceControl.tsindex 7af35dd95a4..a013699e43e 100644--- a/packages/client-runtime/src/state/sourceControl.ts+++ b/packages/client-runtime/src/state/sourceControl.ts@@ -34,6 +34,10 @@ export function createSourceControlEnvironmentAtoms<R, E>(label: "environment-data:source-control:check-starred",tag: WS_METHODS.sourceControlStarred,}),+ star: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:source-control:star",+ tag: WS_METHODS.sourceControlStar,+ }),repository: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:source-control:repository",tag: WS_METHODS.sourceControlLookupRepository,diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsindex d3139f2eeff..c2488226191 100644--- a/packages/contracts/src/clientRpcPermissions.ts+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -36,6 +36,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {[WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope,[WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope,[WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope,+ [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope,// Signing in replaces the server's GitHub credential, as saving a token in Settings does.[WS_METHODS.sourceControlSignInStart]: AuthSettingsWriteScope,[WS_METHODS.sourceControlSignInWait]: AuthSettingsWriteScope,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 01989ff8a47..737059e8557 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -595,6 +595,7 @@ export const WS_METHODS = {sourceControlSignInCancel: "sourceControl.signInCancel",sourceControlAppAccess: "sourceControl.appAccess",sourceControlStarred: "sourceControl.starred",+ sourceControlStar: "sourceControl.star",projectCloneStart: "projectClone.start",projectCloneCancel: "projectClone.cancel",projectCloneRetry: "projectClone.retry",@@ -1252,6 +1253,13 @@ const WsSourceControlStarredRpc = Rpc.make(WS_METHODS.sourceControlStarred, {error: EnvironmentAuthorizationError,});+// Stars the repository as the server's forge account. False when the forge refused or cannot star.+const WsSourceControlStarRpc = Rpc.make(WS_METHODS.sourceControlStar, {+ payload: SourceControlStarredInput,+ success: Schema.Boolean,+ error: EnvironmentAuthorizationError,+});+// Returns when the project exists and cloning starts; progress uses the subscription.const WsProjectCloneStartRpc = Rpc.make(WS_METHODS.projectCloneStart, {payload: ProjectCloneStartInput,@@ -2090,6 +2098,7 @@ export const WsRpcGroup = RpcGroup.make(WsSourceControlSignInCancelRpc,WsSourceControlAppAccessRpc,WsSourceControlStarredRpc,+ WsSourceControlStarRpc,WsProjectCloneStartRpc,WsProjectCloneCancelRpc,WsProjectCloneRetryRpc,diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.tsindex d5fc3d45490..7226faad651 100644--- a/packages/source-control-core/src/server/driver.ts+++ b/packages/source-control-core/src/server/driver.ts@@ -65,6 +65,8 @@ export interface SourceControlDriverInstance {readonly signIn?: SourceControlSignIn;/** Whether the server's account on `host` starred `repository` (`owner/name`). */readonly isRepositoryStarred?: (host: string, repository: string) => Effect.Effect<boolean>;+ /** Stars `repository` as the server's account on `host`; false when the forge refused. */+ readonly starRepository?: (host: string, repository: string) => Effect.Effect<boolean>;}/** What the server gives every driver. A driver builds anything else it needs itself. */diff --git a/packages/source-control-github/src/server/driver.test.ts b/packages/source-control-github/src/server/driver.test.tsindex b97300eceaf..a16f7efca4e 100644--- a/packages/source-control-github/src/server/driver.test.ts+++ b/packages/source-control-github/src/server/driver.test.ts@@ -2,17 +2,17 @@ import { assert, describe, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import { makeIsRepositoryStarred } from "./driver.ts";+import { makeIsRepositoryStarred, makeStarRepository } from "./driver.ts";import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";import * as GitHubRest from "./GitHubRest.ts";-describe("makeIsRepositoryStarred", () => {- it.effect("is true only when GitHub answers 204 for the repository", () => {+describe("starred", () => {+ it.effect("checks and stars only a valid repository, true only on 204", () => {const paths: Array<string> = [];const starred = new Set(["user/starred/pingdotgg/t3code"]);const api = Layer.mock(GitHubRest.GitHubRest)({rest: (input) => {- paths.push(input.path);+ paths.push(`${input.method ?? "GET"} ${input.path}`);return starred.has(input.path)? Effect.succeed({status: 204,@@ -31,12 +31,20 @@ describe("makeIsRepositoryStarred", () => {});return Effect.gen(function* () {const isStarred = yield* makeIsRepositoryStarred;+ const star = yield* makeStarRepository;assert.isTrue(yield* isStarred("github.com", "pingdotgg/t3code"));assert.isFalse(yield* isStarred("github.com", "pingdotgg/uploadthing"));assert.isFalse(yield* isStarred("github.com", "pingdotgg/t3code/../../user"));+ assert.isFalse(yield* isStarred("github.com", "../repos"));+ assert.isTrue(yield* star("github.com", "pingdotgg/t3code"));+ assert.isFalse(yield* star("github.com", "pingdotgg/uploadthing"));+ assert.isFalse(yield* star("github.com", "pingdotgg/t3code/../../user"));+ assert.isFalse(yield* star("github.com", "../repos"));assert.deepStrictEqual(paths, [- "user/starred/pingdotgg/t3code",- "user/starred/pingdotgg/uploadthing",+ "GET user/starred/pingdotgg/t3code",+ "GET user/starred/pingdotgg/uploadthing",+ "PUT user/starred/pingdotgg/t3code",+ "PUT user/starred/pingdotgg/uploadthing",]);}).pipe(Effect.provide(api));});diff --git a/packages/source-control-github/src/server/driver.ts b/packages/source-control-github/src/server/driver.tsindex 351933ce551..45af994eca2 100644--- a/packages/source-control-github/src/server/driver.ts+++ b/packages/source-control-github/src/server/driver.ts@@ -53,17 +53,25 @@ const makeSignIn = Effect.gen(function* () {} satisfies SourceControlSignIn;});+const starredPath = (repository: string) => {+ const segments = repository.split("/");+ // "." and ".." survive encoding and would normalize the URL out of user/starred.+ return segments.length === 2 && segments.every((segment) => !["", ".", ".."].includes(segment))+ ? `user/starred/${segments.map(encodeURIComponent).join("/")}`+ : undefined;+};+// Only 204 means starred. Tokens without star access, a missing login, and 404 all read as false.export const makeIsRepositoryStarred = Effect.gen(function* () {const api = yield* GitHubRest.GitHubRest;return Effect.fn("GitHubDriver.isRepositoryStarred")(function* (host: string, repository: string) {- const segments = repository.split("/");- if (segments.length !== 2) return false;+ const path = starredPath(repository);+ if (path === undefined) return false;const response = yield* api.rest({host,operation: "isRepositoryStarred",- path: `user/starred/${segments.map(encodeURIComponent).join("/")}`,+ path,allowReserve: false,});return response.status === 204;@@ -72,6 +80,20 @@ export const makeIsRepositoryStarred = Effect.gen(function* () {);});+// False on any failure, such as a token or app sign-in without permission to star.+export const makeStarRepository = Effect.gen(function* () {+ const api = yield* GitHubRest.GitHubRest;+ return Effect.fn("GitHubDriver.starRepository")(+ function* (host: string, repository: string) {+ const path = starredPath(repository);+ if (path === undefined) return false;+ const response = yield* api.rest({ host, operation: "starRepository", method: "PUT", path });+ return response.status === 204;+ },+ Effect.orElseSucceed(() => false),+ );+});+const makeInstance = Effect.all({sourceControl: GitHubSourceControlProvider.make,discovery: GitHubSourceControlProvider.makeDiscovery,@@ -79,6 +101,7 @@ const makeInstance = Effect.all({fetchMedia: GitHubMediaFetch.make,signIn: makeSignIn,isRepositoryStarred: makeIsRepositoryStarred,+ starRepository: makeStarRepository,});export const driver = defineSourceControlDriver({