Skip to content

Commit 0487615

Browse files
feat: attach Slack messages and threads as chat context (#134)
Pasting a Slack message link, picking one from the paperclip menu or the command palette, or choosing one in the composer's `#` menu now attaches the message's thread as a chip. It works the same way as Linear issues. The server reads the thread with the user's own Slack token and saves it as capped markdown when it is attached. That markdown keeps the first message and the linked one, fills the rest newest first, and resolves mentions to names. The snapshot is inlined into the prompt for every provider. Right-clicking a result in the picker attaches the message on its own. Settings > Integrations > Slack connects the account with PKCE OAuth. The redirect goes to a fixed localhost loopback port, and remote browsers can paste the redirect URL back. There is no built-in Slack app. Slack lets a distributed app without Marketplace approval read only 15 thread messages a minute, so each workspace makes its own app from a manifest the setting copies and enters its client ID. Mobile renders the chips and has a picker sheet. Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 6d7e409 commit 0487615

57 files changed

Lines changed: 3641 additions & 32 deletions

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: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const CONTEXT_CHIP_PRESENTATIONS = {
2020
skill: { accent: "#b261be", symbol: "cube" },
2121
"linear-issue": { accent: "#617de6", symbol: "ticket" },
2222
"github-issue": { accent: "#009f6e", symbol: "smallcircle.filled.circle" },
23+
"slack-thread": { accent: "#c6589c", symbol: "number" },
2324
repository: { accent: "#009c9c", symbol: "folder" },
2425
} as const;
2526

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const GITHUB_ISSUE_ACTION: MenuAction = {
1313
title: "GitHub issue",
1414
image: "smallcircle.filled.circle",
1515
};
16+
const SLACK_ACTION: MenuAction = { id: "slack", title: "Slack message", image: "number" };
1617
const REPOSITORY_ACTION: MenuAction = {
1718
id: "repository",
1819
title: "Repository",
@@ -28,6 +29,8 @@ export function ComposerAttachmentButton(props: {
2829
readonly onPickLinearIssue?: () => void;
2930
/** Omit to hide the GitHub issue action. See `useGitHubIssuePicker`. */
3031
readonly onPickGitHubIssue?: () => void;
32+
/** Omit to hide the Slack action. See `useSlackMessagePicker`. */
33+
readonly onPickSlackMessage?: () => void;
3134
/** Omit to hide the repository action. See `useRepositoryPicker`. */
3235
readonly onPickRepository?: () => void;
3336
}) {
@@ -37,6 +40,7 @@ export function ComposerAttachmentButton(props: {
3740
...(props.supportsFiles ? [FILES_ACTION] : []),
3841
...(props.onPickLinearIssue ? [LINEAR_ACTION] : []),
3942
...(props.onPickGitHubIssue ? [GITHUB_ISSUE_ACTION] : []),
43+
...(props.onPickSlackMessage ? [SLACK_ACTION] : []),
4044
...(props.onPickRepository ? [REPOSITORY_ACTION] : []),
4145
];
4246
const usesMenu = !props.disabled && actions.length > 1;
@@ -78,6 +82,8 @@ export function ComposerAttachmentButton(props: {
7882
props.onPickLinearIssue?.();
7983
} else if (nativeEvent.event === "github-issue") {
8084
props.onPickGitHubIssue?.();
85+
} else if (nativeEvent.event === "slack") {
86+
props.onPickSlackMessage?.();
8187
} else if (nativeEvent.event === "repository") {
8288
props.onPickRepository?.();
8389
}

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,38 @@ export function ComposerContextSheet(props: {
403403
</Text>
404404
</View>
405405
) : null}
406+
{record.kind === "slack-thread" ? (
407+
<View className="gap-3">
408+
<View className="gap-1">
409+
<Text selectable className="text-lg font-t3-semibold text-foreground">
410+
{record.title}
411+
</Text>
412+
<Text className="text-sm text-foreground-muted">
413+
{record.channelLabel} · {record.authorName}
414+
{record.replyCount > 0
415+
? ` · ${record.replyCount} ${record.replyCount === 1 ? "reply" : "replies"}`
416+
: ""}
417+
</Text>
418+
</View>
419+
{/^https?:\/\//i.test(record.url) ? (
420+
<Pressable
421+
accessibilityRole="link"
422+
onPress={() => {
423+
void tryOpenExternalUrl(record.url, "slack").then((opened) => {
424+
if (!opened) Alert.alert("Could not open Slack", "Try again later.");
425+
});
426+
}}
427+
className="rounded-xl bg-subtle p-4"
428+
>
429+
<Text className="text-foreground">Open in Slack</Text>
430+
</Pressable>
431+
) : null}
432+
{/* Plain text like the other captured context here: exactly what the agent received. */}
433+
<Text selectable className="text-sm text-foreground">
434+
{record.markdown}
435+
</Text>
436+
</View>
437+
) : null}
406438
{record.kind === "thread-tab" ? (
407439
<View className="gap-3">
408440
<ContextField label="Chat" value={record.title} />
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
import type { EnvironmentId, SlackMessageSummary } from "@t3tools/contracts";
2+
import { useAtomValue } from "@effect/atom-react";
3+
import { slackThreadContextRecord } from "@t3tools/client-runtime/state/slack";
4+
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5+
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
6+
import * as Cause from "effect/Cause";
7+
import * as Option from "effect/Option";
8+
import { AsyncResult } from "effect/unstable/reactivity";
9+
import { useState, type ReactNode } from "react";
10+
import { ActivityIndicator, Alert, FlatList, Pressable, View } from "react-native";
11+
import { useSafeAreaInsets } from "react-native-safe-area-context";
12+
13+
import { relativeTime } from "../lib/time";
14+
import { slackEnvironment } from "../state/slack";
15+
import { useDebouncedValue } from "../state/queries";
16+
import { useEnvironmentQuery } from "../state/query";
17+
import { useAtomCommand } from "../state/use-atom-command";
18+
import {
19+
captureComposerDraftInsertion,
20+
insertComposerDraftContext,
21+
type ComposerDraftInsertion,
22+
} from "../state/use-composer-drafts";
23+
import { AppText as Text, AppTextInput } from "./AppText";
24+
import { PickerSheet } from "./PickerSheet";
25+
26+
/** Slack allows about 20 searches a minute, so typing settles longer before it queries. */
27+
const SEARCH_DEBOUNCE_MS = 400;
28+
29+
/** Slack's failures carry a reason; a rate limit deserves a clearer hint than its detail. */
30+
function slackErrorMessage(error: unknown, fallback: string): string {
31+
if (typeof error === "object" && error !== null && "reason" in error) {
32+
if (error.reason === "rate-limited") return "Slack is busy. Try again shortly.";
33+
if (error.reason === "not-connected" || error.reason === "revoked") {
34+
return "Slack is not connected. Connect it from Settings > Integrations on desktop or web.";
35+
}
36+
if (error.reason === "not-found") return "That message is gone or not visible to you.";
37+
}
38+
return error instanceof Error && error.message.trim() ? error.message : fallback;
39+
}
40+
41+
export interface SlackMessagePickerTarget {
42+
readonly environmentId: EnvironmentId;
43+
readonly draftKey: string;
44+
}
45+
46+
type OpenedSlackMessagePicker = SlackMessagePickerTarget & {
47+
readonly insertion: ComposerDraftInsertion;
48+
};
49+
50+
/**
51+
* A Slack message picker. The owner renders `sheet` somewhere that outlives composer focus:
52+
* opening the sheet blurs the editor, which can unmount a focus-dependent toolbar.
53+
*/
54+
export function useSlackMessagePicker(target: SlackMessagePickerTarget | null): {
55+
readonly open: () => void;
56+
readonly sheet: ReactNode;
57+
} {
58+
const [opened, setOpened] = useState<OpenedSlackMessagePicker | null>(null);
59+
return {
60+
open: () => {
61+
if (target) {
62+
setOpened({ ...target, insertion: captureComposerDraftInsertion(target.draftKey) });
63+
}
64+
},
65+
sheet: opened ? <SlackMessagePickerSheet {...opened} onClose={() => setOpened(null)} /> : null,
66+
};
67+
}
68+
69+
/**
70+
* Attaches a Slack thread at the caret the composer had when the sheet opened. Mobile has no
71+
* Slack settings, so an unconnected environment points at desktop or web.
72+
*/
73+
function SlackMessagePickerSheet(
74+
props: OpenedSlackMessagePicker & { readonly onClose: () => void },
75+
) {
76+
const connection = useEnvironmentQuery(
77+
slackEnvironment.connection({ environmentId: props.environmentId, input: {} }),
78+
);
79+
const phase = connection.data?.phase;
80+
return (
81+
<PickerSheet title="Slack message" onClose={props.onClose}>
82+
{phase === "connected" ? (
83+
<SlackMessageSearch {...props} />
84+
) : (
85+
<View className="flex-1 items-center justify-center p-6">
86+
{phase === undefined && !connection.error ? (
87+
<ActivityIndicator />
88+
) : (
89+
<Text className="text-center text-foreground-muted">
90+
{connection.error ??
91+
"Slack is not connected on this environment. Connect it from Settings > Integrations on desktop or web."}
92+
</Text>
93+
)}
94+
</View>
95+
)}
96+
</PickerSheet>
97+
);
98+
}
99+
100+
function SlackMessageSearch(props: OpenedSlackMessagePicker & { readonly onClose: () => void }) {
101+
const [query, setQuery] = useState("");
102+
const trimmed = query.trim();
103+
const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS);
104+
const getThread = useAtomCommand(slackEnvironment.getThread, {
105+
label: "slack thread fetch",
106+
reportFailure: false,
107+
});
108+
const [attaching, setAttaching] = useState<string | null>(null);
109+
110+
const attach = async (message: SlackMessageSummary) => {
111+
if (attaching) return;
112+
setAttaching(message.url);
113+
try {
114+
const fetched = await getThread({
115+
environmentId: props.environmentId,
116+
input: {
117+
channelId: message.channelId,
118+
ts: message.ts,
119+
threadTs: message.threadTs ?? undefined,
120+
url: message.url,
121+
scope: "thread",
122+
},
123+
});
124+
if (fetched._tag === "Failure") {
125+
Alert.alert(
126+
"Could not attach Slack message",
127+
slackErrorMessage(squashAtomCommandFailure(fetched), "Try again."),
128+
);
129+
return;
130+
}
131+
const record = slackThreadContextRecord(fetched.value);
132+
if (
133+
!insertComposerDraftContext(
134+
props.draftKey,
135+
{
136+
text: formatComposerContextReference(record),
137+
context: { version: 1, records: [record] },
138+
},
139+
props.insertion,
140+
)
141+
) {
142+
Alert.alert("Too many context items", "Remove some context from the draft and try again.");
143+
return;
144+
}
145+
props.onClose();
146+
} finally {
147+
setAttaching(null);
148+
}
149+
};
150+
151+
return (
152+
<View className="flex-1">
153+
<View className="px-4 pb-3">
154+
<AppTextInput
155+
accessibilityLabel="Search Slack messages"
156+
autoFocus
157+
autoCapitalize="none"
158+
autoCorrect={false}
159+
clearButtonMode="while-editing"
160+
placeholder="Search Slack"
161+
returnKeyType="search"
162+
value={query}
163+
onChangeText={setQuery}
164+
/>
165+
</View>
166+
{settled ? (
167+
<SlackMessageResults
168+
environmentId={props.environmentId}
169+
query={settled}
170+
pendingInput={settled !== trimmed}
171+
attaching={attaching}
172+
onPick={(message) => void attach(message)}
173+
/>
174+
) : (
175+
<View className="items-center p-6">
176+
{trimmed ? (
177+
<ActivityIndicator />
178+
) : (
179+
<Text className="text-center text-foreground-muted">
180+
Search Slack. Try in:#channel or from:@name
181+
</Text>
182+
)}
183+
</View>
184+
)}
185+
</View>
186+
);
187+
}
188+
189+
/** Mounted only for a settled, non-empty query, so an empty box never spends a search. */
190+
function SlackMessageResults(props: {
191+
readonly environmentId: EnvironmentId;
192+
readonly query: string;
193+
readonly pendingInput: boolean;
194+
readonly attaching: string | null;
195+
readonly onPick: (message: SlackMessageSummary) => void;
196+
}) {
197+
const insets = useSafeAreaInsets();
198+
const result = useAtomValue(
199+
slackEnvironment.messages({
200+
environmentId: props.environmentId,
201+
input: { query: props.query },
202+
}),
203+
);
204+
const messages = Option.getOrNull(AsyncResult.value(result))?.messages ?? [];
205+
const pending = props.pendingInput || result.waiting;
206+
const error =
207+
result._tag === "Failure"
208+
? slackErrorMessage(Cause.squash(result.cause), "Could not search Slack.")
209+
: null;
210+
return (
211+
<FlatList
212+
data={messages}
213+
keyExtractor={(message) => message.url}
214+
keyboardShouldPersistTaps="handled"
215+
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }}
216+
ListEmptyComponent={
217+
<View className="items-center p-6">
218+
{pending ? (
219+
<ActivityIndicator />
220+
) : (
221+
<Text
222+
selectable={error !== null}
223+
className={
224+
error ? "text-center text-danger-foreground" : "text-center text-foreground-muted"
225+
}
226+
>
227+
{error ?? "No matching messages."}
228+
</Text>
229+
)}
230+
</View>
231+
}
232+
renderItem={({ item }) => (
233+
<Pressable
234+
accessibilityRole="button"
235+
accessibilityLabel={`${item.authorName} in ${item.channelLabel}: ${item.text}`}
236+
disabled={props.attaching !== null}
237+
onPress={() => props.onPick(item)}
238+
className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60"
239+
>
240+
<View className="min-w-0 flex-1 gap-0.5">
241+
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
242+
<Text className="text-sm font-t3-semibold text-foreground">{item.authorName}</Text>
243+
{` · ${item.channelLabel} · ${relativeTime(item.postedAt)}`}
244+
</Text>
245+
<Text className="text-base text-foreground" numberOfLines={2}>
246+
{item.text}
247+
</Text>
248+
</View>
249+
{props.attaching === item.url ? <ActivityIndicator /> : null}
250+
</Pressable>
251+
)}
252+
/>
253+
);
254+
}

‎apps/mobile/src/features/threads/NewTaskDraftScreen.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import {
5959
takeStartFromGitHubIssue,
6060
useGitHubIssuePicker,
6161
} from "../../components/GitHubIssuePickerSheet";
62+
import { useSlackMessagePicker } from "../../components/SlackMessagePickerSheet";
6263
import { useRepositoryPicker } from "../../components/RepositoryPickerSheet";
6364
import { ControlPillMenu } from "../../components/ControlPillMenu";
6465
import { gitHubIssueEnvironment } from "../../state/githubIssues";
@@ -990,6 +991,11 @@ export function NewTaskDraftScreen(props: {
990991
? { environmentId: flow.selectedEnvironmentId, draftKey: flow.draftKey }
991992
: null,
992993
);
994+
const slackMessagePicker = useSlackMessagePicker(
995+
flow.draftKey && flow.selectedEnvironmentId
996+
? { environmentId: flow.selectedEnvironmentId, draftKey: flow.draftKey }
997+
: null,
998+
);
993999
const startFromIssuePicker = useLinearIssuePicker(
9941000
flow.draftKey && selectedProject
9951001
? {
@@ -1823,6 +1829,11 @@ export function NewTaskDraftScreen(props: {
18231829
onPickGitHubIssue={
18241830
flow.draftKey && selectedProject ? gitHubIssuePicker.open : undefined
18251831
}
1832+
onPickSlackMessage={
1833+
flow.draftKey && flow.selectedEnvironmentId
1834+
? slackMessagePicker.open
1835+
: undefined
1836+
}
18261837
onPickRepository={flow.draftKey ? repositoryPicker.open : undefined}
18271838
/>
18281839
<View className="min-w-0 flex-1 flex-row items-center justify-end gap-2">
@@ -1908,6 +1919,7 @@ export function NewTaskDraftScreen(props: {
19081919
{startFromIssuePicker.sheet}
19091920
{gitHubIssuePicker.sheet}
19101921
{startFromGitHubIssuePicker.sheet}
1922+
{slackMessagePicker.sheet}
19111923
{startFromPullRequestPicker.sheet}
19121924
{repositoryPicker.sheet}
19131925
</View>

0 commit comments

Comments
 (0)