diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 8e5a954501d8e..767a689568131 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -215,6 +215,8 @@ function ComposerFileAttachment( const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined; const sourceIdentifier = `draft-file:${attachment.id}`; const onPressDocument = props.onPressDocument; + const upload = useComposerAttachmentUploadState(props.environmentId, attachment.id); + const showsUploadBadge = upload !== undefined && upload.status !== "ready"; return ( <> @@ -235,7 +237,7 @@ function ComposerFileAttachment( className={ props.compact ? "items-center justify-center bg-subtle" - : "items-center justify-center gap-1 bg-subtle px-2" + : `items-center justify-center gap-1 bg-subtle px-2${showsUploadBadge ? " pb-4" : ""}` } style={style} > diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 354a86284dd3a..9f6ae1a7aaa7a 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -1,7 +1,8 @@ +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import { prependIssueComments } from "@t3tools/client-runtime/state/issues"; +import { createIssueCommentPager } from "@t3tools/client-runtime/state/issues"; import type { IssueComment, IssueEvent, @@ -12,7 +13,7 @@ import type { } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { T, useGT, useMessages, Var } from "gt-react-native"; -import { useRef, useState } from "react"; +import { useContext, useState } from "react"; import { Linking, Platform, Pressable, Share, View } from "react-native"; import { KeyboardStickyView } from "react-native-keyboard-controller"; @@ -403,6 +404,9 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { const detailAtom = issueEnvironment.detail(target); const detailQuery = useEnvironmentQuery(detailAtom); const pullRefresh = usePullToRefresh(detailAtom); + const registry = useContext(RegistryContext); + const [pager] = useState(() => createIssueCommentPager(detailAtom)); + const { comments, nextCursor, loadingOlder, canLoadOlder } = useAtomValue(pager.view); const detail = detailQuery.data; const issue: IssueSummary | null = detail ?? params.initialSummary ?? null; const access = useIssueAccess(params, detail); @@ -410,25 +414,13 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { const loadComments = useAtomCommand(issueEnvironment.comments, { reportFailure: false }); const postComment = useAtomCommand(issueEnvironment.comment, { reportFailure: false }); const setState = useAtomCommand(issueEnvironment.setState, { reportFailure: false }); - const [older, setOlder] = useState<{ - readonly seed: string | null; - readonly comments: ReadonlyArray; - readonly cursor: string | null; - } | null>(null); - const [busy, setBusy] = useState<"older" | "comment" | "state" | null>(null); + const [busy, setBusy] = useState<"comment" | "state" | null>(null); const [error, setError] = useState(null); const [composerHeight, setComposerHeight] = useState(0); - // Older pages are tied to the cursor the detail was read with; a refreshed detail starts over. - const olderComments = detail && older?.seed === detail.commentsCursor ? older.comments : []; - const nextCursor = !detail - ? null - : older?.seed === detail.commentsCursor - ? older.cursor - : detail.commentsCursor; const timeline = detail ? [ - ...prependIssueComments(detail.comments, olderComments).map((comment) => ({ + ...comments.map((comment) => ({ key: `c:${comment.id}`, at: comment.createdAt, content: ( @@ -447,7 +439,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { kind: NonNullable, command: () => Promise>, ) => { - if (busy !== null) return false; + if (busy !== null || registry.get(pager.view).loadingOlder) return false; setBusy(kind); setError(null); const failure = issueCommandError(await command()); @@ -457,28 +449,13 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { if (failure === null) refreshIssueLists(target.environmentId); return failure === null; }; - // Counts refreshes, so a page asked for before one is not laid over the read that follows it. - const refreshes = useRef(0); const loadOlder = async () => { - if (!detail || nextCursor === null || busy !== null) return; - const asked = refreshes.current; - setBusy("older"); - setError(null); - const result = await loadComments({ - ...target, - input: { ...target.input, cursor: nextCursor }, - }); - setBusy(null); - if (asked !== refreshes.current) return; - if (AsyncResult.isFailure(result)) { - setError(gt("Older comments could not be read.")); - return; - } - setOlder({ - seed: detail.commentsCursor, - comments: prependIssueComments(olderComments, result.value.comments), - cursor: result.value.nextCursor, + if (busy !== null) return; + const failure = await pager.loadOlder(registry, (cursor) => { + setError(null); + return loadComments({ ...target, input: { ...target.input, cursor } }); }); + if (failure) setError(gt("Older comments could not be read.")); }; const submitComment = (body: string) => access?.comment === true @@ -575,12 +552,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { refreshControl={ { - // Older pages are cached under the cursor, which a refresh can hand back unchanged. - refreshes.current += 1; - setOlder(null); - pullRefresh.onRefresh(); - }} + onRefresh={() => void pager.refresh(registry, pullRefresh.onRefresh)} /> } contentContainerStyle={{ @@ -652,8 +624,8 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { {nextCursor !== null ? ( + {detailQuery.error !== null && !detailQuery.isPending ? ( +
+ + {gt("Could not refresh this issue")} + {detailQuery.error} + +
+ ) : null} + {editing === "title" ? (
void loadOlder()} > {loadingOlder ? Loading… : Load older comments} diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index fb2d1b981e4e6..bd8627a2e6689 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -216,7 +216,13 @@ export function IssuesPage() { input: listInput, })); const list = useIssueList(targets); - useLiveRefresh(list.refresh, { key: JSON.stringify(targets) }); + // Refreshing a list still loading would cancel it and start over, losing the scopes already read. + useLiveRefresh( + () => { + if (!list.isPending) list.refresh(); + }, + { key: JSON.stringify(targets) }, + ); const [pages, setPages] = useState>(new Map()); const held = holdIssuePages(list.answers, pages); @@ -772,7 +778,7 @@ export function IssuesPage() { > {renderedSurface.kind === "issue" ? ( () { } function MergeButton({ reference }: { reference: PullRequestRef }) { - const { actionPending, perform } = usePullRequestActionRunner({ + const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( ); } +function setup() { + state.runAction.mockReset(); + state.newThread.mockReset(); + state.prepareThread.mockReset(); +} + it("keeps pending merges with their pull request when navigating between threads", async () => { + setup(); const first: PullRequestRef = { projectId: ProjectId.make("project"), repository: "owner/repo", @@ -54,7 +61,6 @@ it("keeps pending merges with their pull request when navigating between threads const firstResult = deferred<{ _tag: "Success"; value: void }>(); const secondResult = deferred<{ _tag: "Success"; value: void }>(); state.runAction - .mockReset() .mockReturnValueOnce(firstResult.promise) .mockReturnValueOnce(secondResult.promise); await using screen = await render(); @@ -62,6 +68,14 @@ it("keeps pending merges with their pull request when navigating between threads await userEvent.click(button); await expect.element(button).toHaveTextContent("Merging..."); + await screen.rerender( + , + ); + await expect.element(button).toHaveTextContent("Merge"); + await expect.element(button).toBeEnabled(); + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merging..."); + await expect.element(button).toBeDisabled(); await screen.rerender(); await expect.element(button).toHaveTextContent("Merge"); await expect.element(button).toBeEnabled(); @@ -102,6 +116,7 @@ function FixChecksButton() { } it("stops a pull request handoff when its loading toast is dismissed", async () => { + setup(); const prepared = deferred<{ _tag: "Success"; value: { @@ -112,10 +127,9 @@ it("stops a pull request handoff when its loading toast is dismissed", async () }; }>(); state.newThread - .mockReset() .mockResolvedValueOnce({ draftId: "draft-1", threadId: ThreadId.make("thread-1") }) .mockResolvedValueOnce({ draftId: "draft-2", threadId: ThreadId.make("thread-1") }); - state.prepareThread.mockReset().mockReturnValueOnce(prepared.promise); + state.prepareThread.mockReturnValueOnce(prepared.promise); await using screen = await render( diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 5b7210ae32b96..f7885e098d3c3 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -201,23 +201,27 @@ export function usePullRequestActionRunner({ const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false, }); - const pendingRef = useRef(new Set()); - const [pendingKeys, setPendingKeys] = useState>(() => new Set()); + const pendingRef = useRef(new Map()); + const [pendingActions, setPendingActions] = useState>( + () => new Map(), + ); const actionKey = reference === null ? null : JSON.stringify([ environmentId, + reference.projectId, reference.host ?? null, reference.repository, reference.number, ]); - const actionPending = actionKey !== null && pendingKeys.has(actionKey); + const pendingAction = actionKey === null ? null : (pendingActions.get(actionKey) ?? null); + const actionPending = pendingAction !== null; const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => { if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return; - pendingRef.current.add(actionKey); - setPendingKeys(new Set(pendingRef.current)); + pendingRef.current.set(actionKey, action); + setPendingActions(new Map(pendingRef.current)); const result = await runAction({ environmentId, input: { @@ -227,7 +231,7 @@ export function usePullRequestActionRunner({ }, }); pendingRef.current.delete(actionKey); - setPendingKeys(new Set(pendingRef.current)); + setPendingActions(new Map(pendingRef.current)); if (result._tag === "Failure") { toastManager.add({ type: "error", @@ -246,7 +250,7 @@ export function usePullRequestActionRunner({ onSuccess?.(action, result.value); }; - return { actionPending, perform }; + return { actionPending, pendingAction, perform }; } export function usePullRequestCloseBatch( diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 829a83bb6e96f..a5ad1787b6e73 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5733,6 +5733,7 @@ "217e1e7b60469736": "Issue-Status, {state}", "a98a269e3061a069": "{issue} auf {provider} öffnen", "c1ff5afd83b1e027": "Issue aktualisieren", + "8ab83a75cae667a2": "Dieses Issue konnte nicht aktualisiert werden", "78398e2d7d040498": "Issue-Titel", "7b4fa0f856528bb0": "Titel bearbeiten", "c78c0974dbdb66c2": "Labels", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 7d7ff8c767c09..3ea4d48709ac7 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5734,6 +5734,7 @@ "217e1e7b60469736": "Issue state, {state}", "a98a269e3061a069": "Open {issue} on {provider}", "c1ff5afd83b1e027": "Refresh issue", + "8ab83a75cae667a2": "Could not refresh this issue", "78398e2d7d040498": "Issue title", "7b4fa0f856528bb0": "Edit title", "c78c0974dbdb66c2": "Labels", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 1efc2a8d01409..a11053284429b 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5732,6 +5732,7 @@ "217e1e7b60469736": "Estado de la issue, {state}", "a98a269e3061a069": "Abrir {issue} en {provider}", "c1ff5afd83b1e027": "Actualizar issue", + "8ab83a75cae667a2": "No se pudo actualizar esta issue", "78398e2d7d040498": "Título de la issue", "7b4fa0f856528bb0": "Editar título", "c78c0974dbdb66c2": "Etiquetas", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index db827245baf60..62c9bc84a077a 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5733,6 +5733,7 @@ "217e1e7b60469736": "État du ticket, {state}", "a98a269e3061a069": "Ouvrir {issue} sur {provider}", "c1ff5afd83b1e027": "Actualiser le ticket", + "8ab83a75cae667a2": "Impossible d’actualiser ce ticket", "78398e2d7d040498": "Titre du ticket", "7b4fa0f856528bb0": "Modifier le titre", "c78c0974dbdb66c2": "Libellés", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index db67a0661bac2..022e50d120884 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5715,6 +5715,7 @@ "217e1e7b60469736": "Issue の状態、{state}", "a98a269e3061a069": "{provider} で {issue} を開く", "c1ff5afd83b1e027": "Issue を更新", + "8ab83a75cae667a2": "この Issue を更新できませんでした", "78398e2d7d040498": "Issue のタイトル", "7b4fa0f856528bb0": "タイトルを編集", "c78c0974dbdb66c2": "ラベル", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 1b3677fd6fd48..4d8877deec534 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5713,6 +5713,7 @@ "217e1e7b60469736": "이슈 상태, {state}", "a98a269e3061a069": "{provider}에서 {issue} 열기", "c1ff5afd83b1e027": "이슈 새로 고침", + "8ab83a75cae667a2": "이 이슈를 새로고침할 수 없습니다", "78398e2d7d040498": "이슈 제목", "7b4fa0f856528bb0": "제목 편집", "c78c0974dbdb66c2": "레이블", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 0f5fa0c1ea8e6..552a955c2e032 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5732,6 +5732,7 @@ "217e1e7b60469736": "Estado da issue, {state}", "a98a269e3061a069": "Abrir {issue} no {provider}", "c1ff5afd83b1e027": "Atualizar issue", + "8ab83a75cae667a2": "Não foi possível atualizar esta issue", "78398e2d7d040498": "Título da issue", "7b4fa0f856528bb0": "Editar título", "c78c0974dbdb66c2": "Rótulos", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5d847f6d3a4cf..e02a09461e7e1 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5732,6 +5732,7 @@ "217e1e7b60469736": "Состояние issue: {state}", "a98a269e3061a069": "Открыть {issue} в {provider}", "c1ff5afd83b1e027": "Обновить issue", + "8ab83a75cae667a2": "Не удалось обновить этот issue", "78398e2d7d040498": "Заголовок issue", "7b4fa0f856528bb0": "Изменить название", "c78c0974dbdb66c2": "Метки", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 5cdfdc0840615..badfbe9f44e6a 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5733,6 +5733,7 @@ "217e1e7b60469736": "Ärendestatus, {state}", "a98a269e3061a069": "Öppna {issue} på {provider}", "c1ff5afd83b1e027": "Uppdatera ärende", + "8ab83a75cae667a2": "Det gick inte att uppdatera det här ärendet", "78398e2d7d040498": "Ärendets titel", "7b4fa0f856528bb0": "Redigera titel", "c78c0974dbdb66c2": "Etiketter", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index dd494452e9cbf..e5ae3545697fc 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5739,6 +5739,7 @@ "217e1e7b60469736": "issue 状态,{state}", "a98a269e3061a069": "在 {provider} 上打开 {issue}", "c1ff5afd83b1e027": "刷新 issue", + "8ab83a75cae667a2": "无法刷新此 issue", "78398e2d7d040498": "issue 标题", "7b4fa0f856528bb0": "编辑标题", "c78c0974dbdb66c2": "标签", diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index a914349694156..ed8e75c28c74c 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -95,8 +95,11 @@ newest remaining visible user and assistant messages, with 200 messages total. It omits tool activity and attachments. For Codex, it omits generated setup context only when a canonical user event and a valid shared turn ID identify the same user turn. Ambiguous legacy or response-only context stays in the imported -conversation so T3 Code does not remove user text. It reads one conversation at -a time and skips files larger than 4 GiB. It also skips a conversation when the +conversation so T3 Code does not remove user text. For Claude, slash commands +and `!` shell commands appear as you typed them; their output, background task +notifications and interruption markers are left out, and a conversation that +only ran commands such as `/clear`, with no reply, is skipped. It reads one +conversation at a time and skips files larger than 4 GiB. It also skips a conversation when the message text and metadata it keeps need more than 32 MiB of memory. Tool output does not count toward that limit. It skips a conversation with more than 100,000 records every time, so opening the page again does not import it. It ignores diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 92532a6a90579..c56fa973c4501 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -11,7 +11,7 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { isExplicitRelativePath, isHostPath, newProjectFolderName } from "@t3tools/shared/path"; +import { isAbsolutePath, isExplicitRelativePath, newProjectFolderName } from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -222,8 +222,13 @@ export function buildAddProjectRemoteSourceReadiness( export function getAddProjectInitialQuery(baseDirectory: string | null | undefined): string { const trimmed = baseDirectory?.trim() ?? ""; if (trimmed.length === 0) return "~/"; - // A bare relative setting such as `Desktop/dev` means a folder under home. - const isAnchored = trimmed === "~" || isHostPath(trimmed) || isExplicitRelativePath(trimmed); + // A bare relative setting such as `Desktop/dev` means a folder under home. The browser + // navigates `~/` but not `~\` home paths. + const isAnchored = + trimmed === "~" || + isAbsolutePath(trimmed) || + trimmed.startsWith("~/") || + isExplicitRelativePath(trimmed); return ensureBrowseDirectoryPath(isAnchored ? trimmed : `~/${trimmed}`); } diff --git a/packages/client-runtime/src/state/issues.test.ts b/packages/client-runtime/src/state/issues.test.ts index ab16b67be68f1..53fb953c0acb3 100644 --- a/packages/client-runtime/src/state/issues.test.ts +++ b/packages/client-runtime/src/state/issues.test.ts @@ -3,17 +3,18 @@ import { IssueTrackerKind, ProjectId, type IssueComment, + type IssueCommentsPage, type IssueListEntry, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import { Atom, AtomRegistry } from "effect/reactivity"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; import { + createIssueCommentPager, createMergedIssueCandidatesAtoms, issueEntryKey, mergeIssueListPage, - prependIssueComments, } from "./issues.ts"; function entry(overrides: Partial & { key: string }): IssueListEntry { @@ -67,19 +68,56 @@ describe("mergeIssueListPage", () => { }); }); -describe("prependIssueComments", () => { - const comment = (id: string): IssueComment => ({ - id, - author: null, - body: id, - createdAt: "2026-10-01T00:00:00.000Z", - url: null, - }); +const comment = (id: string): IssueComment => ({ + id, + author: null, + body: id, + createdAt: "2026-10-01T00:00:00.000Z", + url: null, +}); + +describe("createIssueCommentPager", () => { + it("drops older pages on refresh, including one still loading, and pauses paging until it ends", async () => { + // The refreshed detail hands back the same cursor, so only the refresh itself can tell pages apart. + const detail = Atom.make( + AsyncResult.success({ comments: [comment("newest")], commentsCursor: "first-page" }), + ); + const pager = createIssueCommentPager(detail); + const registry = AtomRegistry.make(); + const unmount = registry.mount(pager.view); + const ids = () => registry.get(pager.view).comments.map(({ id }) => id); + const cursors: string[] = []; + const page = AsyncResult.success({ + comments: [comment("older"), comment("newest")], + nextCursor: "second-page", + }); + const read = async (cursor: string) => { + cursors.push(cursor); + return page; + }; + try { + await pager.loadOlder(registry, read); + expect(ids()).toEqual(["older", "newest"]); - it("puts older comments first and drops ones already shown", () => { - const current = [comment("c3"), comment("c4")]; - const older = [comment("c1"), comment("c2"), comment("c3")]; - expect(prependIssueComments(current, older).map((c) => c.id)).toEqual(["c1", "c2", "c3", "c4"]); + const pending = Promise.withResolvers(); + const inFlight = pager.loadOlder(registry, () => pending.promise); + const refreshed = Promise.withResolvers(); + const refresh = pager.refresh(registry, () => refreshed.promise); + pending.resolve(page); + await inFlight; + expect(ids()).toEqual(["newest"]); + + await pager.loadOlder(registry, read); + expect(registry.get(pager.view).canLoadOlder).toBe(false); + refreshed.resolve(); + await refresh; + await pager.loadOlder(registry, read); + expect(cursors).toEqual(["first-page", "first-page"]); + expect(ids()).toEqual(["older", "newest"]); + } finally { + unmount(); + registry.dispose(); + } }); }); diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 31d23bc3ebe82..3175602dfaa42 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -4,6 +4,8 @@ import { type IssueAssigneeCandidate, type IssueCandidates, type IssueComment, + type IssueCommentsPage, + type IssueDetail, type IssueLabelCandidate, type IssueListEntry, type IssueListInput, @@ -17,6 +19,7 @@ import * as Option from "effect/Option"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import { + type AtomCommandResult, createAtomCommandScheduler, createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, @@ -49,7 +52,7 @@ export function mergeIssueListPage( } /** Older comments go in front: the detail carries the newest page and pages walk backwards. */ -export function prependIssueComments( +function prependIssueComments( current: ReadonlyArray, older: ReadonlyArray, ): ReadonlyArray { @@ -58,6 +61,89 @@ export function prependIssueComments( return [...older.filter((comment) => !seen.has(comment.id)), ...current]; } +export function createIssueCommentPager( + detailAtom: Atom.Atom< + AsyncResult.AsyncResult, E> + >, +) { + const state = Atom.make<{ + readonly older: (IssueCommentsPage & { readonly seed: string }) | null; + readonly loadingOlder: boolean; + readonly refreshing: boolean; + readonly refreshes: number; + }>({ older: null, loadingOlder: false, refreshing: false, refreshes: 0 }); + const page = Atom.make((get) => { + const detailResult = get(detailAtom); + const detail = AsyncResult.getOrElse(detailResult, () => null); + const current = get(state); + const seed = detail?.commentsCursor ?? null; + const older = current.older?.seed === seed ? current.older : null; + const nextCursor = older ? older.nextCursor : seed; + return { + comments: detail?.comments ?? [], + seed, + older, + nextCursor, + loadingOlder: current.loadingOlder, + unavailable: detailResult.waiting || current.refreshing || current.loadingOlder, + }; + }); + const view = Atom.make((get) => { + const { comments, older, nextCursor, loadingOlder, unavailable } = get(page); + return { + comments: prependIssueComments(comments, older?.comments ?? []), + nextCursor, + loadingOlder, + canLoadOlder: nextCursor !== null && !unavailable, + }; + }); + + return { + view, + async refresh(registry: AtomRegistry.AtomRegistry, read: () => void | Promise) { + const current = registry.get(state); + if (current.refreshing) return; + // The refreshed detail can return the same cursor, so invalidate outstanding pages explicitly. + registry.set(state, { + ...current, + older: null, + refreshing: true, + refreshes: current.refreshes + 1, + }); + try { + await read(); + } finally { + registry.set(state, { ...registry.get(state), refreshing: false }); + } + }, + async loadOlder( + registry: AtomRegistry.AtomRegistry, + read: (cursor: string) => Promise>, + ) { + const { seed, older, nextCursor, unavailable } = registry.get(page); + if (seed === null || nextCursor === null || unavailable) return; + const current = registry.get(state); + registry.set(state, { ...current, loadingOlder: true }); + try { + const result = await read(nextCursor); + const latest = registry.get(state); + if (latest.refreshes !== current.refreshes) return; + if (result._tag === "Failure") return result; + registry.set(state, { + ...latest, + older: { + seed, + comments: prependIssueComments(older?.comments ?? [], result.value.comments), + nextCursor: result.value.nextCursor, + }, + }); + } finally { + registry.set(state, { ...registry.get(state), loadingOlder: false }); + } + }, + }; +} + /** * Every read goes to a tracker API over the environment, so results are reused for a short while * and refreshed explicitly. Mutations run serially per environment: changes to one issue are diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts index 7b5027147c073..44723c79dc1d5 100644 --- a/packages/provider-acp-registry/src/server/copilotAcp.ts +++ b/packages/provider-acp-registry/src/server/copilotAcp.ts @@ -69,7 +69,7 @@ type CopilotToolIdentity = | { readonly kind: "mcp"; readonly server: string; readonly tool: string } | { readonly kind: "search" }; -const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]); +const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep", "rg"]); interface CopilotSessionAttribution { delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined; diff --git a/packages/provider-acp/src/server/clientTerminals.test.ts b/packages/provider-acp/src/server/clientTerminals.test.ts index 22f8bb9ce3dde..87a96999cd1bf 100644 --- a/packages/provider-acp/src/server/clientTerminals.test.ts +++ b/packages/provider-acp/src/server/clientTerminals.test.ts @@ -99,28 +99,59 @@ describe("AcpClientTerminals", () => { it.live("resolves terminal environment from the requesting ACP session", () => Effect.gen(function* () { + const inheritedEnvironment = yield* HostProcess.Environment; const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd(), - environmentForSession: (sessionId) => ({ - T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b", - }), + environmentForSession: (sessionId) => + sessionId === "unknown" + ? undefined + : { + T3_ACP_MCP_AUTHORIZATION: sessionId === "session-a" ? "token-a" : "token-b", + T3CODE_THREAD_ID: sessionId, + }, }); yield* Effect.addFinalizer(() => terminals.disposeAll); + inheritedEnvironment.T3_TEST_INHERITED = "refreshed"; for (const [sessionId, expected] of [ - ["session-a", "token-a"], - ["session-b", "token-b"], + ["session-a", "token-a||session-a|refreshed|T3_TEST_OVERRIDE=request"], + ["session-b", "token-b||session-b|refreshed|T3_TEST_OVERRIDE=request"], + ["unknown", "|||refreshed|T3_TEST_OVERRIDE=inherited"], ] as const) { const created = yield* terminals.create({ sessionId, command: process.execPath, - args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"], + args: [ + "-e", + "const env = process.env; process.stdout.write([env.T3_ACP_MCP_AUTHORIZATION ?? '', env.t3_Acp_Mcp_Endpoint ?? '', env.T3CODE_THREAD_ID ?? '', env.T3_TEST_INHERITED, ...Object.keys(env).filter((name) => name.toUpperCase() === 'T3_TEST_OVERRIDE').map((name) => name + '=' + env[name])].join('|'))", + ], + ...(sessionId === "unknown" + ? {} + : { + env: [ + { name: "T3_TEST_OVERRIDE", value: "first" }, + { name: "t3_Test_Override", value: "second" }, + { name: "T3_TEST_OVERRIDE", value: "request" }, + ], + }), }); yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId }); const output = yield* terminals.output({ sessionId, terminalId: created.terminalId }); expect(output.output).toBe(expected); } - }).pipe(Effect.provide(NodeServices.layer)), + }).pipe( + Effect.provideService(HostProcess.Environment, { + ...process.env, + T3_ACP_MCP_AUTHORIZATION: "launching-thread-token", + t3_Acp_Mcp_Endpoint: "launching-thread-endpoint", + T3CODE_THREAD_ID: "launching-thread", + T3_TEST_INHERITED: "kept", + T3_TEST_OVERRIDE: "inherited", + }), + // Exercise Windows' case-insensitive variable names on every OS. + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provide(NodeServices.layer), + ), ); it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () => diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 77d8767904bb5..2fda24d4e4fa5 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -12,6 +12,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeBuffer from "node:buffer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,22 +138,38 @@ function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; readonly defaultCwd: string; - readonly environment?: NodeJS.ProcessEnv | undefined; + readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { return ChildProcess.make(input.request.command, input.request.args ?? [], { cwd: input.request.cwd ?? input.defaultCwd, - ...(input.environment === undefined ? {} : { env: input.environment }), + env: input.environment, shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, }); } +// Windows variable names are case-insensitive and Node passes only one spelling to the child, +// so a later layer's `Path` must replace an earlier `PATH` rather than sit beside it. +function mergeEnvironments( + isWindows: boolean, + layers: ReadonlyArray>, +) { + const variables = new Map(); + for (const layer of layers) { + for (const [name, value] of layer) { + variables.set(isWindows ? name.toUpperCase() : name, [name, value]); + } + } + return Object.fromEntries(variables.values()); +} + export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(function* ( options: AcpClientTerminalsOptions, ): Effect.fn.Return { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; + const isWindows = yield* HostProcess.isWindows; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -215,16 +232,20 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`, ); } - const requestEnvironment = Object.fromEntries( - (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + // Thread credentials and identity must come from the requesting session. + const inheritedEnvironment = Object.fromEntries( + Object.entries(options.environment ?? (yield* HostProcess.Environment)).filter( + ([name]) => + !name.toUpperCase().startsWith("T3_ACP_MCP_") && + name.toUpperCase() !== "T3CODE_THREAD_ID", + ), ); const sessionEnvironment = options.environmentForSession?.(request.sessionId); - const environment = - options.environment === undefined && - sessionEnvironment === undefined && - (request.env?.length ?? 0) === 0 - ? undefined - : { ...options.environment, ...sessionEnvironment, ...requestEnvironment }; + const environment = mergeEnvironments(isWindows, [ + Object.entries(inheritedEnvironment), + Object.entries(sessionEnvironment ?? {}), + (request.env ?? []).map((variable) => [variable.name, variable.value] as const), + ]); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner diff --git a/packages/provider-muse/src/server/textGeneration.test.ts b/packages/provider-muse/src/server/textGeneration.test.ts index 7876cac59a506..f0b1f1a300adb 100644 --- a/packages/provider-muse/src/server/textGeneration.test.ts +++ b/packages/provider-muse/src/server/textGeneration.test.ts @@ -226,6 +226,62 @@ it.layer(NodeServices.layer)("Muse text generation", (it) => { }), ); + it.effect("explains a failed turn by Muse's error category", () => + Effect.gen(function* () { + const message = "API error 429: raw provider text"; + const cases = [ + { + error: { kind: "modelError", quota: { limitKind: "tierLimit", resetsAtMs: 1 } }, + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + // Credential proxies can refuse with a 429 quota message and no quota object. + error: { kind: "modelError", message: "upstream 429: quota exceeded for this key" }, + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + error: { kind: "authRequired" }, + detail: "Muse Code is not signed in. Run `muse login` on this T3 server host.", + }, + { + error: { kind: "modelError" }, + detail: "Muse Code's model request failed. Try again or choose another Muse model.", + }, + { + error: { kind: "stepLimit" }, + detail: + "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + }, + { + reason: "upstream 429: quota exceeded for this key", + detail: "Muse Code usage limit reached. Try again after it resets.", + }, + { + reason: "raw provider refusal", + detail: + "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + }, + ]; + for (const { error, reason, detail } of cases) { + const raw = error === undefined ? reason : "message" in error ? error.message : message; + const test = fixture((emit) => + emit("turn/completed", { + terminal: "failed", + ...(error === undefined + ? { reason } + : { error: { message, ...error, retryable: false } }), + }), + ); + const service = yield* test.make; + const failure = yield* service.generateThreadTitle(titleInput).pipe(Effect.flip); + expect(failure).toMatchObject({ _tag: "TextGenerationError", detail }); + expect(failure.detail).not.toContain(raw); + expect(failure.cause).toMatchObject({ cause: { message: raw } }); + expect(test.host.close).toHaveBeenCalledOnce(); + } + }), + ); + it.effect("settles a completed turn even when its start acknowledgement never arrives", () => Effect.gen(function* () { const test = fixture(finish('{"title":"Fix login form"}'), false); diff --git a/packages/provider-muse/src/server/textGeneration.ts b/packages/provider-muse/src/server/textGeneration.ts index e36f4de9fbd18..dacaeae8bd033 100644 --- a/packages/provider-muse/src/server/textGeneration.ts +++ b/packages/provider-muse/src/server/textGeneration.ts @@ -21,6 +21,7 @@ import { type MuseSdkHost, } from "./sdk.ts"; import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts"; +import { isMuseUsageLimitFailure } from "./usageLimits.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { generatedThreadTitle, @@ -52,11 +53,17 @@ const ItemNotification = Schema.Struct({ truncated: Schema.optionalKey(Schema.Boolean), }), }); +const TurnError = Schema.Struct({ + kind: Schema.optionalKey(Schema.String), + message: Schema.String, + quota: Schema.optionalKey(Schema.Unknown), +}); const TurnCompleted = Schema.Struct({ sessionId: Schema.String, turnId: Schema.String, terminal: Schema.String, - error: Schema.optionalKey(Schema.Struct({ message: Schema.String })), + reason: Schema.optionalKey(Schema.String), + error: Schema.optionalKey(TurnError), }); const ApprovalRequested = Schema.Struct({ sessionId: Schema.String, @@ -75,10 +82,32 @@ const decodeItem = Schema.decodeUnknownSync(ItemNotification); const decodeCompleted = Schema.decodeUnknownSync(TurnCompleted); const decodeApproval = Schema.decodeUnknownSync(ApprovalRequested); const decodeUserInput = Schema.decodeUnknownSync(UserInputRequested); +const isMuseSdkError = Schema.is(MuseSdkError); const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown)); type Operation = keyof ProviderTextGeneration; +class MuseTurnFailure extends Schema.TaggedError()("MuseTurnFailure", { + turnError: TurnError, +}) { + override get message() { + return this.turnError.message; + } +} +const isMuseTurnFailure = Schema.is(MuseTurnFailure); + +function museFailureDetail(cause: unknown): string { + const error = + isMuseSdkError(cause) && isMuseTurnFailure(cause.cause) ? cause.cause.turnError : undefined; + // Muse sends `quota` only for quota exhaustion, which it still labels `modelError`. + if (error?.quota !== undefined || isMuseUsageLimitFailure(error?.message)) + return "Muse Code usage limit reached. Try again after it resets."; + if (error?.kind === "authRequired") + return "Muse Code is not signed in. Run `muse login` on this T3 server host."; + if (error?.kind === "modelError") + return "Muse Code's model request failed. Try again or choose another Muse model."; + return "Muse Code text generation failed. Check Muse login and availability on this T3 server host."; +} async function generateMuseText( host: MuseSdkHost, @@ -144,8 +173,13 @@ async function generateMuseText( resolveCompletion(answer?.text ?? ""); } } else { + const error = + completed.error ?? + (completed.reason !== undefined ? { message: completed.reason } : undefined); rejectCompletion( - new Error(completed.error?.message ?? `Muse turn ${completed.terminal}.`), + error + ? new MuseTurnFailure({ turnError: error }) + : new Error(`Muse turn ${completed.terminal}.`), ); } } else if ( @@ -276,8 +310,7 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi (cause) => new TextGenerationError({ operation, - detail: - "Muse Code text generation failed. Check Muse login and availability on this T3 server host.", + detail: museFailureDetail(cause), cause, }), ), diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index 514f92b8f54e0..9a9647c1bcd4b 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -59,6 +59,7 @@ describe("resolvePastedPath", () => { ["over a selection", "/Users/me/old", "'/Users/me/My Code'", "/Users/me/My Code"], ["after a prefilled folder", "~/", "~/'/Users/me/My Code'", "/Users/me/My Code"], ["plain, after a prefilled folder", "~/", "~//Users/me/code", "/Users/me/code"], + ["backslash home, after a folder", "~/", "~/~\\folder\\ child", "~/~\\folder\\ child"], ["after a Windows folder", "C:\\Users\\", 'C:\\Users\\"D:\\My Code"', "D:\\My Code"], ["a shell's quoted apostrophe", "", "'/Users/me/Bob'\\''s Work'", "/Users/me/Bob's Work"], ["after a clone destination", "~/code/repo", "~/code/repo'/a b'", "/a b"], diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index 45b49b200091c..e4351b97b2626 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -134,15 +134,20 @@ export function isAbsolutePath(value: string): boolean { return value.startsWith("/") || isWindowsAbsolutePath(value); } -/** Home-relative host paths are expanded by the destination server. */ +/** Both ~/ and ~\ home prefixes are expanded by the destination server. */ export function isHostPath(value: string): boolean { - return isAbsolutePath(value) || value.startsWith("~/"); + return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\"); } // Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`. const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/; const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g; +// Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement. +function isPastedFolderPath(value: string): boolean { + return isAbsolutePath(value) || value.startsWith("~/"); +} + /** * What a folder box holds after a change. A full path pasted into it replaces the box, even after * the text already there, because `~/'/a b'` would create that nested folder. @@ -157,13 +162,13 @@ export function resolvePastedPath(previous: string, next: string): string { // Text before the quote that wasn't in the box is a search, not a folder to paste after. if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) { const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? ""; - if (isHostPath(quoted)) return quoted; + if (isPastedFolderPath(quoted)) return quoted; } // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder. const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous); const path = afterFolder ? next.slice(previous.length) : next; - if (!isHostPath(path)) return next; + if (!isPastedFolderPath(path)) return next; // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths. return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1"); } diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts index 5bd495bca73ee..cc6a1d18cd28f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts @@ -219,6 +219,7 @@ describe("AzureDevOpsIssueTracker", () => { const fs = yield* FileSystem.FileSystem; const bodies: string[] = []; const hydrated: string[] = []; + let typeReads = 0; const api = yield* AzureDevOpsIssueTracker.make.pipe( Effect.provide( Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({ @@ -238,6 +239,7 @@ describe("AzureDevOpsIssueTracker", () => { ); } if (resource !== "wiql" && resource !== "workitemsbatch") { + if (resource === "workitemtypes") typeReads += 1; return Effect.succeed(TestSourceControlHost.processOutput(answer(args))); } return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe( @@ -260,7 +262,7 @@ describe("AzureDevOpsIssueTracker", () => { }), ), ); - const page = yield* api.listIssues({ + const list = api.listIssues({ cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", @@ -273,11 +275,16 @@ describe("AzureDevOpsIssueTracker", () => { limit: 2, cursor: "2026-07-01T00:00:00Z|7", }); + const page = yield* list; + yield* list; // The rows come back in WIQL's order, and the cursor is the last one of the page. - expect(hydrated).toEqual(["9,7"]); + expect(hydrated).toEqual(["9,7", "9,7"]); expect(page.items.map((item) => item.key)).toEqual(["9", "7"]); expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7"); - expect(bodies).toHaveLength(1); + // Each `az` call costs seconds, so a second list reuses the project's states. + expect(typeReads).toBe(1); + expect(bodies).toHaveLength(2); + expect(bodies[1]).toBe(bodies[0]); expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')"); const { query } = JSON.parse(bodies[0]!) as { query: string }; // Mentions cannot be asked for over REST, so the filter sends no clause for them. diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts index 5a6f4c7c38ef9..84212c9ff0ecd 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts @@ -3,7 +3,10 @@ * scope is `organization/project` and every call names the organization. Listing is a WIQL * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset. */ +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; @@ -67,6 +70,7 @@ const VIEWER_PERMISSIONS: IssueViewerPermissions = { const REST_API_VERSION = "7.1"; const PAGE_SIZE = 100; +const CLOSED_STATES_TTL = Duration.minutes(10); /** Updates are read a page per `az` process, oldest first, so a long history is bounded. */ const UPDATE_PAGE_LIMIT = 5; /** Linked pull requests are read one `az` process each, so a work item's links are bounded. */ @@ -356,8 +360,19 @@ export const make: Effect.Effect< decode: decodeAs(decodeTypes), }).pipe(Effect.map((types) => types.value)); - const closedStates = (input: Parameters[0]) => - workItemTypes(input).pipe(Effect.map(closedStateNames)); + // Each `az` call costs seconds of startup, and a project's states rarely change. + const listClosedStates = yield* Cache.makeWith( + (key: string) => { + const [cwd, organization, project] = JSON.parse(key) as [string, string, string]; + return workItemTypes({ cwd, organization, project, operation: "listIssues" }).pipe( + Effect.map(closedStateNames), + ); + }, + { + capacity: 256, + timeToLive: (exit) => (Exit.isSuccess(exit) ? CLOSED_STATES_TTL : Duration.zero), + }, + ); const workItem = (input: { readonly cwd: string; @@ -599,9 +614,10 @@ export const make: Effect.Effect< const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]"; return yield* scoped("listIssues", input).pipe( Effect.flatMap((scope) => - closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe( - Effect.map((closed) => ({ scope, closed })), - ), + Cache.get( + listClosedStates, + JSON.stringify([input.cwd, scope.organization, scope.project]), + ).pipe(Effect.map((closed) => ({ scope, closed }))), ), Effect.flatMap(({ scope, closed }) => invokeWithBody({ diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 1760511cabcd4..3ddcd024f8b35 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -80,6 +80,7 @@ const DETAIL_RESPONSE = JSON.stringify({ viewerCanReopen: true, reactionGroups: [], closedByPullRequestsReferences: { + pageInfo: { hasNextPage: true, endCursor: "links-next" }, nodes: [ { number: 50, @@ -186,9 +187,18 @@ function tracker(onRequest: (variables: unknown) => void, templateRepository?: u pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ name: "needs repro", color: "ffffff" }], }, - assignees: { + closedByPullRequestsReferences: { pageInfo: { hasNextPage: false, endCursor: null }, - nodes: [], + nodes: [ + { + number: 61, + title: "fix(web): restore focus after paste", + url: "https://github.com/acme/web/pull/61", + state: "OPEN", + isDraft: true, + repository: { nameWithOwner: "acme/web" }, + }, + ], }, }, }, @@ -549,6 +559,10 @@ Redact secrets before uploading.`); number: 42, labelsCursor: "labels-next", assigneesCursor: null, + closingPullRequestsCursor: "links-next", + withLabels: true, + withAssignees: false, + withClosingPullRequests: true, }, ]); expect(issue).toMatchObject({ @@ -600,6 +614,16 @@ Redact secrets before uploading.`); isDraft: false, closesIssue: true, }, + // A closing reference past the first page, with no timeline sighting, still shows. + { + repository: "acme/web", + number: 61, + title: "fix(web): restore focus after paste", + url: "https://github.com/acme/web/pull/61", + state: "open", + isDraft: true, + closesIssue: true, + }, ]); // An event kind this page has no vocabulary for is dropped rather than guessed at. expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index eed4578ff389c..bf1c20abae4e3 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -4,7 +4,9 @@ import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql" import { IssueTrackerKind, type IssueCapabilities, + type IssueActor, type IssueInvolvement, + type IssueLabel, type IssueListSort, } from "@t3tools/contracts"; import { @@ -227,51 +229,75 @@ export const make = Effect.gen(function* () { const result = yield* client .IssueDetail({ owner, name, number }) .pipe(graphql(input.host, "getIssue")); - const detail = toIssueDetail(result); - const raw = result.repository?.issue; - if (detail === null || raw == null) return yield* notFound("getIssue"); - // Editing replaces these sets. Finish their pages before handing them to a client. + const repository = result.repository; + const raw = repository?.issue; + if (repository == null || raw == null) return yield* notFound("getIssue"); + // Editing replaces labels and assignees, and a closing reference can sit past the first + // page. Finish their pages before handing the issue to a client. let labels = raw.labels; let assignees = raw.assignees; + let closing = raw.closedByPullRequestsReferences; const seen = new Set(); - const allLabels = [...detail.labels]; - const allAssignees = [...detail.assignees]; - while (labels?.pageInfo.hasNextPage === true || assignees.pageInfo.hasNextPage) { + const moreLabels: IssueLabel[] = []; + const moreAssignees: IssueActor[] = []; + const allClosing = [...(closing?.nodes ?? [])]; + while ( + labels?.pageInfo.hasNextPage === true || + assignees.pageInfo.hasNextPage || + closing?.pageInfo.hasNextPage === true + ) { const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null; const assigneesCursor = assignees.pageInfo.hasNextPage ? assignees.pageInfo.endCursor : null; - const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""}`; + const closingPullRequestsCursor = closing?.pageInfo.hasNextPage + ? closing.pageInfo.endCursor + : null; + const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""} ${closingPullRequestsCursor ?? ""}`; if ( (labels?.pageInfo.hasNextPage && labelsCursor === null) || (assignees.pageInfo.hasNextPage && assigneesCursor === null) || + (closing?.pageInfo.hasNextPage && closingPullRequestsCursor === null) || seen.has(key) ) { return yield* invalid( "getIssue", - "GitHub did not return complete issue labels or assignees.", + "GitHub did not return complete issue labels, assignees or linked pull requests.", ); } seen.add(key); const page = yield* client - .IssueCollections({ owner, name, number, labelsCursor, assigneesCursor }) + .IssueCollections({ + owner, + name, + number, + labelsCursor, + assigneesCursor, + closingPullRequestsCursor, + withLabels: labelsCursor !== null, + withAssignees: assigneesCursor !== null, + withClosingPullRequests: closingPullRequestsCursor !== null, + }) .pipe(graphql(input.host, "getIssue")); const next = page.repository?.issue; if (next == null) return yield* notFound("getIssue"); - if (labels?.pageInfo.hasNextPage) { - labels = next.labels; - if (next.labels === null) { + if (labelsCursor !== null) { + if (next.labels == null) { return yield* invalid("getIssue", "GitHub did not return complete issue labels."); } - allLabels.push( + labels = next.labels; + moreLabels.push( ...(next.labels.nodes ?? []).flatMap((node) => node === null ? [] : [{ name: node.name, color: node.color }], ), ); } - if (assignees.pageInfo.hasNextPage) { + if (assigneesCursor !== null) { + if (next.assignees === undefined) { + return yield* invalid("getIssue", "GitHub did not return complete issue assignees."); + } assignees = next.assignees; - allAssignees.push( + moreAssignees.push( ...(next.assignees.nodes ?? []).flatMap((node) => node === null ? [] @@ -279,8 +305,36 @@ export const make = Effect.gen(function* () { ), ); } + if (closingPullRequestsCursor !== null) { + if (next.closedByPullRequestsReferences == null) { + return yield* invalid( + "getIssue", + "GitHub did not return complete linked pull requests.", + ); + } + closing = next.closedByPullRequestsReferences; + allClosing.push(...(closing.nodes ?? [])); + } } - return { ...detail, labels: allLabels, assignees: allAssignees }; + const detail = toIssueDetail({ + ...result, + repository: { + ...repository, + issue: { + ...raw, + closedByPullRequestsReferences: + raw.closedByPullRequestsReferences === null + ? null + : { ...raw.closedByPullRequestsReferences, nodes: allClosing }, + }, + }, + }); + if (detail === null) return yield* notFound("getIssue"); + return { + ...detail, + labels: [...detail.labels, ...moreLabels], + assignees: [...detail.assignees, ...moreAssignees], + }; }), getComments: (input) => diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index a0ca800e34ca5..42dc67a98a123 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -99,6 +99,10 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } } closedByPullRequestsReferences(first: 20, includeClosedPrs: true) { + pageInfo { + hasNextPage + endCursor + } nodes { number title @@ -363,10 +367,14 @@ query IssueCollections( $number: Int! $labelsCursor: String $assigneesCursor: String + $closingPullRequestsCursor: String + $withLabels: Boolean! + $withAssignees: Boolean! + $withClosingPullRequests: Boolean! ) { repository(owner: $owner, name: $name) { issue(number: $number) { - labels(first: 100, after: $labelsCursor) { + labels(first: 100, after: $labelsCursor) @include(if: $withLabels) { pageInfo { hasNextPage endCursor @@ -376,7 +384,7 @@ query IssueCollections( color } } - assignees(first: 100, after: $assigneesCursor) { + assignees(first: 100, after: $assigneesCursor) @include(if: $withAssignees) { pageInfo { hasNextPage endCursor @@ -387,6 +395,26 @@ query IssueCollections( avatarUrl } } + closedByPullRequestsReferences( + first: 100 + after: $closingPullRequestsCursor + includeClosedPrs: true + ) @include(if: $withClosingPullRequests) { + pageInfo { + hasNextPage + endCursor + } + nodes { + number + title + url + state + isDraft + repository { + nameWithOwner + } + } + } } } } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index e71768b4fb2e3..d99defc174a5c 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -332,6 +332,8 @@ export interface NodesPullRequest extends Schema.Struct.Type {} @@ -1001,10 +1005,14 @@ export const IssueCollections = GraphQL.query("IssueCollections", { { name: "name", body: "String!" }, { name: "number", body: "Int!" }, { name: "labelsCursor", body: "String" }, - { name: "assigneesCursor", body: "String" } + { name: "assigneesCursor", body: "String" }, + { name: "closingPullRequestsCursor", body: "String" }, + { name: "withLabels", body: "Boolean!" }, + { name: "withAssignees", body: "Boolean!" }, + { name: "withClosingPullRequests", body: "Boolean!" } ], selections: [ - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){labels(first:100 after:$", "labelsCursor", "){pageInfo{hasNextPage endCursor}nodes{name color}}assignees(first:100 after:$", "assigneesCursor", "){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){labels(first:100 after:$", "labelsCursor", ")@include(if:$", "withLabels", "){pageInfo{hasNextPage endCursor}nodes{name color}}assignees(first:100 after:$", "assigneesCursor", ")@include(if:$", "withAssignees", "){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}closedByPullRequestsReferences(first:100 after:$", "closingPullRequestsCursor", " includeClosedPrs:true)@include(if:$", "withClosingPullRequests", "){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}}}"] } ], fragments: [] }, @@ -1013,7 +1021,11 @@ export const IssueCollections = GraphQL.query("IssueCollections", { name: Schema.String, number: Shared.Int, labelsCursor: Schema.optional(Schema.NullOr(Schema.String)), - assigneesCursor: Schema.optional(Schema.NullOr(Schema.String)) + assigneesCursor: Schema.optional(Schema.NullOr(Schema.String)), + closingPullRequestsCursor: Schema.optional(Schema.NullOr(Schema.String)), + withLabels: Schema.Boolean, + withAssignees: Schema.Boolean, + withClosingPullRequests: Schema.Boolean }, result: Schema.Struct({ /** Lookup a given repository by the owner and repository name. */ diff --git a/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts b/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts new file mode 100644 index 0000000000000..13797e21179e2 --- /dev/null +++ b/scripts/scenarios/github-closing-pr-after-first-page.e2e.ts @@ -0,0 +1,222 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; +import { expect } from "e2e"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; + +import { APP_DIR, T3_HOME } from "../e2e.config.ts"; +import { run, ScenarioError } from "./shell.ts"; +import { prepareHome, start } from "./start-app.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const HOST = "github.scenario.invalid"; +const SCOPE = "scenario/demo"; +const HOME = `${T3_HOME}-github-issue-links`; + +// Install only on the isolated server. The real GitHub adapter still builds and decodes requests. +const upstream = String.raw` +const host = "${HOST}"; +const scope = "${SCOPE}"; +const viewer = { login: "scenario-user" }; +const createdAt = "2026-10-01T00:00:00Z"; +const updatedAt = "2026-10-05T00:00:00Z"; +const row = { + __typename: "Issue", number: 42, title: "Release preparation", + url: "https://" + host + "/" + scope + "/issues/42", + state: "OPEN", stateReason: null, author: null, createdAt, updatedAt, closedAt: null, +}; +const empty = { nodes: [], totalCount: 0, pageInfo: { hasNextPage: false, endCursor: null } }; +const links = Array.from({ length: 21 }, (_, i) => ({ + number: 100 + i, + title: i === 20 ? "Backfill release metadata" : "Fix release check " + (i + 1), + url: "https://" + host + "/" + scope + "/pull/" + (100 + i), + state: "OPEN", + isDraft: false, + repository: { nameWithOwner: scope }, +})); +const timeline = [ + ...links.map((link) => ({ + __typename: "CrossReferencedEvent", id: "ref-" + link.number, createdAt, actor: null, + source: { ...link, __typename: "PullRequest" }, + })), + ...Array.from({ length: 100 }, (_, i) => ({ + __typename: "RenamedTitleEvent", id: "rename-" + i, + createdAt: new Date(Date.parse(updatedAt) - (99 - i) * 60_000).toISOString(), + actor: null, currentTitle: i === 99 ? row.title : "Release draft " + i, + })), +]; +function arg(query, field, argument, vars) { + const args = query.match(new RegExp("\\b" + field + "\\s*\\(([^)]*)\\)"))?.[1] ?? ""; + const value = args.match(new RegExp("\\b" + argument + '\\s*:\\s*(\\$[\\w]+|[0-9]+|"[^"]*")'))?.[1]; + if (value === undefined) return undefined; + if (value.startsWith("$")) return vars[value.slice(1)]; + return JSON.parse(value); +} + +function page(nodes, query, field, vars) { + const filter = arg(query, field, "query", vars)?.toLowerCase(); + const matches = filter ? nodes.filter((node) => node.name?.toLowerCase().includes(filter)) : nodes; + const start = Number(arg(query, field, "after", vars) ?? 0); + const end = start + (arg(query, field, "first", vars) ?? 100); + const last = arg(query, field, "last", vars); + return { + nodes: last === undefined ? matches.slice(start, end) : matches.slice(-last), + totalCount: matches.length, + pageInfo: { hasNextPage: end < matches.length, endCursor: String(end) }, + }; +} + +const fetchActual = globalThis.fetch; +globalThis.fetch = async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + if (url.hostname !== host) return fetchActual(input, init); + if (url.pathname === "/api/v3/user") return Response.json({ ...viewer, name: null }); + if (url.pathname !== "/api/graphql") return new Response(null, { status: 404 }); + const { query, variables = {} } = await request.json(); + if (/\bsearch\s*\(/.test(query)) { + return Response.json({ data: { search: { ...empty, nodes: [ + { ...row, assignees: empty, labels: empty, comments: { totalCount: 0 } }, + ] } } }); + } + const repository = { + viewerPermission: "WRITE", + labels: empty, assignableUsers: empty, + issue: { + ...row, labels: empty, assignees: empty, body: "Check the release notes.", + viewerCanUpdate: true, viewerCanClose: true, viewerCanReopen: false, reactionGroups: [], + locked: false, activeLockReason: null, viewerCanComment: true, + comments: { nodes: [], totalCount: 0, pageInfo: { hasPreviousPage: false, startCursor: null } }, + closedByPullRequestsReferences: page(links, query, "closedByPullRequestsReferences", variables), + timelineItems: page(timeline, query, "timelineItems", variables), + }, + }; + return Response.json({ data: { viewer, repository } }); +}; +`; + +function startFixtureServer(webOrigin: string) { + const ready = Promise.withResolvers<{ origin: string; token: string }>(); + const server = Effect.runFork( + Effect.gen(function* () { + yield* prepareHome(HOME); + const port = yield* (yield* NetService.NetService).reserveLoopbackPort(); + const origin = `http://127.0.0.1:${port}`; + const token = yield* Deferred.make(); + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + const node = yield* HostProcess.ExecutablePath; + const child = yield* start({ + cwd: APP_DIR, + command: node, + args: [ + `--import=data:text/javascript;base64,${Buffer.from(upstream).toString("base64")}`, + "apps/server/src/bin.ts", + "serve", + "--host", + "127.0.0.1", + "--port", + String(port), + "--base-dir", + HOME, + "--dev-url", + webOrigin, + ], + env: { + PATH: `${path.join(HOME, "bin")}:${searchPath}`, + HOME, + GH_HOST: HOST, + GH_ENTERPRISE_TOKEN: "scenario-only-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", + }, + onLine: (line) => { + const value = /^Token:\s*(\S+)/.exec(line)?.[1]; + return value === undefined + ? Effect.void + : Deferred.succeed(token, value).pipe(Effect.asVoid); + }, + }); + const exited = child.exitCode.pipe( + Effect.flatMap( + (code) => new ScenarioError({ message: `Fixture server exited (${code}).` }), + ), + ); + ready.resolve({ origin, token: yield* Effect.raceFirst(Deferred.await(token), exited) }); + return yield* exited; + }).pipe(Effect.scoped, Effect.provide([NodeServices.layer, NetService.layer])), + ); + void Effect.runPromise(Fiber.join(server)).catch(ready.reject); + return { ready: ready.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) }; +} + +test( + "A closing pull request remains visible after its timeline reference ages out", + WEB, + async ({ t3, app, browser, screen }) => { + const workspace = await t3.project("Release"); + const server = startFixtureServer(app.baseUrl ?? ""); + try { + const { origin, token } = await server.ready; + const repository = await runPromise( + Effect.map(Path.Path, (path) => path.join(HOME, "release")), + ); + await runPromise(run("git", ["clone", "--quiet", workspace, repository])); + await runPromise( + run("git", ["remote", "set-url", "origin", `https://${HOST}/${SCOPE}.git`], { + cwd: repository, + }), + ); + const added = await runPromise(makeState(HOME).cli(["project", "add", repository])); + const projectId = /Added project (\S+) /.exec(added.stdout)?.[1]; + if (!projectId) throw new Error("The fixture project was not added."); + const { environmentId } = await runPromise( + HttpClient.get(`${origin}/.well-known/t3/environment`).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap( + HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String })), + ), + Effect.provide(FetchHttpClient.layer), + ), + ); + const link = new URLSearchParams({ + key: "42", + tracker: "github", + scope: SCOPE, + selectedHost: HOST, + selectedEnvironmentId: environmentId, + selectedProjectId: projectId, + }); + + await t3.open("/settings/connections"); + await screen.getByRole("button", "Add environment").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByPlaceholder("backend.example.com").fill(origin); + await dialog.getByPlaceholder("PAIRCODE").fill(token); + await dialog.getByRole("button", "Add environment").tap(); + await screen.getByRole("button", "More actions for Scenario").waitFor(); + await app.open(`/issues?${link}`); + + await screen.getByRole("button", /Fix release check 20/).waitFor(); + try { + await expect(screen.getByRole("button", /Backfill release metadata/)).toBeVisible(); + } finally { + await browser.evaluate(() => { + const rows = document.querySelectorAll("button"); + const row = + [...rows].find((button) => button.textContent?.includes("Backfill release metadata")) ?? + [...rows].find((button) => button.textContent?.includes("Fix release check 20")); + row?.scrollIntoView({ block: "center" }); + return null; + }); + await app.screenshot("last-linked-pull-request"); + } + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts b/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts new file mode 100644 index 0000000000000..220da5c4c82d7 --- /dev/null +++ b/scripts/scenarios/issues-refresh-discards-pending-older-comments.e2e.ts @@ -0,0 +1,175 @@ +/// +import type { IssueComment, IssueCommentsPage, IssueDetail, IssueRef } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A page requested before refreshing an issue does not restore old comments", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await browser.addInitScript(() => { + const pendingPage = new Promise((resolve) => { + Object.assign(window, { releaseOldIssuePage: () => resolve() }); + }); + const comment = (id: string, body: string, day: string): IssueComment => ({ + id, + body, + author: null, + createdAt: `2026-10-${day}T00:00:00.000Z`, + url: null, + }); + let refreshed = false; + let pendingRefresh: Promise | undefined; + Object.assign(window, { + armIssueRefresh: () => { + refreshed = true; + }, + holdIssueRefresh: () => { + const { promise, resolve } = Promise.withResolvers(); + pendingRefresh = promise; + Object.assign(window, { releaseIssueRefresh: resolve }); + }, + }); + // Keep the real socket for all other RPCs. Supply three pages of an unchanged GitHub + // comment history and hold the last page until the refreshed detail has rendered. + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { + _tag: string; + id: string; + tag: string; + payload: IssueRef & { cursor?: string }; + } | null = typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request") return send.call(this, data); + const reply = (value: IssueDetail | IssueCommentsPage) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Success", value }, + }), + }), + ); + if (request.tag === "issues.detail") { + const { projectId, tracker, scope, key } = request.payload; + const detail: IssueDetail = { + projectId, + tracker, + scope, + key, + host: "github.com", + displayKey: "#42", + projectTitle: "demo", + title: refreshed ? "Pagination issue after refresh" : "Pagination issue", + body: "Comment history", + url: "https://github.com/example/demo/issues/42", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-04T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 201, + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: true, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + comments: [comment("newest", "Newest comment", "04")], + commentsCursor: "first-older-page", + events: [], + linkedPullRequests: [], + }; + if (pendingRefresh) { + void pendingRefresh.then(() => reply(detail)); + pendingRefresh = undefined; + return; + } + queueMicrotask(() => reply(detail)); + } else if (request.tag === "issues.comments") { + if (request.payload.cursor === "first-older-page") { + queueMicrotask(() => + reply({ + comments: [comment("older", "First older comment", "03")], + nextCursor: "last-page", + }), + ); + } else if (request.payload.cursor === "last-page") { + void pendingPage.then(() => + reply({ + comments: [comment("oldest", "Oldest comment", "02")], + nextCursor: null, + }), + ); + } else return send.call(this, data); + } else return send.call(this, data); + }; + }); + + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + const loadOlder = screen.getByRole("button", "Load older comments", { exact: true }); + // The issues route compiles on first open, which can outlast the 30 s action timeout. + await loadOlder.waitFor({ timeout: 60_000 }); + await loadOlder.tap(); + await screen.getByText("First older comment", { exact: true }).waitFor(); + await loadOlder.tap(); + const loading = screen.getByRole("button", "Loading…", { exact: true }); + await loading.waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssueRefresh: () => void }).armIssueRefresh(); + return null; + }); + await screen.getByRole("button", "Refresh issue", { exact: true }).tap(); + await screen.getByText("Pagination issue after refresh", { exact: true }).waitFor(); + + await browser.evaluate(() => { + (window as unknown as { releaseOldIssuePage: () => void }).releaseOldIssuePage(); + return null; + }); + const activity = 'section[aria-label^="Activity"]'; + await loading.waitFor({ state: "hidden" }); + await browser.evaluate((selector) => { + document.querySelector(selector)?.scrollIntoView({ block: "start" }); + return null; + }, activity); + await app.screenshot("activity-after-refresh-and-late-page"); + await expect(browser.locator(activity)).not.toContainText("First older comment"); + + await browser.evaluate(() => { + (window as unknown as { holdIssueRefresh: () => void }).holdIssueRefresh(); + return null; + }); + const refresh = screen.getByRole("button", "Refresh issue", { exact: true }); + await refresh.tap(); + await expect(refresh).toBeDisabled(); + await expect(loadOlder).toBeDisabled(); + await browser.evaluate(() => { + (window as unknown as { releaseIssueRefresh: () => void }).releaseIssueRefresh(); + return null; + }); + await expect(loadOlder).toBeEnabled(); + await loadOlder.tap(); + await screen.getByText("First older comment", { exact: true }).waitFor(); + }, +); diff --git a/scripts/scenarios/issues-shows-failed-refresh.e2e.ts b/scripts/scenarios/issues-shows-failed-refresh.e2e.ts new file mode 100644 index 0000000000000..325d1a2605dee --- /dev/null +++ b/scripts/scenarios/issues-shows-failed-refresh.e2e.ts @@ -0,0 +1,125 @@ +/// +import type { IssueDetail, IssueRef } from "@t3tools/contracts"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A failed issue refresh tells the reader what went wrong", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await browser.addInitScript(() => { + let rateLimited = false; + Object.assign(window, { + armIssueRefreshFailure: () => { + rateLimited = true; + }, + }); + const refresh = new Promise((resolve) => { + Object.assign(window, { releaseIssueRefresh: () => resolve() }); + }); + // The first issue read succeeds; the refresh then hits GitHub's rate limit. + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + const request: { _tag: string; id: string; tag: string; payload: IssueRef } | null = + typeof data === "string" ? JSON.parse(data) : null; + if (request?._tag !== "Request" || request.tag !== "issues.detail") + return send.call(this, data); + const reply = (exit: unknown) => + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ _tag: "Exit", requestId: request.id, exit }), + }), + ); + if (rateLimited) { + void refresh.then(() => + reply({ + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "IssueOperationError", + operation: "detail", + detail: "GitHub API rate limit exceeded.", + reason: "rate-limited", + }, + }, + ], + }), + ); + return; + } + const { projectId, tracker, scope, key } = request.payload; + const detail: IssueDetail = { + projectId, + tracker, + scope, + key, + host: "github.com", + displayKey: "#42", + projectTitle: "demo", + title: "Issue before the rate limit", + body: "The details from the last successful read.", + url: "https://github.com/example/demo/issues/42", + author: null, + state: { category: "open", name: "Open" }, + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-01T00:00:00.000Z", + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + writable: false, + capabilities: { + create: false, + edit: false, + comment: false, + labels: false, + assignees: false, + reactions: false, + templates: false, + linkedPullRequests: false, + events: false, + search: true, + }, + viewerPermissions: { + setState: false, + comment: false, + edit: false, + labels: false, + assignees: false, + }, + states: [], + viewer: null, + comments: [], + commentsCursor: null, + events: [], + linkedPullRequests: [], + }; + queueMicrotask(() => reply({ _tag: "Success", value: detail })); + }; + }); + + await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42"); + await screen.getByText("Issue before the rate limit", { exact: true }).waitFor(); + await browser.evaluate(() => { + (window as unknown as { armIssueRefreshFailure: () => void }).armIssueRefreshFailure(); + return null; + }); + await screen.getByRole("button", "Refresh issue", { exact: true }).tap(); + const refreshing = browser.locator('button[aria-label="Refresh issue"]:disabled'); + await refreshing.waitFor(); + await browser.evaluate(() => { + (window as unknown as { releaseIssueRefresh: () => void }).releaseIssueRefresh(); + return null; + }); + await refreshing.waitFor({ state: "hidden" }); + await app.screenshot("after-failed-refresh"); + await expect( + screen.getByText("GitHub API rate limit exceeded.", { exact: false }), + ).toBeVisible(); + await expect(screen.getByText("Issue before the rate limit", { exact: true })).toBeVisible(); + }, +);