Skip to content

Commit 36a5516

Browse files
feat: attach and start threads from GitHub issues (#110)
GitHub issues now work like Linear issues. They attach to a message as a context chip carrying the description and selected comments, from the attach menu, the # menu, the command palette, and the mobile attach menu. They're read with `gh` from the project's checkout. Starting a thread from an issue, from the new Issues tab in the start-from picker or mobile's ⋯ menu, links the issue to the thread's tab group. Pickers mark linked issues In use and offer to open that thread, and the chat header and mobile tab switcher show the issue's live state. Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 0c1a2c3 commit 36a5516

65 files changed

Lines changed: 2987 additions & 206 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const CONTEXT_CHIP_PRESENTATIONS = {
1919
"pull-request": { accent: "#7079e4", symbol: "git-pull-request" },
2020
skill: { accent: "#b261be", symbol: "cube" },
2121
"linear-issue": { accent: "#617de6", symbol: "ticket" },
22+
"github-issue": { accent: "#009f6e", symbol: "smallcircle.filled.circle" },
2223
repository: { accent: "#009c9c", symbol: "folder" },
2324
} as const;
2425

@@ -46,13 +47,20 @@ const PULL_REQUEST_CHIP_PRESENTATIONS = {
4647
closed: { accent: "#d55665", symbol: "git-pull-request" },
4748
} as const;
4849

50+
/** A GitHub issue chip is green while open and purple once closed, the way GitHub colours it. */
51+
const CLOSED_GITHUB_ISSUE_CHIP_PRESENTATION = {
52+
accent: "#8a70dd",
53+
symbol: "smallcircle.filled.circle",
54+
} as const;
55+
4956
export function contextChipPresentation(
5057
kind: string,
5158
record?: {
5259
readonly kind?: string;
5360
readonly name?: string;
5461
readonly mimeType?: string;
5562
readonly sectionId?: string;
63+
readonly state?: string;
5664
readonly pullRequest?: {
5765
readonly state?: string;
5866
readonly isDraft?: boolean;
@@ -84,6 +92,9 @@ export function contextChipPresentation(
8492
return PULL_REQUEST_CHIP_PRESENTATIONS[state as keyof typeof PULL_REQUEST_CHIP_PRESENTATIONS];
8593
}
8694
}
95+
if (presentationKind === "github-issue" && record?.state === "closed") {
96+
return CLOSED_GITHUB_ISSUE_CHIP_PRESENTATION;
97+
}
8798
return Object.hasOwn(CONTEXT_CHIP_PRESENTATIONS, presentationKind)
8899
? CONTEXT_CHIP_PRESENTATIONS[presentationKind as keyof typeof CONTEXT_CHIP_PRESENTATIONS]
89100
: CONTEXT_CHIP_PRESENTATIONS.file;

‎apps/mobile/src/components/ComposerAttachmentButton.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import { ControlPillMenu } from "./ControlPill";
88
const PHOTOS_ACTION: MenuAction = { id: "photos", title: "Photo Library", image: "photo" };
99
const FILES_ACTION: MenuAction = { id: "files", title: "Choose Files", image: "folder" };
1010
const LINEAR_ACTION: MenuAction = { id: "linear", title: "Linear issue", image: "ticket" };
11+
const GITHUB_ISSUE_ACTION: MenuAction = {
12+
id: "github-issue",
13+
title: "GitHub issue",
14+
image: "smallcircle.filled.circle",
15+
};
1116
const REPOSITORY_ACTION: MenuAction = {
1217
id: "repository",
1318
title: "Repository",
@@ -21,6 +26,8 @@ export function ComposerAttachmentButton(props: {
2126
readonly onPickFiles: () => Promise<void>;
2227
/** Omit to hide the Linear action. See `useLinearIssuePicker`. */
2328
readonly onPickLinearIssue?: () => void;
29+
/** Omit to hide the GitHub issue action. See `useGitHubIssuePicker`. */
30+
readonly onPickGitHubIssue?: () => void;
2431
/** Omit to hide the repository action. See `useRepositoryPicker`. */
2532
readonly onPickRepository?: () => void;
2633
}) {
@@ -29,6 +36,7 @@ export function ComposerAttachmentButton(props: {
2936
PHOTOS_ACTION,
3037
...(props.supportsFiles ? [FILES_ACTION] : []),
3138
...(props.onPickLinearIssue ? [LINEAR_ACTION] : []),
39+
...(props.onPickGitHubIssue ? [GITHUB_ISSUE_ACTION] : []),
3240
...(props.onPickRepository ? [REPOSITORY_ACTION] : []),
3341
];
3442
const usesMenu = !props.disabled && actions.length > 1;
@@ -68,6 +76,8 @@ export function ComposerAttachmentButton(props: {
6876
void props.onPickFiles();
6977
} else if (nativeEvent.event === "linear") {
7078
props.onPickLinearIssue?.();
79+
} else if (nativeEvent.event === "github-issue") {
80+
props.onPickGitHubIssue?.();
7181
} else if (nativeEvent.event === "repository") {
7282
props.onPickRepository?.();
7383
}

‎apps/mobile/src/components/ComposerContextSheet.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,36 @@ export function ComposerContextSheet(props: {
373373
</Text>
374374
</View>
375375
) : null}
376+
{record.kind === "github-issue" ? (
377+
<View className="gap-3">
378+
<View className="gap-1">
379+
<Text selectable className="text-lg font-t3-semibold text-foreground">
380+
{record.title}
381+
</Text>
382+
<Text className="text-sm text-foreground-muted">
383+
{record.repository}#{record.number} ·{" "}
384+
{record.state === "open" ? "Open" : "Closed"}
385+
</Text>
386+
</View>
387+
{/^https?:\/\//i.test(record.url) ? (
388+
<Pressable
389+
accessibilityRole="link"
390+
onPress={() => {
391+
void tryOpenExternalUrl(record.url, "github-issue").then((opened) => {
392+
if (!opened) Alert.alert("Could not open GitHub", "Try again later.");
393+
});
394+
}}
395+
className="rounded-xl bg-subtle p-4"
396+
>
397+
<Text className="text-foreground">Open on GitHub</Text>
398+
</Pressable>
399+
) : null}
400+
{/* Plain text like the other captured context here: exactly what the agent received. */}
401+
<Text selectable className="text-sm text-foreground">
402+
{record.markdown}
403+
</Text>
404+
</View>
405+
) : null}
376406
{record.kind === "thread-tab" ? (
377407
<View className="gap-3">
378408
<ContextField label="Chat" value={record.title} />
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
import type {
2+
EnvironmentId,
3+
GitHubIssueStateFilter,
4+
GitHubIssueSummary,
5+
OrchestrationMessageContext,
6+
ProjectId,
7+
} from "@t3tools/contracts";
8+
import {
9+
gitHubIssueContextRecord,
10+
gitHubIssueLabel,
11+
threadsForGitHubIssue,
12+
} from "@t3tools/client-runtime/state/github-issues";
13+
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
14+
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
15+
import { useAtomValue } from "@effect/atom-react";
16+
import * as Cause from "effect/Cause";
17+
import * as Option from "effect/Option";
18+
import { AsyncResult } from "effect/unstable/reactivity";
19+
import { StackActions, useNavigation } from "@react-navigation/native";
20+
import { useState, type ReactNode } from "react";
21+
import { ActivityIndicator, Alert, FlatList, Pressable, View } from "react-native";
22+
import { useSafeAreaInsets } from "react-native-safe-area-context";
23+
24+
import { useThreadShells } from "../state/entities";
25+
import { gitHubIssueEnvironment } from "../state/githubIssues";
26+
import { useDebouncedValue } from "../state/queries";
27+
import { useEnvironmentQuery } from "../state/query";
28+
import { useAtomCommand } from "../state/use-atom-command";
29+
import {
30+
captureComposerDraftInsertion,
31+
insertComposerDraftContext,
32+
type ComposerDraftInsertion,
33+
} from "../state/use-composer-drafts";
34+
import { confirmOpenExistingThread } from "./confirmOpenExistingThread";
35+
import { AppText as Text, AppTextInput } from "./AppText";
36+
import { PickerSheet } from "./PickerSheet";
37+
import { SegmentedControl } from "./SegmentedControl";
38+
39+
/** Each search runs `gh` on the host, so typing settles before it queries. */
40+
const SEARCH_DEBOUNCE_MS = 300;
41+
42+
const STATE_OPTIONS = [
43+
{ value: "open", label: "Open" },
44+
{ value: "closed", label: "Closed" },
45+
{ value: "all", label: "All" },
46+
] as const satisfies ReadonlyArray<{ value: GitHubIssueStateFilter; label: string }>;
47+
48+
/** GitHub's failures carry a reason; the host's `gh` setup deserves a clearer hint than its detail. */
49+
function gitHubIssueErrorMessage(error: unknown, fallback: string): string {
50+
if (typeof error === "object" && error !== null && "reason" in error) {
51+
if (error.reason === "rate-limited") return "GitHub is busy. Try again shortly.";
52+
if (error.reason === "unavailable") {
53+
return "The GitHub CLI (gh) is not installed on the computer running T3 Code.";
54+
}
55+
if (error.reason === "not-authenticated") {
56+
return "The GitHub CLI is not signed in. Run `gh auth login` on the computer running T3 Code.";
57+
}
58+
}
59+
return error instanceof Error && error.message.trim() ? error.message : fallback;
60+
}
61+
62+
/**
63+
* Attach inserts the issue into a composer draft. `cwd` is the checkout whose repository lists
64+
* issues. With `startFrom` it starts a new thread from the issue: it first offers threads already
65+
* linked to it, and the thread the draft creates is linked once it sends.
66+
*/
67+
export interface GitHubIssuePickerTarget {
68+
readonly environmentId: EnvironmentId;
69+
readonly draftKey: string;
70+
readonly cwd: string;
71+
readonly startFrom?: { readonly projectId: ProjectId };
72+
}
73+
74+
type OpenedGitHubIssuePicker = GitHubIssuePickerTarget & {
75+
readonly insertion: ComposerDraftInsertion;
76+
};
77+
78+
/** Issues picked to start a draft's thread from, by draft key, until the draft sends. */
79+
const startFromIssueUrls = new Map<string, string>();
80+
81+
/**
82+
* The issue URL the draft was started from, if its chip is still in the draft. Clears it: the
83+
* caller links the thread the draft just created.
84+
*/
85+
export function takeStartFromGitHubIssue(
86+
draftKey: string,
87+
context: OrchestrationMessageContext | undefined,
88+
): string | null {
89+
const url = startFromIssueUrls.get(draftKey);
90+
startFromIssueUrls.delete(draftKey);
91+
if (url === undefined) return null;
92+
const attached = context?.records.some(
93+
(record) => record.kind === "github-issue" && "url" in record && record.url === url,
94+
);
95+
return attached ? url : null;
96+
}
97+
98+
/**
99+
* A GitHub issue picker. The owner renders `sheet` somewhere that outlives composer focus:
100+
* opening the sheet blurs the editor, which can unmount a focus-dependent toolbar.
101+
*/
102+
export function useGitHubIssuePicker(target: GitHubIssuePickerTarget | null): {
103+
readonly open: () => void;
104+
readonly sheet: ReactNode;
105+
} {
106+
const [opened, setOpened] = useState<OpenedGitHubIssuePicker | null>(null);
107+
return {
108+
open: () => {
109+
if (target) {
110+
setOpened({ ...target, insertion: captureComposerDraftInsertion(target.draftKey) });
111+
}
112+
},
113+
sheet: opened ? <GitHubIssuePickerSheet {...opened} onClose={() => setOpened(null)} /> : null,
114+
};
115+
}
116+
117+
/** Attaches a GitHub issue at the caret the composer had when the sheet opened. */
118+
function GitHubIssuePickerSheet(props: OpenedGitHubIssuePicker & { readonly onClose: () => void }) {
119+
const insets = useSafeAreaInsets();
120+
const navigation = useNavigation();
121+
const { startFrom } = props;
122+
const [query, setQuery] = useState("");
123+
const [state, setState] = useState<GitHubIssueStateFilter>("open");
124+
const trimmed = query.trim();
125+
const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS);
126+
const result = useAtomValue(
127+
gitHubIssueEnvironment.issues({
128+
environmentId: props.environmentId,
129+
input: { cwd: props.cwd, state, ...(settled ? { query: settled } : {}) },
130+
}),
131+
);
132+
const threadLinks = useEnvironmentQuery(
133+
gitHubIssueEnvironment.threadLinks({ environmentId: props.environmentId, input: {} }),
134+
).data;
135+
// Starting from an issue offers the project's threads; attaching only marks issues in use.
136+
const candidateThreads = useThreadShells().filter(
137+
(thread) =>
138+
thread.environmentId === props.environmentId &&
139+
(!startFrom || thread.projectId === startFrom.projectId),
140+
);
141+
const getIssue = useAtomCommand(gitHubIssueEnvironment.getIssue, {
142+
label: "github issue fetch",
143+
reportFailure: false,
144+
});
145+
const [attaching, setAttaching] = useState<string | null>(null);
146+
const issues = Option.getOrNull(AsyncResult.value(result))?.issues ?? [];
147+
const pending = settled !== trimmed || result.waiting;
148+
const error =
149+
result._tag === "Failure"
150+
? gitHubIssueErrorMessage(Cause.squash(result.cause), "Could not load GitHub issues.")
151+
: null;
152+
153+
const pick = async (issue: GitHubIssueSummary) => {
154+
if (attaching) return;
155+
if (startFrom) {
156+
const choice = await confirmOpenExistingThread(
157+
gitHubIssueLabel(issue),
158+
threadsForGitHubIssue(candidateThreads, threadLinks, issue.url),
159+
);
160+
if (choice === "cancel") return;
161+
if (choice !== "start") {
162+
props.onClose();
163+
navigation.dispatch(
164+
StackActions.replace("Thread", {
165+
environmentId: String(choice.environmentId),
166+
threadId: String(choice.id),
167+
}),
168+
);
169+
return;
170+
}
171+
}
172+
await attach(issue);
173+
};
174+
175+
const attach = async (issue: GitHubIssueSummary) => {
176+
setAttaching(issue.url);
177+
try {
178+
const fetched = await getIssue({
179+
environmentId: props.environmentId,
180+
input: { url: issue.url },
181+
});
182+
if (fetched._tag === "Failure") {
183+
Alert.alert(
184+
"Could not attach issue",
185+
gitHubIssueErrorMessage(squashAtomCommandFailure(fetched), "Try again."),
186+
);
187+
return;
188+
}
189+
const record = gitHubIssueContextRecord(fetched.value);
190+
if (
191+
!insertComposerDraftContext(
192+
props.draftKey,
193+
{
194+
text: formatComposerContextReference(record),
195+
context: { version: 1, records: [record] },
196+
},
197+
props.insertion,
198+
)
199+
) {
200+
Alert.alert("Too many context items", "Remove some context from the draft and try again.");
201+
return;
202+
}
203+
if (startFrom) startFromIssueUrls.set(props.draftKey, issue.url);
204+
props.onClose();
205+
} finally {
206+
setAttaching(null);
207+
}
208+
};
209+
210+
return (
211+
<PickerSheet title={startFrom ? "Start from issue" : "GitHub issue"} onClose={props.onClose}>
212+
<View className="gap-3 px-4 pb-3">
213+
<AppTextInput
214+
accessibilityLabel="Search GitHub issues"
215+
autoFocus
216+
autoCapitalize="none"
217+
autoCorrect={false}
218+
clearButtonMode="while-editing"
219+
placeholder="Search, or paste #123 or an issue link"
220+
returnKeyType="search"
221+
value={query}
222+
onChangeText={setQuery}
223+
/>
224+
<SegmentedControl
225+
options={STATE_OPTIONS}
226+
selected={state}
227+
onSelect={setState}
228+
size="compact"
229+
/>
230+
</View>
231+
<FlatList
232+
data={issues}
233+
keyExtractor={(issue) => issue.url}
234+
keyboardShouldPersistTaps="handled"
235+
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }}
236+
ListEmptyComponent={
237+
<View className="items-center p-6">
238+
{pending ? (
239+
<ActivityIndicator />
240+
) : (
241+
<Text
242+
selectable={error !== null}
243+
className={
244+
error ? "text-center text-danger-foreground" : "text-center text-foreground-muted"
245+
}
246+
>
247+
{error ?? (trimmed ? "No matching issues." : "No issues.")}
248+
</Text>
249+
)}
250+
</View>
251+
}
252+
renderItem={({ item }) => {
253+
const inUse = threadsForGitHubIssue(candidateThreads, threadLinks, item.url).length > 0;
254+
return (
255+
<Pressable
256+
accessibilityRole="button"
257+
accessibilityLabel={`${gitHubIssueLabel(item)} ${item.title}, ${item.state}${inUse ? ", in use" : ""}`}
258+
disabled={attaching !== null}
259+
onPress={() => void pick(item)}
260+
className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60"
261+
>
262+
<View className="min-w-0 flex-1 gap-0.5">
263+
<Text className="text-base text-foreground" numberOfLines={2}>
264+
{item.title}
265+
</Text>
266+
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
267+
{gitHubIssueLabel(item)} · {item.state === "open" ? "Open" : "Closed"}
268+
{inUse ? " · In use" : ""}
269+
</Text>
270+
</View>
271+
{attaching === item.url ? <ActivityIndicator /> : null}
272+
</Pressable>
273+
);
274+
}}
275+
/>
276+
</PickerSheet>
277+
);
278+
}

0 commit comments

Comments
 (0)