From 490a0d687bde4f29a869fdb62ea7c8241e35e082 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 16:07:39 -0800 Subject: [PATCH 01/58] fix(server): Antigravity usage skips agy index databases instead of reporting partial history (#39435) --- .../Drivers/antigravityUsageReader.test.ts | 53 +++++++++++-------- .../Drivers/antigravityUsageReader.ts | 7 ++- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index 8fd031d43442e..d0def84f1efe0 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -587,27 +587,38 @@ describe("readAntigravityUsage", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - it.effect("reads Antigravity step-only stores and reports malformed databases", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const dir = yield* tempDir; - yield* seedDatabase(path.join(dir, "steps.db"), (db) => - Effect.gen(function* () { - yield* db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)"); - const usage = [...protoNumber(1, 246), ...protoNumber(2, 10), ...protoNumber(3, 5)]; - yield* db.run("INSERT INTO steps VALUES (?, ?)", [ - 0, - new Uint8Array([...protoBytes(9, usage), ...protoBytes(8, protoNumber(1, 1780000000))]), - ]); - }), - ); - yield* fileSystem.writeFileString(path.join(dir, "broken.db"), "not a sqlite database"); - const result = yield* readAntigravityUsage(dir, 0); - assert.strictEqual(result.errors.length, 1); - assert.strictEqual(records(result)[0]?.model, "gemini-2.5-pro"); - assert.strictEqual(records(result)[0]?.totals.outputTokens, 5); - }).pipe(Effect.provide(NodeServices.layer)), + it.effect( + "reads Antigravity step-only stores, skips index files and reports malformed databases", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* tempDir; + // agy 1.5.x keeps this index beside its conversations; it is not a conversation store. + yield* seedDatabase(path.join(dir, "conversation_summaries.db"), (db) => + db.exec( + "CREATE TABLE conversation_summaries (conversation_id TEXT PRIMARY KEY, title TEXT, step_count INTEGER)", + ), + ); + yield* seedDatabase(path.join(dir, "steps.db"), (db) => + Effect.gen(function* () { + yield* db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)"); + const usage = [...protoNumber(1, 246), ...protoNumber(2, 10), ...protoNumber(3, 5)]; + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 0, + new Uint8Array([ + ...protoBytes(9, usage), + ...protoBytes(8, protoNumber(1, 1780000000)), + ]), + ]); + }), + ); + yield* fileSystem.writeFileString(path.join(dir, "broken.db"), "not a sqlite database"); + const result = yield* readAntigravityUsage(dir, 0); + assert.deepStrictEqual(result.errors, [path.join(dir, "broken.db")]); + assert.strictEqual(records(result)[0]?.model, "gemini-2.5-pro"); + assert.strictEqual(records(result)[0]?.totals.outputTokens, 5); + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("ignores large values in unused Antigravity protobuf fields", () => diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 532233f7facce..4a71c8ed2b056 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -253,9 +253,8 @@ const readDatabase = Effect.fn("readDatabase")(function* ( "SELECT name FROM sqlite_master WHERE type = 'table'", )).map((row) => row.name), ); - if (!tables.has("gen_metadata") && !tables.has("steps")) { - return yield* new AntigravityDatabaseDecodeError({ path }); - } + // Not a conversation store, e.g. agy's conversation_summaries.db index. + if (!tables.has("gen_metadata") && !tables.has("steps")) return null; // Seek by rowid regardless of indexes; idx normally aliases rowid, but sort for layouts where it does not. const readMetadata = Effect.fnUntraced(function* ( query: string, @@ -421,7 +420,7 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* const files: Array<{ root: string; path: string; records: UsageRecord[] }> = []; const errors: string[] = []; const models = new Map(); - const pending: Array<{ data: CachedDatabase["data"]; fileIndex: number }> = []; + const pending: Array<{ data: NonNullable; fileIndex: number }> = []; const identities = new Map(); const groups: Array< UsageCandidate & { parent: number; size: number; owner: number; fileIndex: number } From 5872b0a488847d12aa2351fe5af5e7b7b81077ab Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:57:15 +0530 Subject: [PATCH 02/58] fix(web): a later thread error with the same text shows its banner again (#37419) Co-authored-by: Claude Haiku 5.5 Co-authored-by: Julius Marminge --- .../web/src/components/ChatView.logic.test.ts | 37 ++++++++++++++++ apps/web/src/components/ChatView.logic.ts | 12 +++++ apps/web/src/components/ChatView.tsx | 18 +++++++- .../chat/ThreadErrorBanner.test.tsx | 17 +++++++ .../src/components/chat/ThreadErrorBanner.tsx | 8 +++- packages/client-runtime/src/state/models.ts | 2 + .../src/state/threadExecution.test.ts | 39 ++++++++++++++++ .../src/state/threadExecution.ts | 44 +++++++++++++++++-- .../shared/src/orchestrationV2ThreadError.ts | 9 +++- 9 files changed, 177 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index dbbb445a5ec95..298a7c9b44f01 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -22,6 +22,7 @@ import { isThreadEnvironmentLocked, recallCheckoutIsRepo, rememberCheckoutIsRepo, + threadErrorIsServerRuntime, } from "./ChatView.logic"; import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; import { deriveProviderInstanceEntries } from "../providerInstances"; @@ -1640,3 +1641,39 @@ describe("prepareRevertedMessageAttachments", () => { expect(store.getComposerDraft(target)?.images.map(({ id }) => id)).toEqual(["restored"]); }); }); + +describe("threadErrorIsServerRuntime", () => { + it("is true for a server thread's runtime error, and for a local copy of that same error", () => { + expect( + threadErrorIsServerRuntime({ + isServerThread: true, + localServerError: null, + runtimeError: "E", + }), + ).toBe(true); + expect( + threadErrorIsServerRuntime({ + isServerThread: true, + localServerError: "E", + runtimeError: "E", + }), + ).toBe(true); + }); + + it("is false for a local error that differs from the runtime error, and for draft threads", () => { + expect( + threadErrorIsServerRuntime({ + isServerThread: true, + localServerError: "E2", + runtimeError: "E", + }), + ).toBe(false); + expect( + threadErrorIsServerRuntime({ + isServerThread: false, + localServerError: null, + runtimeError: "E", + }), + ).toBe(false); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 1992b748331a2..1f8bb8e10043c 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1242,6 +1242,18 @@ export function chatActionErrorMessage(error: unknown, resolve: MessageResolver return thrownErrorMessage(error, resolve) ?? resolve(msg("An error occurred.")); } +/** A local copy of the runtime's error shares the runtime's key, so one dismissal covers both. */ +export function threadErrorIsServerRuntime(input: { + readonly isServerThread: boolean; + readonly localServerError: string | null; + readonly runtimeError: string | null; +}): boolean { + return ( + input.isServerThread && + (input.localServerError === null || input.localServerError === input.runtimeError) + ); +} + export function releaseChatTimelineAnchor( current: T, ): T { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1e1646e3123e6..128f3b16d1dde 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -41,7 +41,11 @@ import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider"; import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner"; -import { isThreadEnvironmentLocked, resolveDraftHeroState } from "./ChatView.logic"; +import { + isThreadEnvironmentLocked, + resolveDraftHeroState, + threadErrorIsServerRuntime, +} from "./ChatView.logic"; import { useQueuedRunEdit } from "./chat/useQueuedRunEdit"; import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; @@ -979,7 +983,17 @@ export default function ChatView(props: ChatViewProps) { const threadError = isServerThread ? (localServerError ?? serverRuntime?.lastError ?? null) : localDraftError; - const threadErrorBannerKey = getThreadErrorBannerKey(routeThreadKey, threadError); + const threadErrorBannerKey = getThreadErrorBannerKey( + routeThreadKey, + threadError, + threadErrorIsServerRuntime({ + isServerThread, + localServerError, + runtimeError: serverRuntime?.lastError ?? null, + }) + ? (serverRuntime?.lastErrorSource ?? null) + : null, + ); const visibleThreadError = shouldShowThreadErrorBanner( routeThreadKey, threadError, diff --git a/apps/web/src/components/chat/ThreadErrorBanner.test.tsx b/apps/web/src/components/chat/ThreadErrorBanner.test.tsx index f43f03ad46db0..efa15aaf6bf21 100644 --- a/apps/web/src/components/chat/ThreadErrorBanner.test.tsx +++ b/apps/web/src/components/chat/ThreadErrorBanner.test.tsx @@ -42,4 +42,21 @@ describe("ThreadErrorBanner", () => { ), ).toBe(true); }); + + it("reappears when a later run fails with the same error on the same thread", () => { + const error = "Turn failed"; + const dismissedKey = getThreadErrorBannerKey("env:thread-c", error, "run-a"); + dismissThreadErrorBannerForSession(dismissedKey); + const laterRunKey = getThreadErrorBannerKey("env:thread-c", error, "run-b"); + + expect(isThreadErrorBannerDismissedForSession(dismissedKey)).toBe(true); + expect(isThreadErrorBannerDismissedForSession(laterRunKey)).toBe(false); + expect( + shouldShowThreadErrorBanner( + "env:thread-c", + error, + isThreadErrorBannerDismissedForSession(laterRunKey), + ), + ).toBe(true); + }); }); diff --git a/apps/web/src/components/chat/ThreadErrorBanner.tsx b/apps/web/src/components/chat/ThreadErrorBanner.tsx index 8d6ebc71fa435..f4a4bc484ffe5 100644 --- a/apps/web/src/components/chat/ThreadErrorBanner.tsx +++ b/apps/web/src/components/chat/ThreadErrorBanner.tsx @@ -51,8 +51,12 @@ export function getThreadErrorBannerMessage(error: string): string { : error; } -export function getThreadErrorBannerKey(threadKey: string, error: string | null): string | null { - return error === null ? null : `${threadKey}\u0000${error}`; +export function getThreadErrorBannerKey( + threadKey: string, + error: string | null, + source: string | null = null, +): string | null { + return error === null ? null : `${threadKey}\u0000${source ?? ""}\u0000${error}`; } export function shouldShowThreadErrorBanner( diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index b37da2abe28b2..4401f90e898c3 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -114,6 +114,8 @@ export interface ThreadRuntimeSummary { readonly lastError: string | null; readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null; readonly lastErrorCode?: string | null; + /** The record `lastError` came from, with its change time so a repeated failure differs. */ + readonly lastErrorSource?: string | null; readonly usageLimitResetAt?: string | null; readonly updatedAt: string; } diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index b03236959d786..2984bb97dbaeb 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -179,7 +179,46 @@ describe("thread execution presentation", () => { expect(deriveThreadRuntime(projection)).toMatchObject({ lastError: "Plan limit reached", lastErrorClass: "usage_limit", + lastErrorSource: "limit-error@2026-07-28T10:00:00.000Z", }); + // A retried run fails again through the same item, so only its failure time tells it apart. + const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z"); + const source = (input: Partial[0]>) => + deriveThreadRuntime({ ...projection, ...input })?.lastErrorSource; + expect(source({ turnItems: [{ ...item, completedAt: later, updatedAt: later }] })).toBe( + "limit-error@2026-07-28T10:05:00.000Z", + ); + expect(source({ turnItems: [{ ...item, updatedAt: later }] })).toBe( + "limit-error@2026-07-28T10:00:00.000Z", + ); + const session = (lastError: string) => ({ + id: ProviderSessionId.make("failed-session"), + driver: ProviderDriverKind.make("pi"), + providerInstanceId: v2Projection.thread.providerInstanceId, + status: "error" as const, + cwd: "/repo", + model: null, + capabilities: {} as never, + createdAt: now, + updatedAt: later, + lastError, + }); + // A session that repeats the failure keeps its source, whatever the session's own updates. + expect(source({ providerSessions: [session("Plan limit reached")] })).toBe( + "limit-error@2026-07-28T10:00:00.000Z", + ); + // Otherwise a session error belongs to the latest ended run, kept while a newer run starts. + const ended = { ...failed, completedAt: now }; + const starting = [ended, run("next", 2, "starting")]; + expect(source({ runs: [ended], providerSessions: [session("Session failed")] })).toBe( + "limited@2026-07-28T10:00:00.000Z", + ); + expect(source({ runs: starting, providerSessions: [session("Session failed")] })).toBe( + "limited@2026-07-28T10:00:00.000Z", + ); + expect(source({ runs: starting, providerSessions: [session("Plan limit reached")] })).toBe( + "limit-error@2026-07-28T10:00:00.000Z", + ); expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id); expect( deriveThreadRuntime({ diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index de0c2672cbde8..033930e254f57 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -1,6 +1,7 @@ import { latestExecutedRun, latestRootProviderFailure, + latestRootProviderFailureItem, latestUnheldRun, threadErrorSummary, usageLimitRunPresentedAsLatest, @@ -405,6 +406,8 @@ export function deriveThreadStructureRuntime( if (latestRun === null && !backgroundWorkHoldsRun) return null; const activeRunId = latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null; + const failureItem = latestRootProviderFailureItem(latestRunProjection, projection.turnItems); + const sessionError = providerSession?.lastError ?? null; return { status: usageLimitedRun ? "failed" @@ -418,13 +421,46 @@ export function deriveThreadStructureRuntime( : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)), providerInstanceId: projection.thread.providerInstanceId, providerName: providerSession?.driver ?? null, - ...threadErrorSummary( - latestRootProviderFailure(latestRunProjection, projection.turnItems), - providerSession?.lastError ?? null, - ), + ...threadErrorSummary(failureItem?.failure ?? null, sessionError), + lastErrorSource: threadErrorSource(failureItem, sessionError, projection), }; } +const isoOrEmpty = (at: DateTime.Utc | null) => (at === null ? "" : DateTime.formatIso(at)); + +/** + * A session error belongs to the latest ended run, as that run's failure when the text matches. + * Session timestamps are not used: providers rewrite them on unrelated updates. + */ +function threadErrorSource( + failureItem: ReturnType, + sessionError: string | null, + projection: Pick, +): string | null { + const itemSource = (item: NonNullable) => + `${item.id}@${isoOrEmpty(item.completedAt)}`; + if ( + failureItem !== null && + (sessionError === null || sessionError === failureItem.failure.message) + ) { + return itemSource(failureItem); + } + if (sessionError === null) return null; + let ended: ThreadStructure["runs"][number] | null = null; + for (const run of projection.runs) { + if (run.status !== "failed" && run.status !== "completed") continue; + if (ended === null || run.ordinal > ended.ordinal) ended = run; + } + if (ended === null) return null; + const endedFailure = + failureItem?.runId === ended.id + ? failureItem + : latestRootProviderFailureItem(ended, projection.turnItems); + return endedFailure?.failure.message === sessionError + ? itemSource(endedFailure) + : `${ended.id}@${isoOrEmpty(ended.completedAt)}`; +} + export interface UsageLimitNoticeRows { readonly itemIds: ReadonlySet; /** Hidden only when its text reads as the provider's limit message; see PROVIDER_LIMIT_NOTICE. */ diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 141d73f402540..8987593a0b0a5 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -15,6 +15,13 @@ export function latestRootProviderFailure( run: OrchestrationV2Run | null, turnItems: ReadonlyArray, ): OrchestrationV2ProviderFailure | null { + return latestRootProviderFailureItem(run, turnItems)?.failure ?? null; +} + +export function latestRootProviderFailureItem( + run: OrchestrationV2Run | null, + turnItems: ReadonlyArray, +): ErrorTurnItem | null { if (run?.status !== "failed") return null; let latest: ErrorTurnItem | null = null; for (const item of turnItems) { @@ -34,7 +41,7 @@ export function latestRootProviderFailure( latest = item; } } - return latest?.failure ?? null; + return latest; } export function threadErrorSummary( From 003d53ace1f5255eaca52486e35d58fbd299e22e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 16:38:38 -0800 Subject: [PATCH 03/58] fix(client-runtime): connection supervisor restarts its background listeners after a defect (#39431) --- .../src/connection/supervisor.test.ts | 120 ++++++++++++++++++ .../src/connection/supervisor.ts | 86 ++++++++----- 2 files changed, 176 insertions(+), 30 deletions(-) diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 81c8bf4064a45..c8e241f8f69c0 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -2936,3 +2936,123 @@ describe("EnvironmentSupervisor routes", () => { }), ); }); + +describe("EnvironmentSupervisor background fibers", () => { + it.effect("hears the network return after its connectivity stream died", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const status = yield* SubscriptionRef.make("offline"); + const subscriptions = yield* Ref.make(0); + const dying = Connectivity.Connectivity.of({ + status: SubscriptionRef.get(status), + changes: Stream.unwrap( + Ref.updateAndGet(subscriptions, (count) => count + 1).pipe( + Effect.map((count) => + count === 1 + ? Stream.die(new Error("platform connectivity stream died")) + : SubscriptionRef.changes(status), + ), + ), + ), + }); + const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService(Connectivity.Connectivity, dying), + Effect.provide(harness.dependencies), + ); + yield* TestClock.adjust("10 minutes"); + expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("offline"); + + yield* SubscriptionRef.set(status, "online"); + yield* TestClock.adjust("10 minutes"); + expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected"); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("replaces a stalled session on return to the app after its wakeup stream died", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ probe: () => Effect.never }); + const returns = yield* SubscriptionRef.make(0); + const subscriptions = yield* Ref.make(0); + const dying = ConnectionWakeups.ConnectionWakeups.of({ + changes: Stream.unwrap( + Ref.updateAndGet(subscriptions, (count) => count + 1).pipe( + Effect.map((count) => + count === 1 + ? Stream.die(new Error("platform wakeup stream died")) + : SubscriptionRef.changes(returns).pipe( + Stream.drop(1), + Stream.map(() => "application-active" as const), + ), + ), + ), + ), + }); + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, { + initiallyDesired: true, + }).pipe( + Effect.provideService(ConnectionWakeups.ConnectionWakeups, dying), + Effect.provide(harness.dependencies), + ); + yield* TestClock.adjust("10 minutes"); + expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({ + phase: "connected", + generation: 1, + }); + + // The user returns to the app; the session's probe never answers. + yield* SubscriptionRef.update(returns, (count) => count + 1); + yield* TestClock.adjust("15 seconds"); + yield* TestClock.adjust("15 seconds"); + yield* TestClock.adjust("10 minutes"); + expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({ + phase: "connected", + generation: 2, + }); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("still moves to a better route after one route check crashed", () => + Effect.gen(function* () { + const lanReachable = yield* Ref.make(false); + const preflights = yield* Ref.make(0); + const harness = yield* makeHarness({ + checkRoute: (route) => + route.target._tag === "BearerConnectionTarget" + ? Ref.get(lanReachable).pipe( + Effect.map((reachable) => (reachable ? "answered" : "silent")), + ) + : Effect.succeed("unchecked"), + preflight: () => + Ref.updateAndGet(preflights, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 + ? Effect.die(new Error("route check threw")) + : Ref.get(lanReachable).pipe( + Effect.map((reachable) => (reachable ? "ready" : "silent")), + ), + ), + ), + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)), + }); + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, { + initiallyDesired: true, + }).pipe(Effect.provide(harness.dependencies)); + yield* awaitState( + supervisor.state, + (state) => state.phase === "connected" && state.generation === 1, + ); + yield* TestClock.adjust("60 seconds"); + expect(yield* Ref.get(preflights)).toBeGreaterThanOrEqual(1); + + yield* Ref.set(lanReachable, true); + for (let minute = 0; minute < 60; minute += 1) { + yield* TestClock.adjust("60 seconds"); + } + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe( + "BearerConnectionTarget", + ); + }).pipe(Effect.provide(TestClock.layer())), + ); +}); diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 79e6802805205..0964db0359b18 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -1332,40 +1332,66 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( // Registered before the fibers below so closing the scope interrupts them first. // A loop still running when the queue shuts down would report that as a failure. yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease))); - yield* connectivity.changes.pipe( - Stream.runForEach((network) => - Ref.modify(intent, (current) => { - const next = targetNetwork(network); - return current.network === next - ? [false, current] - : ([true, { ...current, network: next }] as const); - }).pipe( - Effect.flatMap((changed) => - changed - ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe( - Effect.andThen(signal({ _tag: "NetworkChanged", network })), - ) - : Effect.void, - ), + // A defect in a background listener would otherwise end it for good, silently. + // Untraced: a span here would stay open for the supervisor's whole lifetime. + const keepRunning = Effect.fnUntraced( + function* (task: string, effect: Effect.Effect, onRestart?: Effect.Effect) { + let current = effect; + while (true) { + const exit = yield* Effect.exit(current); + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return yield* exit; + yield* Effect.logError("Connection supervisor task failed; restarting it.").pipe( + Effect.annotateLogs({ + "environment.id": target.environmentId, + "environment.label": target.label, + task, + ...safeErrorLogAttributes(exit.cause.reasons.find(Cause.isDieReason)?.defect), + }), + ); + yield* Effect.sleep(RETRY_BASE_DELAY_MS); + current = onRestart ? onRestart.pipe(Effect.andThen(effect)) : effect; + } + }, + (self) => Effect.forkScoped(self), + ); + + const applyNetwork = (network: NetworkStatus) => + Ref.modify(intent, (current) => { + const next = targetNetwork(network); + return current.network === next + ? [false, current] + : ([true, { ...current, network: next }] as const); + }).pipe( + Effect.flatMap((changed) => + changed + ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe( + Effect.andThen(signal({ _tag: "NetworkChanged", network })), + ) + : Effect.void, ), - ), - Effect.forkScoped, + ); + // A restarted listener may have missed changes while it was down. + yield* keepRunning( + "network-listener", + connectivity.changes.pipe(Stream.runForEach(applyNetwork)), + connectivity.status.pipe(Effect.flatMap(applyNetwork)), ); - yield* wakeups.changes.pipe( - Stream.filter(ConnectionWakeups.reachesConnectionSupervisor), - Stream.runForEach((reason) => - // A long suspension can hide a network change the platform never reported. - (reason === "network-changed" || reason === "application-active-long" - ? forgetSilentRoutes - : Effect.void - ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))), + yield* keepRunning( + "wakeup-listener", + wakeups.changes.pipe( + Stream.filter(ConnectionWakeups.reachesConnectionSupervisor), + Stream.runForEach((reason) => + // A long suspension can hide a network change the platform never reported. + (reason === "network-changed" || reason === "application-active-long" + ? forgetSilentRoutes + : Effect.void + ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))), + ), ), - Effect.forkScoped, ); - yield* Queue.take(betterRouteChecks).pipe( - Effect.flatMap(checkBetterRoutes), - Effect.forever, - Effect.forkScoped, + yield* keepRunning( + "better-route-checker", + Queue.take(betterRouteChecks).pipe(Effect.flatMap(checkBetterRoutes), Effect.forever), ); // A restarted loop has forgotten its retry ladder, so it waits out the // ladder's ceiling unless a signal cuts the wait short. From 57e92b0b98725a2e4ea60790f550b1915b0ac8c2 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 19 Nov 2026 18:46:58 -0600 Subject: [PATCH 04/58] fix(cursor): Max Mode tiers keep working after Cursor changes a model (#39453) Co-authored-by: Cursor --- .../provider-cursor/src/server/adapter.ts | 7 +++- packages/provider-cursor/src/server/driver.ts | 17 ++++++++ .../src/server/sdkModel.test.ts | 33 +++++++++++++++ .../provider-cursor/src/server/sdkModel.ts | 42 ++++++++++++++----- .../src/server/textGeneration.ts | 5 ++- 5 files changed, 91 insertions(+), 13 deletions(-) diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 5d08119953c06..c2786c9947973 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -4,6 +4,7 @@ import type { InteractionUpdate, McpServerConfig, RunResult, + SDKModel, SDKUserMessage, SettingSource, ToolCall, @@ -309,6 +310,7 @@ export function makeCursorAgentOptions(input: { readonly apiKey?: string; readonly modelSelection: ModelSelection; readonly models?: ReadonlyArray; + readonly sdkModels?: ReadonlyArray; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; readonly threadId: ThreadId; readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; @@ -317,7 +319,7 @@ export function makeCursorAgentOptions(input: { const policy = cursorRuntimeAgentPolicy(input.runtimePolicy, input.platform); const mcpServers = cursorMcpServers(input.mcpSession); return { - model: cursorSdkModelSelection(input.modelSelection, input.models), + model: cursorSdkModelSelection(input.modelSelection, input.models, input.sdkModels), name: `T3 Code ${input.threadId}`, mode: input.runtimePolicy.interactionMode === "plan" ? "plan" : "agent", ...(input.apiKey === undefined ? {} : { apiKey: input.apiKey }), @@ -1017,6 +1019,7 @@ export interface CursorAdapterV2Options { readonly instanceId: ProviderInstanceId; readonly environment: NodeJS.ProcessEnv; readonly getModels?: () => ReadonlyArray; + readonly getSdkModels?: () => ReadonlyArray; } export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( @@ -2548,6 +2551,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ...(apiKey === undefined ? {} : { apiKey }), modelSelection: openInput.modelSelection, models: adapterOptions.getModels?.() ?? [], + sdkModels: adapterOptions.getSdkModels?.() ?? [], runtimePolicy: openInput.runtimePolicy, platform, threadId: openInput.threadId, @@ -2775,6 +2779,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( model: cursorSdkModelSelection( turnInput.modelSelection, adapterOptions.getModels?.() ?? [], + adapterOptions.getSdkModels?.() ?? [], ), mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent", ...(Object.keys(turnMcpServers).length === 0 diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index 4b7477295fbd8..ebd981330bf4a 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -4,6 +4,7 @@ import { type ServerProviderModel, } from "@t3tools/contracts"; import { CursorSettings } from "../settings.ts"; +import type { SDKModel } from "@cursor/sdk"; import * as Effect from "effect/Effect"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as FileSystem from "effect/FileSystem"; @@ -164,10 +165,12 @@ export const CursorDriver: ProviderDriver< }); let catalogModels: ReadonlyArray = []; + let catalogSdkModels: ReadonlyArray = []; const orchestrationAdapter = yield* makeCursorAdapterV2({ instanceId, environment: processEnv, getModels: () => catalogModels, + getSdkModels: () => catalogSdkModels, }).pipe( Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { ...sdkRunner, @@ -211,6 +214,7 @@ export const CursorDriver: ProviderDriver< auth.requireApiKey, auth.withAccess, () => catalogModels, + () => catalogSdkModels, ); const checkProvider = auth.readApiKey.pipe( @@ -250,6 +254,19 @@ export const CursorDriver: ProviderDriver< } }), ), + Effect.provideServiceEffect( + CursorSdkCatalog.CursorSdkCatalog, + Effect.map(CursorSdkCatalog.CursorSdkCatalog, (catalog) => + CursorSdkCatalog.CursorSdkCatalog.of({ + // Untraced: CursorSdkCatalog.read already spans this call. + read: Effect.fnUntraced(function* (apiKey) { + const snapshot = yield* catalog.read(apiKey); + if (snapshot.models.length > 0) catalogSdkModels = snapshot.models; + return snapshot; + }), + }), + ), + ), Effect.provide(CursorSdkCatalog.layer), Effect.provideService(HttpClient.HttpClient, httpClient), ); diff --git a/packages/provider-cursor/src/server/sdkModel.test.ts b/packages/provider-cursor/src/server/sdkModel.test.ts index 4ad129e1ae239..a457becef9377 100644 --- a/packages/provider-cursor/src/server/sdkModel.test.ts +++ b/packages/provider-cursor/src/server/sdkModel.test.ts @@ -65,6 +65,39 @@ describe("cursorSdkModelSelection", () => { }); }); + it.each([ + { context: undefined, maxMode: true }, + { context: "1m", maxMode: true }, + { context: "300k", maxMode: undefined }, + ])("sets Max Mode from the catalog for context $context", ({ context, maxMode }) => { + const sdkModels = [ + { + id: "gemini-4-neon", + displayName: "Gemini 4 Neon", + parameters: [{ id: "context", values: [{ value: "300k" }, { value: "1m" }] }], + variants: [ + { displayName: "300K", params: [{ id: "context", value: "300k" }] }, + { + displayName: "1M", + isDefault: true, + isMaxMode: true, + params: [{ id: "context", value: "1m" }], + }, + ], + }, + ]; + const selection = cursorSdkModelSelection( + { + instanceId, + model: "gemini-4-neon", + ...(context === undefined ? {} : { options: [{ id: "contextWindow", value: context }] }), + }, + buildCursorDiscoveredModelsFromSdk(sdkModels), + sdkModels, + ); + expect(selection.maxMode).toBe(maxMode); + }); + it("sends no parameters for a model missing from the catalog", () => { expect(cursorSdkModelSelection({ instanceId, model: "auto" }, models)).toEqual({ id: "default", diff --git a/packages/provider-cursor/src/server/sdkModel.ts b/packages/provider-cursor/src/server/sdkModel.ts index ec2a53b6aea71..eb030a4158344 100644 --- a/packages/provider-cursor/src/server/sdkModel.ts +++ b/packages/provider-cursor/src/server/sdkModel.ts @@ -1,4 +1,8 @@ -import type { ModelSelection as CursorSdkModelSelection, ModelParameterValue } from "@cursor/sdk"; +import type { + ModelSelection as CursorSdkModelSelection, + ModelParameterValue, + SDKModel, +} from "@cursor/sdk"; import type { ModelSelection, ServerProviderModel } from "@t3tools/contracts"; import { getProviderOptionCurrentValue } from "@t3tools/shared/model"; @@ -55,9 +59,27 @@ export function cursorContextWindowTokens( return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined; } +// The SDK infers Max Mode from a model list it never refreshes, so pass it from T3's fresher catalog. +function cursorSdkMaxMode( + sdkModel: SDKModel | undefined, + params: ReadonlyArray, +): boolean { + if (params.length === 0) return false; + const variants = (sdkModel?.variants ?? []).filter((variant) => + params.every((param) => + variant.params.some( + (candidate) => + candidate.id.trim() === param.id.trim() && candidate.value.trim() === param.value.trim(), + ), + ), + ); + return variants.length > 0 && variants.every((variant) => variant.isMaxMode === true); +} + export function cursorSdkModelSelection( modelSelection: ModelSelection, models: ReadonlyArray = [], + sdkModels: ReadonlyArray = [], ): CursorSdkModelSelection { const explicit = modelSelection.options ?? []; const descriptors = @@ -69,16 +91,16 @@ export function cursorSdkModelSelection( const value = descriptor.id === "fastMode" ? false : getProviderOptionCurrentValue(descriptor); return value === undefined ? [] : [{ id: descriptor.id, value }]; }); - const options = [...explicit, ...defaults]; + const params = [...explicit, ...defaults].map((option): ModelParameterValue => ({ + id: cursorSdkParameterId(option.id), + value: String(option.value), + })); + const sdkModel = sdkModels.find( + (model) => model.id === modelSelection.model || model.aliases?.includes(modelSelection.model), + ); return { id: modelSelection.model === "auto" ? "default" : modelSelection.model, - ...(options.length === 0 - ? {} - : { - params: options.map((option): ModelParameterValue => ({ - id: cursorSdkParameterId(option.id), - value: String(option.value), - })), - }), + ...(params.length === 0 ? {} : { params }), + ...(cursorSdkMaxMode(sdkModel, params) ? { maxMode: true } : {}), }; } diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.ts index fc15f3ee185e2..21f4f78860512 100644 --- a/packages/provider-cursor/src/server/textGeneration.ts +++ b/packages/provider-cursor/src/server/textGeneration.ts @@ -1,6 +1,6 @@ import * as FileSystem from "effect/FileSystem"; -import type { AgentOptions, RunResult } from "@cursor/sdk"; +import type { AgentOptions, RunResult, SDKModel } from "@cursor/sdk"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -55,6 +55,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu resolveApiKey?: Effect.Effect, withAccess?: CursorAuth["withAccess"], getModels?: () => ReadonlyArray, + getSdkModels?: () => ReadonlyArray, ) { const fs = yield* FileSystem.FileSystem; const sdk = yield* CursorSdk.CursorSdk; @@ -121,7 +122,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu const agentOptions = { apiKey, mode: "plan", - model: cursorSdkModelSelection(modelSelection, getModels?.() ?? []), + model: cursorSdkModelSelection(modelSelection, getModels?.() ?? [], getSdkModels?.() ?? []), local: { cwd, store, From 9fde959ac0542e835a2cdafd417125bbdbe4ad07 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:48:08 +0300 Subject: [PATCH 05/58] feat(web): choose which projects the issues list shows (#38799) Co-authored-by: Claude Opus 5.5 --- apps/server/src/issue/IssueService.test.ts | 3 + apps/server/src/issue/IssueService.ts | 11 +- .../issue/IssueListFilterPickers.tsx | 124 ++++++++++++------ apps/web/src/components/issue/IssuesPage.tsx | 117 +++++++++++------ .../components/issue/issueListPreferences.ts | 26 ++-- .../components/issue/issueSavedViews.test.ts | 29 +++- .../src/components/issue/issueSavedViews.ts | 6 +- .../issue/issuesSearch.logic.test.ts | 42 +++++- .../components/issue/issuesSearch.logic.ts | 70 +++++++++- apps/web/src/i18n/translations/de.json | 5 +- apps/web/src/i18n/translations/en.json | 5 +- apps/web/src/i18n/translations/es.json | 5 +- apps/web/src/i18n/translations/fr.json | 5 +- apps/web/src/i18n/translations/ja.json | 5 +- apps/web/src/i18n/translations/ko.json | 5 +- apps/web/src/i18n/translations/pt-BR.json | 5 +- apps/web/src/i18n/translations/ru.json | 5 +- apps/web/src/i18n/translations/sv.json | 5 +- apps/web/src/i18n/translations/zh.json | 5 +- docs/user/source-control.md | 5 +- packages/client-runtime/src/issueList.test.ts | 41 ------ packages/client-runtime/src/issueList.ts | 5 - packages/contracts/src/issue.ts | 6 + 23 files changed, 376 insertions(+), 159 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e68799eea12e7..362d9b104a45e 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -613,6 +613,9 @@ describe("IssueService with a standalone tracker", () => { ["web", "ENG"], ["web", "acme/web"], ]); + listed.length = 0; + yield* bound.list({ state: "open", excludeProjectIds: ["web" as ProjectId] }); + expect(listed).toEqual(["github github.com acme/api"]); // A reference picks the project's tracker by kind; both are the project's own, so writable. const linearRef = { projectId: "web" as ProjectId, diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index e4ffc8817628b..215c07ed82074 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -219,6 +219,7 @@ const make = Effect.gen(function* () { const listProjects = (filter: { readonly projectId?: IssueListInput["projectId"]; + readonly excludeProjectIds?: IssueListInput["excludeProjectIds"]; readonly host?: string | undefined; /** The link's `host:port`, for a host whose binding keeps its port. */ readonly authority?: string | undefined; @@ -236,7 +237,10 @@ const make = Effect.gen(function* () { }), ), Effect.flatMap( - Effect.fnUntraced(function* (shells) { + Effect.fnUntraced(function* (allShells) { + const shells = allShells.filter( + (project) => !filter.excludeProjectIds?.includes(project.id), + ); if (shells.length === 0) return []; // One read per listing, not per project, and never cached so Settings changes apply. const bound = yield* bindings.list.pipe( @@ -322,7 +326,10 @@ const make = Effect.gen(function* () { const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) { // Trackers name every host so a client narrowed to one can switch to another; only the // narrowed host's scopes are read. - const { supported, unimplemented } = yield* listProjects({ projectId: input.projectId }); + const { supported, unimplemented } = yield* listProjects({ + projectId: input.projectId, + excludeProjectIds: input.excludeProjectIds, + }); const host = input.host?.trim().toLowerCase(); const limit = input.limit ?? DEFAULT_LIST_LIMIT; // Worktrees of one repository are separate projects, and every repository of an Azure diff --git a/apps/web/src/components/issue/IssueListFilterPickers.tsx b/apps/web/src/components/issue/IssueListFilterPickers.tsx index ff40d1c3f8f45..d1d28fa366de0 100644 --- a/apps/web/src/components/issue/IssueListFilterPickers.tsx +++ b/apps/web/src/components/issue/IssueListFilterPickers.tsx @@ -26,7 +26,7 @@ import { } from "~/components/ui/menu"; import { useIssueFilterCandidates } from "~/state/issues"; -import type { ProjectFaviconProject } from "../ProjectFavicon"; +import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { PullRequestFilterRadioSubmenu, @@ -36,7 +36,6 @@ import { import { pullRequestLabelColor } from "../pullRequest/pullRequestList.logic"; const VISIBLE_CHOICES = 30; -const ALL_PROJECTS = "all"; const matches = (needle: string, ...fields: ReadonlyArray) => needle.length === 0 || fields.some((field) => field?.toLowerCase().includes(needle)); @@ -54,38 +53,18 @@ export function IssueFiltersMenu(props: { assignee: string | undefined; onAssignee: (assignee: string | undefined) => void; projects: ReadonlyArray; - project: { environmentId: EnvironmentId; projectId: ProjectId } | undefined; - onProject: (project: { environmentId: EnvironmentId; projectId: ProjectId } | undefined) => void; + hiddenProjects: ReadonlySet; + onHiddenProjects: (hidden: ReadonlyArray) => void; }) { const gt = useGT(); const [open, setOpen] = useState(false); const count = [ props.state !== "open", props.involvement !== "all", - props.project, + props.hiddenProjects.size > 0, props.assignee, ...props.labels, ].filter(Boolean).length; - const projectValue = props.project - ? pullRequestProjectKey({ - id: props.project.projectId, - environmentId: props.project.environmentId, - }) - : ALL_PROJECTS; - const projectOptions: ReadonlyArray> = [ - { value: ALL_PROJECTS, label: gt("All projects"), Icon: LayersIcon }, - // A remembered project this client does not list stays shown, so the filter can be taken off. - ...(projectValue !== ALL_PROJECTS && - !props.projects.some((project) => pullRequestProjectKey(project) === projectValue) - ? [{ value: projectValue, label: gt("Unavailable project"), Icon: FolderGit2Icon }] - : []), - ...props.projects.map((project) => ({ - value: pullRequestProjectKey(project), - label: project.title, - Icon: FolderGit2Icon, - project, - })), - ]; // Read when the menu opens, not with every listing: one request per scope. const scopes = open ? props.scopes : []; return ( @@ -114,20 +93,25 @@ export function IssueFiltersMenu(props: { options={props.involvementOptions} onChange={props.onInvolvement} /> - {props.projects.length > 1 || props.project ? ( - { - const project = props.projects.find((p) => pullRequestProjectKey(p) === next); - props.onProject( - project - ? { environmentId: project.environmentId, projectId: project.id } - : undefined, - ); - }} - /> + {props.projects.length > 0 || props.hiddenProjects.size > 0 ? ( + + + + {gt("Projects")} + + {props.hiddenProjects.size === 0 + ? gt("All projects") + : gt("{hidden} hidden", { hidden: props.hiddenProjects.size })} + + + + + ) : null} @@ -169,6 +153,68 @@ export function IssueFiltersMenu(props: { ); } +function ProjectChoices(props: { + projects: ReadonlyArray; + hidden: ReadonlySet; + onChange: (hidden: ReadonlyArray) => void; +}) { + const gt = useGT(); + const [query, setQuery] = useState(""); + const needle = query.trim().toLowerCase(); + const visible = props.projects.filter((project) => matches(needle, project.title)); + const pairsOf = (keys: Iterable) => + [...keys].map((key) => JSON.parse(key) as readonly [EnvironmentId, ProjectId]); + const allShown = props.hidden.size === 0; + return ( + <> + {props.projects.length > 8 ? ( + setQuery(event.currentTarget.value)} + placeholder={gt("Search projects")} + aria-label={gt("Search projects")} + /> + ) : null} + + props.onChange( + shown ? [] : pairsOf(props.projects.map((project) => pullRequestProjectKey(project))), + ) + } + > + + + {gt("Show all")} + + + + {visible.length === 0 ? {gt("No matching projects.")} : null} + {visible.map((project) => { + const key = pullRequestProjectKey(project); + return ( + { + const next = new Set(props.hidden); + if (shown) next.delete(key); + else next.add(key); + props.onChange(pairsOf(next)); + }} + > + + + {project.title} + + + ); + })} + + ); +} + function LabelChoices(props: { scopes: ReadonlyArray; value: ReadonlyArray; diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index 39fd8a0ec60ed..ca471a87f975c 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -49,13 +49,14 @@ import { PullRequestDetailPanel } from "~/components/pullRequest/PullRequestDeta import { PullRequestListGhost } from "~/components/pullRequest/PullRequestGhosts"; import { PullRequestFilterOptionIcon, + pullRequestProjectKey, PullRequestSearchInput, type PullRequestFilterOption, } from "~/components/pullRequest/PullRequestListFilters"; import { m, type MessageResolver } from "~/i18n/messages"; import { resolveFilterOptions } from "../pullRequest/pullRequestListOptions"; import { IssueFiltersMenu } from "./IssueListFilterPickers"; -import { issueFilterProjects } from "./issuesSearch.logic"; +import { issueFilterProjects, issueListTargets, issueProjectKeys } from "./issuesSearch.logic"; import { ISSUE_SAVED_VIEWS } from "./issueSavedViews"; import { SavedViewsMenu } from "~/components/SavedViewsMenu"; import { PullRequestCompactFilterMenu } from "../pullRequest/PullRequestCompactFilterMenu"; @@ -68,6 +69,7 @@ import { PanelLayoutControls } from "~/components/chat/PanelLayoutControls"; import { Button } from "~/components/ui/button"; import { Empty, + EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, @@ -94,7 +96,7 @@ import { useAtomCommand } from "~/state/use-atom-command"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { useProjects } from "~/state/entities"; import { useEnvironments, useIssuesSupported } from "~/state/environments"; -import { issueEnvironment, useIssueList, type IssueListTarget } from "~/state/issues"; +import { issueEnvironment, useIssueList } from "~/state/issues"; import { useDebouncedValue } from "~/state/queries"; import { primaryServerKeybindingsAtom } from "~/state/server"; @@ -206,26 +208,30 @@ export function IssuesPage() { ), environmentLabels, ); - const scopedProject = - search.issueServer && search.issueProject - ? { environmentId: search.issueServer, projectId: search.issueProject } - : undefined; + const hiddenProjects = issueProjectKeys(search.hideProjects); const debouncedQuery = useDebouncedValue(search.q ?? "", 300); const listInput: IssueListInput = { state: search.status, involvement: search.who, limit: PAGE_SIZE, - ...(scopedProject ? { projectId: scopedProject.projectId } : {}), ...(search.host ? { host: search.host } : {}), ...(debouncedQuery ? { query: debouncedQuery } : {}), ...(search.label?.length ? { labels: search.label } : {}), ...(search.assignee ? { assignee: search.assignee } : {}), ...(search.order ? { sort: search.order } : {}), }; - const targets: ReadonlyArray = capableEnvironments - .filter((e) => scopedProject === undefined || e.environmentId === scopedProject.environmentId) - .map((e) => ({ environmentId: e.environmentId, input: listInput })); + const everyProjectHidden = + filterProjects.length > 0 && + filterProjects.every((project) => hiddenProjects.has(pullRequestProjectKey(project))); + const targets = everyProjectHidden + ? [] + : issueListTargets( + capableEnvironments.map((e) => e.environmentId), + filterProjects, + search.hideProjects, + listInput, + ); const list = useIssueList(targets); // Refreshing a list still loading would cancel it and start over, losing the scopes already read. useLiveRefresh( @@ -245,7 +251,9 @@ export function IssuesPage() { const cursors = page ? issueCursorsForHost(page.nextCursors, host) : {}; if (!page || Object.keys(cursors).length === 0 || loadingMore !== null) return; setLoadingMore(`${environmentId} ${host}`); - const result = await loadPage({ environmentId, input: { ...listInput, cursors } }); + const input = targets.find((target) => target.environmentId === environmentId)?.input; + if (!input) return; + const result = await loadPage({ environmentId, input: { ...input, cursors } }); setLoadingMore(null); const failure = result._tag === "Failure" ? squashAtomCommandFailure(result) : null; setPages((current) => { @@ -271,24 +279,49 @@ export function IssuesPage() { // would be, and each tracker's rows carry on from their own cursors. // The server names every tracker so the menu can switch hosts, but reads only the chosen one. const chosenHost = search.host?.toLowerCase(); - const shown = chosenHost - ? new Map( - [...held].map(([environmentId, page]) => [ - environmentId, - { - ...page, - answer: { - ...page.answer, - trackers: page.answer.trackers.filter( - (tracker) => tracker.host.toLowerCase() === chosenHost, + // A server older than `excludeProjectIds` still answers for hidden projects. + const shown = + chosenHost || hiddenProjects.size > 0 + ? new Map( + [...held].map(([environmentId, page]) => [ + environmentId, + { + ...page, + entries: page.entries.filter( + (entry) => + !hiddenProjects.has( + pullRequestProjectKey({ environmentId, id: entry.projectId }), + ), + ), + errors: page.errors.filter( + (error) => + !hiddenProjects.has( + pullRequestProjectKey({ environmentId, id: error.projectId }), + ), ), + answer: { + ...page.answer, + scopes: page.answer.scopes?.filter( + (scope) => + !hiddenProjects.has( + pullRequestProjectKey({ environmentId, id: scope.projectId }), + ), + ), + trackers: chosenHost + ? page.answer.trackers.filter( + (tracker) => tracker.host.toLowerCase() === chosenHost, + ) + : page.answer.trackers, + }, }, - }, - ]), - ) - : held; + ]), + ) + : held; const groups = groupIssues(shown, debouncedQuery, projects, search.order ?? "updated"); - const filterScopes = issueFilterScopes(shown, projects, scopedProject); + const filterScopes = issueFilterScopes( + shown, + projects.filter((project) => !hiddenProjects.has(pullRequestProjectKey(project))), + ); const hostOptions = hostOptionsFor( [...held.values()].flatMap((page) => page.answer.trackers), @@ -301,9 +334,7 @@ export function IssuesPage() { const next: IssuesSearch = { who: merged.who ?? search.who, status: merged.status ?? search.status, - ...(merged.issueServer && merged.issueProject - ? { issueServer: merged.issueServer, issueProject: merged.issueProject } - : {}), + ...(merged.hideProjects?.length ? { hideProjects: merged.hideProjects } : {}), ...(merged.host ? { host: merged.host } : {}), q: merged.q || undefined, ...(merged.label?.length ? { label: merged.label } : {}), @@ -485,6 +516,22 @@ export function IssuesPage() { onRetry={list.retry} refreshing={list.isPending} /> + ) : everyProjectHidden ? ( + + + + + + + Every project is hidden + + + + + + ) : groups.length === 0 ? ( @@ -691,13 +738,8 @@ export function IssuesPage() { assignee={search.assignee} onAssignee={(assignee) => updateSearch({ assignee })} projects={filterProjects} - project={scopedProject} - onProject={(project) => - updateSearch({ - issueServer: project?.environmentId, - issueProject: project?.projectId, - }) - } + hiddenProjects={hiddenProjects} + onHiddenProjects={(hideProjects) => updateSearch({ hideProjects })} /> | undefined; readonly host?: string | undefined; readonly q?: string | undefined; /** `label`, `assignee` and `order` for the same reason: the pull-request page has `labels` and `sort`. */ @@ -32,8 +38,11 @@ const BoundedPreference = Schema.String.check(Schema.isMaxLength(200)); export const IssueListPreferencesSchema = Schema.Struct({ who: IssueInvolvement, status: IssueListState, - issueServer: Schema.optional(EnvironmentId), - issueProject: Schema.optional(ProjectId), + hideProjects: Schema.optional( + Schema.Array(Schema.Tuple([EnvironmentId, ProjectId])).check( + Schema.isMaxLength(ISSUE_LIST_MAX_EXCLUDED_PROJECTS), + ), + ), host: Schema.optional(BoundedPreference), q: Schema.optional(BoundedPreference), label: Schema.optional(Schema.Array(BoundedPreference).check(Schema.isMaxLength(20))), @@ -52,8 +61,7 @@ function storage(): PreferenceStorage | undefined { export function issueListPreferences(search: { readonly who: IssueInvolvement; readonly status: IssueListState; - readonly issueServer?: EnvironmentId | undefined; - readonly issueProject?: ProjectId | undefined; + readonly hideProjects?: ReadonlyArray | undefined; readonly host?: string | undefined; readonly q?: string | undefined; readonly label?: ReadonlyArray | undefined; @@ -63,8 +71,8 @@ export function issueListPreferences(search: { return { who: search.who, status: search.status, - ...(search.issueServer && search.issueProject - ? { issueServer: search.issueServer, issueProject: search.issueProject } + ...(search.hideProjects?.length + ? { hideProjects: search.hideProjects.slice(0, ISSUE_LIST_MAX_EXCLUDED_PROJECTS) } : {}), ...(search.host ? { host: search.host } : {}), ...(search.q ? { q: search.q } : {}), diff --git a/apps/web/src/components/issue/issueSavedViews.test.ts b/apps/web/src/components/issue/issueSavedViews.test.ts index 0933dc008edef..cda0072b5da17 100644 --- a/apps/web/src/components/issue/issueSavedViews.test.ts +++ b/apps/web/src/components/issue/issueSavedViews.test.ts @@ -1,14 +1,21 @@ import { describe, expect, it } from "vite-plus/test"; +import * as Schema from "effect/Schema"; + import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { issueListPreferences, IssueListPreferencesSchema } from "./issueListPreferences"; import { issueViewMatches } from "./issueSavedViews"; +const decodePreferences = Schema.decodeOption(IssueListPreferencesSchema); + const preferences = { who: "assigned", status: "open", - issueServer: EnvironmentId.make("env-1"), - issueProject: ProjectId.make("project-1"), + hideProjects: [ + [EnvironmentId.make("env-1"), ProjectId.make("project-1")], + [EnvironmentId.make("env-1"), ProjectId.make("project-2")], + ], host: "github.com", q: "crash", label: ["bug", "priority"], @@ -24,6 +31,22 @@ describe("saved issue views", () => { ); expect(issueViewMatches(view, { ...preferences, assignee: undefined })).toBe(false); expect(issueViewMatches(view, { ...preferences, label: ["bug"] })).toBe(false); - expect(issueViewMatches(view, { ...preferences, issueProject: undefined })).toBe(false); + expect( + issueViewMatches(view, { + ...preferences, + hideProjects: preferences.hideProjects.toReversed(), + }), + ).toBe(true); + expect(issueViewMatches(view, { ...preferences, hideProjects: undefined })).toBe(false); + }); + + it("keeps a selection of every project within what it reads back", () => { + const many = Array.from( + { length: 1_001 }, + (_, index) => [EnvironmentId.make("env-1"), ProjectId.make(`project-${index}`)] as const, + ); + const stored = issueListPreferences({ ...preferences, hideProjects: many }); + const restored = decodePreferences(stored); + expect(restored._tag === "Some" && restored.value.hideProjects).toEqual(many.slice(0, 1_000)); }); }); diff --git a/apps/web/src/components/issue/issueSavedViews.ts b/apps/web/src/components/issue/issueSavedViews.ts index bac3a6c9ab7bb..02a5a851a460f 100644 --- a/apps/web/src/components/issue/issueSavedViews.ts +++ b/apps/web/src/components/issue/issueSavedViews.ts @@ -15,7 +15,11 @@ export function issueViewMatches( ): boolean { const key = (value: IssueListPreferences) => { const normalized = issueListPreferences(value); - return JSON.stringify({ ...normalized, label: normalized.label?.toSorted() }); + return JSON.stringify({ + ...normalized, + label: normalized.label?.toSorted(), + hideProjects: normalized.hideProjects?.map((pair) => JSON.stringify(pair)).toSorted(), + }); }; return key(issueListPreferences(view.preferences)) === key(preferences); } diff --git a/apps/web/src/components/issue/issuesSearch.logic.test.ts b/apps/web/src/components/issue/issuesSearch.logic.test.ts index 2d4aad1072b01..095323fc3d2b2 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.test.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; import { EnvironmentId, ProjectId } from "@t3tools/contracts"; -import { issueFilterProjects, issuesSearchFromUrl } from "./issuesSearch.logic"; +import { issueFilterProjects, issueListTargets, issuesSearchFromUrl } from "./issuesSearch.logic"; describe("issuesSearchFromUrl", () => { it("replaces a malformed filter instead of letting the raw value through", () => { @@ -19,11 +19,48 @@ describe("issuesSearchFromUrl", () => { label: ["bug", "ui"], order: "created", }); + expect( + issuesSearchFromUrl({ hideProjects: [["env", "web"], ["env"], "api", ["env", 3]] }) + .hideProjects, + ).toEqual([ + ["env", "web"], + ["env", "3"], + ]); + }); +}); + +describe("issueListTargets", () => { + it("leaves hidden projects out and skips an environment with every project hidden", () => { + const laptop = EnvironmentId.make("laptop"); + const vps = EnvironmentId.make("vps"); + const projects = [ + { environmentId: laptop, id: ProjectId.make("web") }, + { environmentId: laptop, id: ProjectId.make("api") }, + { environmentId: vps, id: ProjectId.make("docs") }, + ]; + const input = { state: "open" } as const; + const hidden = [ + [laptop, ProjectId.make("api")], + [laptop, ProjectId.make("removed")], + [vps, ProjectId.make("docs")], + ] as const; + expect(issueListTargets([laptop, vps], projects, hidden, input)).toEqual([ + { environmentId: laptop, input: { state: "open", excludeProjectIds: ["api"] } }, + ]); + // Before the project list loads, the saved choice still leaves its projects out. + expect(issueListTargets([laptop, vps], [], hidden, input)).toEqual([ + { environmentId: laptop, input: { state: "open", excludeProjectIds: ["api", "removed"] } }, + { environmentId: vps, input: { state: "open", excludeProjectIds: ["docs"] } }, + ]); + expect(issueListTargets([laptop, vps], projects, undefined, input)).toEqual([ + { environmentId: laptop, input }, + { environmentId: vps, input }, + ]); }); }); describe("issueFilterProjects", () => { - it("keeps every project on one repository as its own choice", () => { + it("keeps every project, scratch ones too, as its own choice", () => { const environmentId = EnvironmentId.make("env"); const project = (id: string, isScratch = false) => ({ @@ -40,6 +77,7 @@ describe("issueFilterProjects", () => { ); expect(choices.map((choice) => [choice.id, choice.title])).toEqual([ ["main", "t3code · laptop · /work/main"], + ["scratch", "t3code · laptop · /work/scratch"], ["worktree", "t3code · laptop · /work/worktree"], ]); }); diff --git a/apps/web/src/components/issue/issuesSearch.logic.ts b/apps/web/src/components/issue/issuesSearch.logic.ts index 808acd1242f0d..01830e48238c2 100644 --- a/apps/web/src/components/issue/issuesSearch.logic.ts +++ b/apps/web/src/components/issue/issuesSearch.logic.ts @@ -1,6 +1,13 @@ import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-project-filter"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; -import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { + ISSUE_LIST_MAX_EXCLUDED_PROJECTS, + type EnvironmentId, + type IssueListInput, + type ProjectId, +} from "@t3tools/contracts"; + +import type { IssueListTarget } from "@t3tools/client-runtime/state/issues"; import type { IssuesSearch } from "./IssuesPage"; @@ -15,14 +22,24 @@ const labels = (raw: unknown): ReadonlyArray | undefined => { return names.length === 0 ? undefined : names.slice(0, 20); }; +const projectPairs = (raw: unknown): IssuesSearch["hideProjects"] => { + const pairs = (Array.isArray(raw) ? raw : []).flatMap((pair) => { + const environmentId = Array.isArray(pair) ? bounded(pair[0]) : undefined; + const projectId = Array.isArray(pair) ? bounded(pair[1]) : undefined; + return environmentId && projectId + ? [[environmentId as EnvironmentId, projectId as ProjectId] as const] + : []; + }); + return pairs.length === 0 ? undefined : pairs.slice(0, ISSUE_LIST_MAX_EXCLUDED_PROJECTS); +}; + // Every optional key is an own key, even when undefined: the router lays these over the parent // route's unvalidated search, where a key left out would keep its raw value. export const issuesSearchFromUrl = (raw: Record): IssuesSearch => ({ who: raw.who === "assigned" || raw.who === "authored" || raw.who === "mentioned" ? raw.who : "all", status: raw.status === "closed" || raw.status === "all" ? raw.status : "open", - issueServer: bounded(raw.issueServer) as EnvironmentId | undefined, - issueProject: bounded(raw.issueProject) as ProjectId | undefined, + hideProjects: projectPairs(raw.hideProjects), host: bounded(raw.host), q: bounded(raw.q), label: labels(raw.label), @@ -36,14 +53,53 @@ export const issuesSearchFromUrl = (raw: Record): IssuesSearch key: bounded(raw.key), }); -/** One choice per project: projects on one repository can read different Linear teams. */ +/** + * One choice per project: projects on one repository can read different Linear teams. Scratch + * projects stay, since Settings can bind one to a Linear team. + */ export const issueFilterProjects = ( projects: ReadonlyArray, environmentLabels: ReadonlyMap, ) => pullRequestFilterProjects( - projects - .filter((project) => !project.isScratch) - .map((project) => ({ ...project, repositoryIdentity: null })), + projects.map((project) => ({ ...project, repositoryIdentity: null })), environmentLabels, ); + +/** The same key as `pullRequestProjectKey`. */ +const projectKey = (project: { readonly id: ProjectId; readonly environmentId: EnvironmentId }) => + JSON.stringify([project.environmentId, project.id]); + +export const issueProjectKeys = (pairs: IssuesSearch["hideProjects"]): ReadonlySet => + new Set((pairs ?? []).map((pair) => JSON.stringify(pair))); + +/** + * Each environment leaves out its hidden projects, named from the saved pairs so a listing sent + * before the project list loads still leaves them out. One with every project hidden is not read. + * Rows past the request limit are hidden on the client. + */ +export function issueListTargets( + environmentIds: ReadonlyArray, + projects: ReadonlyArray<{ readonly id: ProjectId; readonly environmentId: EnvironmentId }>, + hidden: IssuesSearch["hideProjects"], + input: IssueListInput, +): ReadonlyArray { + const keys = issueProjectKeys(hidden); + return environmentIds.flatMap((environmentId) => { + const own = projects.filter((project) => project.environmentId === environmentId); + if (own.length > 0 && own.every((project) => keys.has(projectKey(project)))) return []; + const excludeProjectIds = ( + own.length > 0 + ? own.filter((project) => keys.has(projectKey(project))).map((project) => project.id) + : (hidden ?? []) + .filter(([environment]) => environment === environmentId) + .map(([, projectId]) => projectId) + ).slice(0, ISSUE_LIST_MAX_EXCLUDED_PROJECTS); + return [ + { + environmentId, + input: excludeProjectIds.length ? { ...input, excludeProjectIds } : input, + }, + ]; + }); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 2ec76aa57cfd7..76c02fcf63f94 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5779,9 +5779,12 @@ "1cf216566c1ee064": "Projekt nicht verfügbar", "b5ddadeb0810688c": "Status", "93c1fc19d9bf1db0": "Beteiligung", + "d5a8b335d88b65bc": "{hidden} ausgeblendet", "2160067266a61dd8": "Beliebig", "cd4ec4acf33c65b9": "{count, plural, one {{count} Label} other {{count} Labels}}", "bfd20acb8b7dee6b": "Beliebig", + "ad208e3e32c85029": "Alle ausblenden", + "77ce79d865716719": "Keine passenden Projekte.", "af7eb4f9c7f0f575": "Filter", "08247dd39b0c85ff": "Zugewiesene Person", "5cad5a7879c8d38c": "Keine Labels gefunden", @@ -5818,6 +5821,7 @@ "297613ddcf68d031": "Sortieren", "4aa8190ec693085e": "Nach Tracker filtern", "d44aed6ee67982dd": "Issues aktualisieren", + "df23678c28c56593": "Alle Projekte sind ausgeblendet", "2ccf231996dc89c2": "Keine Tracker zum Lesen", "ffdb63a22901a1fa": "Füge ein Projekt hinzu, dessen Remote bei einem unterstützten Tracker liegt.", "403e9debff81d7df": [ @@ -9724,7 +9728,6 @@ "51497bd401292062": "Gedrückt halten", "9d6cc6ac23312071": "Doppelt drücken", "f001fa7b329c8fbf": "Erfolgreiche ausblenden", - "ad208e3e32c85029": "Alle ausblenden", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Nur Status", "cf0f7fc3df26fa75": "Status und Nachrichten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 83909c95ae905..7895391f00f4b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5780,9 +5780,12 @@ "1cf216566c1ee064": "Unavailable project", "b5ddadeb0810688c": "State", "93c1fc19d9bf1db0": "Involvement", + "d5a8b335d88b65bc": "{hidden} hidden", "2160067266a61dd8": "Any", "cd4ec4acf33c65b9": "{count, plural, one {{count} label} other {{count} labels}}", "bfd20acb8b7dee6b": "Anyone", + "ad208e3e32c85029": "Hide all", + "77ce79d865716719": "No matching projects.", "af7eb4f9c7f0f575": "Filters", "08247dd39b0c85ff": "Assignee", "5cad5a7879c8d38c": "No labels found", @@ -5819,6 +5822,7 @@ "297613ddcf68d031": "Sort", "4aa8190ec693085e": "Filter by tracker", "d44aed6ee67982dd": "Refresh issues", + "df23678c28c56593": "Every project is hidden", "2ccf231996dc89c2": "No trackers to read", "ffdb63a22901a1fa": "Add a project whose remote is on a supported tracker.", "403e9debff81d7df": [ @@ -9733,7 +9737,6 @@ "51497bd401292062": "Hold", "9d6cc6ac23312071": "Double press", "f001fa7b329c8fbf": "Hide successful", - "ad208e3e32c85029": "Hide all", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Status only", "cf0f7fc3df26fa75": "Status and messages", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 58a70229908d8..9dcdb371970d1 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5778,9 +5778,12 @@ "1cf216566c1ee064": "Proyecto no disponible", "b5ddadeb0810688c": "Estado", "93c1fc19d9bf1db0": "Participación", + "d5a8b335d88b65bc": "{hidden} ocultos", "2160067266a61dd8": "Cualquiera", "cd4ec4acf33c65b9": "{count, plural, one {{count} etiqueta} other {{count} etiquetas}}", "bfd20acb8b7dee6b": "Cualquiera", + "ad208e3e32c85029": "Ocultar todo", + "77ce79d865716719": "No hay proyectos que coincidan.", "af7eb4f9c7f0f575": "Filtros", "08247dd39b0c85ff": "Asignado", "5cad5a7879c8d38c": "No se encontraron etiquetas", @@ -5817,6 +5820,7 @@ "297613ddcf68d031": "Ordenar", "4aa8190ec693085e": "Filtrar por gestor de issues", "d44aed6ee67982dd": "Actualizar issues", + "df23678c28c56593": "Todos los proyectos están ocultos", "2ccf231996dc89c2": "No hay gestores de issues que leer", "ffdb63a22901a1fa": "Añade un proyecto cuyo remoto esté en un gestor de issues compatible.", "403e9debff81d7df": [ @@ -9721,7 +9725,6 @@ "51497bd401292062": "Mantener pulsado", "9d6cc6ac23312071": "Doble pulsación", "f001fa7b329c8fbf": "Ocultar las correctas", - "ad208e3e32c85029": "Ocultar todo", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Solo el estado", "cf0f7fc3df26fa75": "Estado y mensajes", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 829d5654d59e5..9ece50a183cf6 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5779,9 +5779,12 @@ "1cf216566c1ee064": "Projet indisponible", "b5ddadeb0810688c": "État", "93c1fc19d9bf1db0": "Participation", + "d5a8b335d88b65bc": "{hidden} masqués", "2160067266a61dd8": "Tous", "cd4ec4acf33c65b9": "{count, plural, one {{count} libellé} other {{count} libellés}}", "bfd20acb8b7dee6b": "N’importe qui", + "ad208e3e32c85029": "Tout masquer", + "77ce79d865716719": "Aucun projet correspondant.", "af7eb4f9c7f0f575": "Filtres", "08247dd39b0c85ff": "Assigné", "5cad5a7879c8d38c": "Aucun libellé trouvé", @@ -5818,6 +5821,7 @@ "297613ddcf68d031": "Trier", "4aa8190ec693085e": "Filtrer par gestionnaire de tickets", "d44aed6ee67982dd": "Actualiser les tickets", + "df23678c28c56593": "Tous les projets sont masqués", "2ccf231996dc89c2": "Aucun gestionnaire de tickets à lire", "ffdb63a22901a1fa": "Ajoutez un projet dont le remote est sur un gestionnaire de tickets pris en charge.", "403e9debff81d7df": [ @@ -9723,7 +9727,6 @@ "51497bd401292062": "Appui long", "9d6cc6ac23312071": "Double appui", "f001fa7b329c8fbf": "Masquer les réussis", - "ad208e3e32c85029": "Tout masquer", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Statut uniquement", "cf0f7fc3df26fa75": "Statut et messages", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index dac6333be5e1a..6370a88d22e68 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5761,9 +5761,12 @@ "1cf216566c1ee064": "利用できないプロジェクト", "b5ddadeb0810688c": "状態", "93c1fc19d9bf1db0": "関与", + "d5a8b335d88b65bc": "{hidden} 件非表示", "2160067266a61dd8": "すべて", "cd4ec4acf33c65b9": "{count, plural, other {{count} 個のラベル}}", "bfd20acb8b7dee6b": "すべてのユーザー", + "ad208e3e32c85029": "すべて非表示", + "77ce79d865716719": "一致するプロジェクトはありません。", "af7eb4f9c7f0f575": "フィルター", "08247dd39b0c85ff": "担当者", "5cad5a7879c8d38c": "ラベルが見つかりません", @@ -5800,6 +5803,7 @@ "297613ddcf68d031": "並べ替え", "4aa8190ec693085e": "トラッカーで絞り込む", "d44aed6ee67982dd": "Issue を更新", + "df23678c28c56593": "すべてのプロジェクトが非表示です", "2ccf231996dc89c2": "読み取れるトラッカーがありません", "ffdb63a22901a1fa": "リモートが対応トラッカー上にあるプロジェクトを追加してください。", "403e9debff81d7df": [ @@ -9675,7 +9679,6 @@ "51497bd401292062": "長押し", "9d6cc6ac23312071": "2 回押し", "f001fa7b329c8fbf": "成功したものを非表示", - "ad208e3e32c85029": "すべて非表示", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "ステータスのみ", "cf0f7fc3df26fa75": "ステータスとメッセージ", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 937913f4ba846..da9457df746ac 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5759,9 +5759,12 @@ "1cf216566c1ee064": "사용할 수 없는 프로젝트", "b5ddadeb0810688c": "상태", "93c1fc19d9bf1db0": "참여", + "d5a8b335d88b65bc": "{hidden}개 숨김", "2160067266a61dd8": "전체", "cd4ec4acf33c65b9": "{count, plural, other {레이블 {count}개}}", "bfd20acb8b7dee6b": "모든 사람", + "ad208e3e32c85029": "모두 숨기기", + "77ce79d865716719": "일치하는 프로젝트가 없습니다.", "af7eb4f9c7f0f575": "필터", "08247dd39b0c85ff": "담당자", "5cad5a7879c8d38c": "레이블을 찾을 수 없음", @@ -5798,6 +5801,7 @@ "297613ddcf68d031": "정렬", "4aa8190ec693085e": "트래커별 필터", "d44aed6ee67982dd": "이슈 새로 고침", + "df23678c28c56593": "모든 프로젝트가 숨겨져 있습니다", "2ccf231996dc89c2": "읽을 트래커 없음", "ffdb63a22901a1fa": "원격 저장소가 지원되는 트래커에 있는 프로젝트를 추가하세요.", "403e9debff81d7df": [ @@ -9678,7 +9682,6 @@ "51497bd401292062": "길게 누르기", "9d6cc6ac23312071": "두 번 누르기", "f001fa7b329c8fbf": "성공한 항목 숨기기", - "ad208e3e32c85029": "모두 숨기기", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "상태만", "cf0f7fc3df26fa75": "상태 및 메시지", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6ab44ccc24f70..bf2af0b1f9867 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5778,9 +5778,12 @@ "1cf216566c1ee064": "Projeto indisponível", "b5ddadeb0810688c": "Estado", "93c1fc19d9bf1db0": "Envolvimento", + "d5a8b335d88b65bc": "{hidden} ocultos", "2160067266a61dd8": "Qualquer", "cd4ec4acf33c65b9": "{count, plural, one {{count} rótulo} other {{count} rótulos}}", "bfd20acb8b7dee6b": "Qualquer pessoa", + "ad208e3e32c85029": "Ocultar todas", + "77ce79d865716719": "Nenhum projeto correspondente.", "af7eb4f9c7f0f575": "Filtros", "08247dd39b0c85ff": "Responsável", "5cad5a7879c8d38c": "Nenhum rótulo encontrado", @@ -5817,6 +5820,7 @@ "297613ddcf68d031": "Ordenar", "4aa8190ec693085e": "Filtrar por rastreador", "d44aed6ee67982dd": "Atualizar issues", + "df23678c28c56593": "Todos os projetos estão ocultos", "2ccf231996dc89c2": "Nenhum rastreador para ler", "ffdb63a22901a1fa": "Adicione um projeto cujo remoto esteja em um rastreador compatível.", "403e9debff81d7df": [ @@ -9722,7 +9726,6 @@ "51497bd401292062": "Manter pressionado", "9d6cc6ac23312071": "Pressionar duas vezes", "f001fa7b329c8fbf": "Ocultar bem-sucedidas", - "ad208e3e32c85029": "Ocultar todas", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Só status", "cf0f7fc3df26fa75": "Status e mensagens", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index ea00719da3b6b..fefbaa68105b6 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5778,9 +5778,12 @@ "1cf216566c1ee064": "Проект недоступен", "b5ddadeb0810688c": "Состояние", "93c1fc19d9bf1db0": "Участие", + "d5a8b335d88b65bc": "Скрыто: {hidden}", "2160067266a61dd8": "Любая", "cd4ec4acf33c65b9": "{count, plural, one {{count} метка} few {{count} метки} many {{count} меток} other {{count} метки}}", "bfd20acb8b7dee6b": "Любой", + "ad208e3e32c85029": "Скрывать все", + "77ce79d865716719": "Нет подходящих проектов.", "af7eb4f9c7f0f575": "Фильтры", "08247dd39b0c85ff": "Исполнитель", "5cad5a7879c8d38c": "Метки не найдены", @@ -5817,6 +5820,7 @@ "297613ddcf68d031": "Сортировать", "4aa8190ec693085e": "Фильтр по трекеру", "d44aed6ee67982dd": "Обновить issue", + "df23678c28c56593": "Все проекты скрыты", "2ccf231996dc89c2": "Нет трекеров для чтения", "ffdb63a22901a1fa": "Добавьте проект, у которого remote находится в поддерживаемом трекере.", "403e9debff81d7df": [ @@ -9725,7 +9729,6 @@ "51497bd401292062": "Удержание", "9d6cc6ac23312071": "Двойное нажатие", "f001fa7b329c8fbf": "Скрывать успешные", - "ad208e3e32c85029": "Скрывать все", "c80e4bb3201efd71": "Дзен", "0cb9ffcd1fb46b0c": "Только статус", "cf0f7fc3df26fa75": "Статус и сообщения", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index baf63922386cb..69eca250158a0 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5779,9 +5779,12 @@ "1cf216566c1ee064": "Projektet är inte tillgängligt", "b5ddadeb0810688c": "Status", "93c1fc19d9bf1db0": "Inblandning", + "d5a8b335d88b65bc": "{hidden} dolda", "2160067266a61dd8": "Alla", "cd4ec4acf33c65b9": "{count, plural, one {{count} etikett} other {{count} etiketter}}", "bfd20acb8b7dee6b": "Vem som helst", + "ad208e3e32c85029": "Dölj alla", + "77ce79d865716719": "Inga matchande projekt.", "af7eb4f9c7f0f575": "Filter", "08247dd39b0c85ff": "Tilldelad", "5cad5a7879c8d38c": "Inga etiketter hittades", @@ -5818,6 +5821,7 @@ "297613ddcf68d031": "Sortera", "4aa8190ec693085e": "Filtrera efter ärendehanterare", "d44aed6ee67982dd": "Uppdatera ärenden", + "df23678c28c56593": "Alla projekt är dolda", "2ccf231996dc89c2": "Inga ärendehanterare att läsa", "ffdb63a22901a1fa": "Lägg till ett projekt vars fjärr finns i en ärendehanterare som stöds.", "403e9debff81d7df": [ @@ -9731,7 +9735,6 @@ "51497bd401292062": "Håll ned", "9d6cc6ac23312071": "Dubbeltryck", "f001fa7b329c8fbf": "Dölj lyckade", - "ad208e3e32c85029": "Dölj alla", "c80e4bb3201efd71": "Zen", "0cb9ffcd1fb46b0c": "Endast status", "cf0f7fc3df26fa75": "Status och meddelanden", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 8f05fc5be57bc..1fcd0b2f96920 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5785,9 +5785,12 @@ "1cf216566c1ee064": "不可用的项目", "b5ddadeb0810688c": "状态", "93c1fc19d9bf1db0": "参与方式", + "d5a8b335d88b65bc": "已隐藏 {hidden} 个", "2160067266a61dd8": "任意", "cd4ec4acf33c65b9": "{count, plural, other {{count} 个标签}}", "bfd20acb8b7dee6b": "任何人", + "ad208e3e32c85029": "全部隐藏", + "77ce79d865716719": "没有匹配的项目。", "af7eb4f9c7f0f575": "筛选条件", "08247dd39b0c85ff": "受理人", "5cad5a7879c8d38c": "未找到标签", @@ -5824,6 +5827,7 @@ "297613ddcf68d031": "排序", "4aa8190ec693085e": "按跟踪器筛选", "d44aed6ee67982dd": "刷新 issue", + "df23678c28c56593": "所有项目均已隐藏", "2ccf231996dc89c2": "没有可读取的跟踪器", "ffdb63a22901a1fa": "请添加一个远端位于受支持跟踪器上的项目。", "403e9debff81d7df": [ @@ -9738,7 +9742,6 @@ "51497bd401292062": "长按", "9d6cc6ac23312071": "连按两次", "f001fa7b329c8fbf": "隐藏成功的调用", - "ad208e3e32c85029": "全部隐藏", "c80e4bb3201efd71": "专注模式", "0cb9ffcd1fb46b0c": "仅状态", "cf0f7fc3df26fa75": "状态和消息", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..138e4c9acf62e 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -369,8 +369,9 @@ out from the matching organization and repository. The Issues page lists the issues of every project whose remote is on GitHub, GitLab, Azure DevOps or Forgejo, grouped per tracker account. Open it from the sidebar's utility row or with **Open issues** in the command palette. Filter by open or closed, by your involvement -(assigned, opened by you, mentioning you), by project, and by tracker; the search box asks the tracker -itself where it can search. Press **Load more** at the end of a group to read further back. +(assigned, opened by you, mentioning you), and by tracker. Under **Projects**, uncheck the +projects you do not want to see; the list remembers them, and a project you add later shows. +The search box asks the tracker itself where it can search. Press **Load more** at the end of a group to read further back. The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull requests. diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 300eacc5a3408..5085c10e51887 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -6,7 +6,6 @@ import type { IssueTrackerSummary, ProjectId, } from "@t3tools/contracts"; -import type { EnvironmentProject } from "./state/models.ts"; import { describe, expect, it } from "vite-plus/test"; import { @@ -143,46 +142,6 @@ describe("issueFilterScopes", () => { [environmentId, hold(answer({ trackers: [tracker({})], entries: [], scopes: [scope] }))], ]); expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); - const otherProjectId = "web" as ProjectId; - const projects = [api, otherProjectId].map((id) => ({ - id, - environmentId, - repositoryIdentity: { - provider: "github", - canonicalKey: `github.com/acme/${id}`, - owner: "acme", - name: id, - }, - })) as unknown as ReadonlyArray; - const withRepositories = new Map([ - [ - environmentId, - hold( - answer({ - trackers: [ - tracker({}), - tracker({ tracker: "github" as IssueTrackerKind, host: "github.com" }), - ], - scopes: [scope, { ...scope, projectId: otherProjectId, scope: "WEB" }], - }), - ), - ], - ]); - expect( - issueFilterScopes(withRepositories, projects, { environmentId, projectId: api }), - ).toEqual([ - { - environmentId, - input: { projectId: api, tracker: "github", host: "github.com", scope: "acme/api" }, - }, - { environmentId, input: scope }, - ]); - expect( - issueFilterScopes(withRepositories, projects, { - environmentId: "other" as EnvironmentId, - projectId: api, - }), - ).toEqual([]); }); it("skips a tracker that cannot be read", () => { diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index a5f3f2d5d1709..df0f80aae5c57 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -8,7 +8,6 @@ import type { IssueScopeRef, IssueTrackerSummary, SourceControlProviderKind, - ProjectId, } from "@t3tools/contracts"; import { mergeIssueListPage } from "./state/issues.ts"; @@ -168,14 +167,11 @@ export function groupIssues( export function issueFilterScopes( held: ReadonlyMap, projects: ReadonlyArray, - selectedProject?: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; for (const [environmentId, page] of held) { - if (selectedProject && selectedProject.environmentId !== environmentId) continue; for (const project of projects) { - if (selectedProject && selectedProject.projectId !== project.id) continue; if (project.environmentId !== environmentId) continue; const identity = project.repositoryIdentity; const kind = identity?.provider as SourceControlProviderKind | undefined; @@ -208,7 +204,6 @@ export function issueFilterScopes( scope, })); for (const input of covered) { - if (selectedProject && selectedProject.projectId !== input.projectId) continue; const host = input.host?.toLowerCase(); const tracker = page.answer.trackers.find( (t) => t.tracker === input.tracker && t.host.toLowerCase() === host, diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 07f2eab6e6a42..b17911da295e2 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -256,10 +256,16 @@ export const IssueListCursors = Schema.Record( ); export type IssueListCursors = typeof IssueListCursors.Type; +export const ISSUE_LIST_MAX_EXCLUDED_PROJECTS = 1_000; + export const IssueListInput = Schema.Struct({ state: IssueListState, involvement: Schema.optional(IssueInvolvement), projectId: Schema.optional(ProjectId), + /** Projects left out of the listing, as the issues page hides them. */ + excludeProjectIds: Schema.optional( + Schema.Array(ProjectId).check(Schema.isMaxLength(ISSUE_LIST_MAX_EXCLUDED_PROJECTS)), + ), /** Narrows to one host, named as the host itself. Absent means every host the workspace has. */ host: Schema.optional(TrimmedNonEmptyString), /** Rows per scope, which with a continuation is rows per slice. */ From 38d27db7467099babcf6dfb39db04938603137a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 16:49:10 -0800 Subject: [PATCH 06/58] perf(server): refreshing a branch list frees the snapshot it replaces (#39440) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 50 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 32 +++++++++---- 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 1d5c25573a851..4d248f465f454 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1712,6 +1712,56 @@ it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => ), ); +it.effect("superseded ref snapshots of one repository do not evict another's", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const quietRepo = yield* makeTmpDir(); + const quietRepoRealPath = NodeFS.realpathSync.native(quietRepo); + const quietRepoScans = yield* Ref.make(0); + const countingSpawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if ( + ChildProcess.isStandardCommand(command) && + command.args.includes("for-each-ref") && + command.args.includes("refs/remotes") && + NodeFS.realpathSync.native(String(command.options.cwd)).startsWith(quietRepoRealPath) + ) { + yield* Ref.update(quietRepoScans, (count) => count + 1); + } + return yield* delegate.spawn(command); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner), + ); + const busyRepo = yield* makeTmpDir(); + yield* initRepoWithCommit(quietRepo).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + yield* initRepoWithCommit(busyRepo).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + + yield* driver.listRefs({ cwd: quietRepo }); + // More epochs than the snapshot cache holds. + for (let index = 0; index < 70; index++) { + yield* driver.invalidateRefs(busyRepo); + yield* driver.listRefs({ cwd: busyRepo }); + } + yield* driver.listRefs({ cwd: quietRepo }); + + assert.equal(yield* Ref.get(quietRepoScans), 1); + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("invalidates a ref snapshot when a mutation fails after changing Git", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 3b1a066303ba3..b88ade8863259 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -5037,15 +5037,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_REFS_SNAPSHOT_CACHE_TTL : Duration.zero), }, ); + // Readers only ask for the current epoch and Cache expires entries lazily, so a superseded + // snapshot (megabytes in a repository with many remote branches) would stay until evicted. + const advanceListRefsEpoch = Effect.fn("GitVcsDriver.advanceListRefsEpoch")(function* ( + gitCommonDir: string, + ) { + const previous = listRefsEpochByCommonDir.get(gitCommonDir); + const epoch = bumpListRefsEpoch(gitCommonDir); + if (previous !== undefined) { + yield* Cache.invalidate( + listRefsSnapshotCache, + new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: previous }), + ); + } + return epoch; + }); const listRefsRefreshSnapshotCache = yield* Cache.makeWith( (cacheKey: GitRefsRefreshCacheKey) => - Effect.suspend(() => { - const epoch = bumpListRefsEpoch(cacheKey.gitCommonDir); - return Cache.get( - listRefsSnapshotCache, - new GitRefsSnapshotCacheKey({ gitCommonDir: cacheKey.gitCommonDir, epoch }), - ); - }), + advanceListRefsEpoch(cacheKey.gitCommonDir).pipe( + Effect.flatMap((epoch) => + Cache.get( + listRefsSnapshotCache, + new GitRefsSnapshotCacheKey({ gitCommonDir: cacheKey.gitCommonDir, epoch }), + ), + ), + ), { capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY, timeToLive: (exit) => @@ -5087,7 +5103,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (commonDir == null) return; const previousGeneration = currentListRefsGeneration(commonDir); bumpListRefsGeneration(commonDir); - bumpListRefsEpoch(commonDir); + yield* advanceListRefsEpoch(commonDir); yield* Cache.invalidate( listRefsRefreshSnapshotCache, new GitRefsRefreshCacheKey({ From bb1a66a3a45f258da139a2a68f074b9fbc0f4b24 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:58:06 +0300 Subject: [PATCH 07/58] feat(web): reference a side chat from its main thread with Add to chat and @ (#38323) Co-authored-by: Yash Singh --- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/web/src/components/ThreadContextChip.tsx | 17 +++++- .../chat/MarkdownThreadLink.browser.test.tsx | 5 ++ apps/web/src/components/chat/SideChatPane.tsx | 60 ++++++------------- apps/web/src/i18n/translations/de.json | 10 +--- apps/web/src/i18n/translations/en.json | 10 +--- apps/web/src/i18n/translations/es.json | 10 +--- apps/web/src/i18n/translations/fr.json | 10 +--- apps/web/src/i18n/translations/ja.json | 10 +--- apps/web/src/i18n/translations/ko.json | 10 +--- apps/web/src/i18n/translations/pt-BR.json | 10 +--- apps/web/src/i18n/translations/ru.json | 10 +--- apps/web/src/i18n/translations/sv.json | 10 +--- apps/web/src/i18n/translations/zh.json | 10 +--- docs/user/thread-sidebar.md | 8 ++- .../src/composerThreadItems.test.ts | 28 +++++++++ .../client-runtime/src/composerThreadItems.ts | 19 ++++-- 26 files changed, 115 insertions(+), 142 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 14a72ef456de5..afa1198fff177 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Nebenchat", "23be753133ae6950": "Thread", "0001ae5846061bb6": "Thread auf {machine}", "eef7f4dacbc3c3f2": "Rechner", @@ -4801,7 +4802,6 @@ "13eb3e529a3e9bff": "Aus dem Thread entfernen", "986951276ab5723d": "Verknüpfung mit Thread lösen", "a9c188a91c93fdb4": "Beobachten konnte nicht geändert werden", - "4bcfa3b976a421cf": "Nebenchat", "afd7cfeb929fcdbd": "Der Nebenchat wurde erstellt, hat dieses Gerät aber nicht erreicht.", "0efeaa8d0ca3a757": "Der Nebenchat ist nicht mehr verfügbar.", "61fc2531d076d396": "Der Berechtigungsmodus des Nebenchats konnte nicht festgelegt werden.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 3596aa21e36af..f699ea466b076 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Side chat", "23be753133ae6950": "Thread", "0001ae5846061bb6": "Thread on {machine}", "eef7f4dacbc3c3f2": "Machine", @@ -4802,7 +4803,6 @@ "13eb3e529a3e9bff": "Dismiss from thread", "986951276ab5723d": "Unlink from thread", "a9c188a91c93fdb4": "Couldn't change watching", - "4bcfa3b976a421cf": "Side chat", "afd7cfeb929fcdbd": "The side chat was created, but it did not reach this device.", "0efeaa8d0ca3a757": "The side chat is no longer available.", "61fc2531d076d396": "Could not set the side chat's permission mode.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index a18764f050d09..0e9074eea47d1 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Chat lateral", "23be753133ae6950": "Hilo", "0001ae5846061bb6": "Hilo en {machine}", "eef7f4dacbc3c3f2": "Máquina", @@ -4794,7 +4795,6 @@ "13eb3e529a3e9bff": "Descartar del hilo", "986951276ab5723d": "Desvincular del hilo", "a9c188a91c93fdb4": "No se pudo cambiar el seguimiento", - "4bcfa3b976a421cf": "Chat lateral", "afd7cfeb929fcdbd": "Se creó el chat lateral, pero no llegó a este dispositivo.", "0efeaa8d0ca3a757": "El chat lateral ya no está disponible.", "61fc2531d076d396": "No se pudo definir el modo de permisos del chat lateral.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 9f12d87dd513b..f353a6b4986d8 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Discussion annexe", "23be753133ae6950": "Fil", "0001ae5846061bb6": "Fil sur {machine}", "eef7f4dacbc3c3f2": "Machine", @@ -4795,7 +4796,6 @@ "13eb3e529a3e9bff": "Écarter du fil", "986951276ab5723d": "Dissocier du fil", "a9c188a91c93fdb4": "Impossible de modifier le suivi", - "4bcfa3b976a421cf": "Discussion annexe", "afd7cfeb929fcdbd": "La discussion annexe a été créée, mais elle n’est pas parvenue sur cet appareil.", "0efeaa8d0ca3a757": "La discussion annexe n’est plus disponible.", "61fc2531d076d396": "Impossible de définir le mode d’autorisation de la discussion annexe.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 441175f85337e..94a0bd9a1d3e2 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "サイドチャット", "23be753133ae6950": "スレッド", "0001ae5846061bb6": "{machine} 上のスレッド", "eef7f4dacbc3c3f2": "マシン", @@ -4776,7 +4777,6 @@ "13eb3e529a3e9bff": "スレッドから除外", "986951276ab5723d": "スレッドからリンクを解除", "a9c188a91c93fdb4": "監視を変更できませんでした", - "4bcfa3b976a421cf": "サイドチャット", "afd7cfeb929fcdbd": "サイドチャットは作成されましたが、このデバイスに届きませんでした。", "0efeaa8d0ca3a757": "サイドチャットは利用できなくなりました。", "61fc2531d076d396": "サイドチャットの権限モードを設定できませんでした。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index c73c767074bde..56ee179e894df 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "사이드 채팅", "23be753133ae6950": "스레드", "0001ae5846061bb6": "{machine}의 스레드", "eef7f4dacbc3c3f2": "머신", @@ -4781,7 +4782,6 @@ "13eb3e529a3e9bff": "스레드에서 제외", "986951276ab5723d": "스레드에서 연결 해제", "a9c188a91c93fdb4": "지켜보기를 변경할 수 없습니다", - "4bcfa3b976a421cf": "사이드 채팅", "afd7cfeb929fcdbd": "사이드 채팅이 생성되었지만 이 기기에 도착하지 않았습니다.", "0efeaa8d0ca3a757": "사이드 채팅을 더 이상 사용할 수 없습니다.", "61fc2531d076d396": "사이드 채팅의 권한 모드를 설정할 수 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 8c9071db5dfee..9fbcaaf1d6fa4 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Chat paralelo", "23be753133ae6950": "Thread", "0001ae5846061bb6": "Thread em {machine}", "eef7f4dacbc3c3f2": "Máquina", @@ -4795,7 +4796,6 @@ "13eb3e529a3e9bff": "Dispensar da thread", "986951276ab5723d": "Desvincular da thread", "a9c188a91c93fdb4": "Não foi possível alterar o acompanhamento", - "4bcfa3b976a421cf": "Chat paralelo", "afd7cfeb929fcdbd": "O chat paralelo foi criado, mas não chegou a este dispositivo.", "0efeaa8d0ca3a757": "O chat paralelo não está mais disponível.", "61fc2531d076d396": "Não foi possível definir o modo de permissão do chat paralelo.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index ce752d7d25c6f..31c1677c7e12d 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Боковой чат", "23be753133ae6950": "Тред", "0001ae5846061bb6": "Тред на {machine}", "eef7f4dacbc3c3f2": "Машина", @@ -4873,7 +4874,6 @@ "13eb3e529a3e9bff": "Убрать из треда", "986951276ab5723d": "Отвязать от треда", "a9c188a91c93fdb4": "Не удалось изменить отслеживание", - "4bcfa3b976a421cf": "Боковой чат", "afd7cfeb929fcdbd": "Боковой чат создан, но не дошёл до этого устройства.", "0efeaa8d0ca3a757": "Боковой чат больше недоступен.", "61fc2531d076d396": "Не удалось задать режим разрешений бокового чата.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index c87a75ea47e5d..4c62afb649f59 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "Sidochatt", "23be753133ae6950": "Tråd", "0001ae5846061bb6": "Tråd på {machine}", "eef7f4dacbc3c3f2": "Dator", @@ -4801,7 +4802,6 @@ "13eb3e529a3e9bff": "Avfärda från tråden", "986951276ab5723d": "Ta bort länk från tråd", "a9c188a91c93fdb4": "Kunde inte ändra bevakningen", - "4bcfa3b976a421cf": "Sidochatt", "afd7cfeb929fcdbd": "Sidochatten skapades, men den nådde inte den här enheten.", "0efeaa8d0ca3a757": "Sidochatten är inte längre tillgänglig.", "61fc2531d076d396": "Kunde inte ange sidochattens behörighetsläge.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index ce8b8caf281d5..d1d05c0aad116 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1,4 +1,5 @@ { + "4bcfa3b976a421cf": "侧聊", "23be753133ae6950": "会话", "0001ae5846061bb6": "{machine} 上的会话", "eef7f4dacbc3c3f2": "机器", @@ -4784,7 +4785,6 @@ "13eb3e529a3e9bff": "从会话中忽略", "986951276ab5723d": "取消与会话的关联", "a9c188a91c93fdb4": "无法更改关注状态", - "4bcfa3b976a421cf": "侧聊", "afd7cfeb929fcdbd": "侧聊已创建,但未同步到此设备。", "0efeaa8d0ca3a757": "这段侧聊已不可用。", "61fc2531d076d396": "无法设置侧聊的权限模式。", diff --git a/apps/web/src/components/ThreadContextChip.tsx b/apps/web/src/components/ThreadContextChip.tsx index 997324c50d9f7..cc099fc791a8c 100644 --- a/apps/web/src/components/ThreadContextChip.tsx +++ b/apps/web/src/components/ThreadContextChip.tsx @@ -1,9 +1,11 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import type { ThreadContextRecord, ProjectId } from "@t3tools/contracts"; -import { Link } from "@tanstack/react-router"; +import { Link, useNavigate } from "@tanstack/react-router"; import { MessagesSquareIcon } from "lucide-react"; import { useGT } from "gt-react"; +import { resolveThreadOpenRoute } from "~/lib/sideChatPane"; +import { buildThreadRouteParams } from "~/threadRoutes"; import { useProject, useThreadShell } from "~/state/entities"; import { orchestrationEnvironment } from "~/state/orchestration"; import { useEnvironmentQuery } from "~/state/query"; @@ -32,6 +34,7 @@ export function ThreadContextChip(props: { const projectId = shell?.projectId ?? props.projectId ?? metadata?.projectId; const project = useProject(projectId ? scopeProjectRef(environmentId, projectId) : null); const title = shell?.title?.trim() || metadata?.title.trim() || props.record.title; + const navigate = useNavigate(); return ( { + if (shell?.lineage.sideChat !== true || event.button !== 0) return; + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + // A side chat opens as a tab beside its parent, not as its own page. + event.preventDefault(); + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams( + resolveThreadOpenRoute({ environmentId, threadId }, shell), + ), + }); + }} draggable={false} /> } diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index 6febe0ff8b343..80e8cdf0dbd76 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -51,6 +51,11 @@ function setup() { id: ThreadId.make("older-thread"), title: "Remote thread", projectId: ProjectId.make("essay-project"), + lineage: { + rootThreadId: ThreadId.make("older-thread"), + parentThreadId: null, + relationshipToParent: null, + }, }; return { reply, registry: AtomRegistry.make() }; } diff --git a/apps/web/src/components/chat/SideChatPane.tsx b/apps/web/src/components/chat/SideChatPane.tsx index 5fd40e5b001cc..ffd3845022a35 100644 --- a/apps/web/src/components/chat/SideChatPane.tsx +++ b/apps/web/src/components/chat/SideChatPane.tsx @@ -1,6 +1,4 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows"; import { isAtomCommandInterrupted, settlePromise, @@ -11,6 +9,7 @@ import { type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { T, useGT } from "gt-react"; import { Trash2Icon, XIcon } from "lucide-react"; import { useEffect, useState } from "react"; @@ -22,7 +21,7 @@ import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads"; import type { SideChatParentPanel } from "../../lib/sideChatPane"; import { readLocalApi } from "../../localApi"; import { hostRightPanel, useRightPanelStore } from "../../rightPanelStore"; -import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities"; +import { useQuietThreadShell } from "../../state/entities"; import { useEnvironmentScope } from "../../state/session"; import { useEnvironmentShellHasSnapshot } from "../../state/shell"; import { threadEnvironment } from "../../state/threads"; @@ -33,7 +32,7 @@ import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { BackgroundThreadContext } from "./backgroundThread"; -/** A side chat tab: its title, Bring back, Delete and Close, over the side chat's own chat. */ +/** A side chat tab: its title, Add to chat, Delete and Close, over the side chat's own chat. */ export default function SideChatPane(props: { readonly parentRef: ScopedThreadRef; readonly threadId: ThreadId; @@ -49,47 +48,20 @@ export default function SideChatPane(props: { [parentRef, threadId], ); const shell = useQuietThreadShell(threadRef); - const parent = useQuietThreadShell(parentRef); const snapshotLoaded = useEnvironmentShellHasSnapshot(parentRef.environmentId); - const projection = useQuietThreadProjection(shell === null ? null : threadRef)?.projection; const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope); - const mergeBack = useAtomCommand(threadEnvironment.mergeBack, { reportFailure: false }); const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete); - const [bringingBack, setBringingBack] = useState(false); const [deleting, setDeleting] = useState(false); - const mergeRun = projection ? resolveLatestMergeBackRun(projection) : null; - // A pending merge-back would fail the main thread's queued message, so the server refuses it. - const bringBackBlockedReason = !canOperate - ? gt("This connection cannot change threads.") - : threadRuntimeIsActive(parent?.runtime) - ? gt("Available when the main thread is idle.") - : mergeRun === null - ? gt("Available after a finished reply.") - : null; - - const bringBack = async () => { - if (bringBackBlockedReason !== null || mergeRun === null || bringingBack) return; - setBringingBack(true); - const result = await mergeBack({ - environmentId: parentRef.environmentId, - input: { sourceThreadId: threadId, targetThreadId: parentRef.threadId, runId: mergeRun.id }, - }); - setBringingBack(false); - if (result._tag === "Success") { - toastManager.add({ - type: "success", - title: gt("Brought back"), - description: gt("The main thread gets this side chat with your next message there."), - }); - } else if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add({ - type: "error", - title: gt("Could not bring back the side chat"), - ...(error instanceof Error ? { description: error.message } : {}), + // Closing an unused side chat deletes it, which would leave the link unreadable. + const canAddToChat = shell !== null && shell.latestUserMessageAt !== null; + const addToChat = () => { + if (!canAddToChat) return; + useComposerDraftStore + .getState() + .addThreadContexts(parentRef, [threadContextRecord(threadRef, shell.title)], { + insertAtCaret: false, }); - } }; const deleteSideChat = async () => { @@ -140,15 +112,17 @@ export default function SideChatPane(props: { } /> - {bringBackBlockedReason ?? gt("Adds this side chat to the main thread's next message.")} + {canAddToChat + ? gt("Adds this side chat to the main thread's next message.") + : gt("Available after the first message.")}