diff --git a/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx index f62aba2c73668..f72393f4b896c 100644 --- a/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsFollowUpRouteScreen.tsx @@ -11,6 +11,7 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/ import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsScreen } from "./components/SettingsScreen"; +import { ShareTemplatesSection } from "./ShareTemplatesSection"; const FOLLOW_UP_OPTIONS: ReadonlyArray<{ readonly behavior: FollowUpBehavior; @@ -67,6 +68,7 @@ export function SettingsFollowUpRouteScreen() { keyboard, hold {Platform.OS === "android" ? "Ctrl" : "Command"} while sending. + ); diff --git a/apps/mobile/src/features/settings/ShareTemplatesSection.tsx b/apps/mobile/src/features/settings/ShareTemplatesSection.tsx new file mode 100644 index 0000000000000..8226d17377d13 --- /dev/null +++ b/apps/mobile/src/features/settings/ShareTemplatesSection.tsx @@ -0,0 +1,98 @@ +import { useGT } from "gt-react-native"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { useState } from "react"; +import { TextInput, View } from "react-native"; + +import * as Dialog from "../../components/ui/Dialog"; +import { IconButton } from "../../components/ui/IconButton"; +import { ListActionRow } from "../../components/ui/ListActionRow"; +import { uuidv4 } from "../../lib/uuid"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { SHARE_TEMPLATE_PLACEHOLDER, type ShareTemplate } from "../sharing/share-templates"; +import { SettingsSection } from "./components/SettingsSection"; + +export function ShareTemplatesSection() { + const gt = useGT(); + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const [addedTemplateId, setAddedTemplateId] = useState(null); + const templates = AsyncResult.isSuccess(preferencesResult) + ? (preferencesResult.value.shareTemplates ?? []) + : null; + + const updateTemplates = ( + transform: (templates: ReadonlyArray) => ReadonlyArray, + ) => + savePreferences({ + transform: (current) => ({ shareTemplates: transform(current.shareTemplates ?? []) }), + }); + const addTemplate = () => { + const id = uuidv4(); + setAddedTemplateId(id); + updateTemplates((current) => [...current, { id, prompt: "" }]); + }; + const removeTemplate = (template: ShareTemplate) => { + const remove = () => + updateTemplates((current) => current.filter(({ id }) => id !== template.id)); + if (!template.prompt.trim()) { + remove(); + return; + } + Dialog.confirm({ + title: gt("Delete this template?"), + confirmText: gt("Delete"), + destructive: true, + onConfirm: remove, + }); + }; + + return ( + + {(templates ?? []).map((template) => ( + + {/* Uncontrolled so saving each keystroke never moves the cursor. */} + + updateTemplates((current) => + current.map((candidate) => + candidate.id === template.id ? { ...candidate, prompt } : candidate, + ), + ) + } + /> + removeTemplate(template)} + /> + + ))} + + + ); +} diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 9b8334641290d..f5be0564e42e5 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -119,6 +119,8 @@ const SETTINGS_SEARCH_TERMS = { msg("queue", { $context: "settings search keyword" }), msg("steer", { $context: "settings search keyword" }), msg("while the agent is running", { $context: "settings search keyword" }), + msg("share templates", { $context: "settings search keyword" }), + msg("share sheet", { $context: "settings search keyword" }), ], SettingsArchive: [ msg("archive", { $context: "settings search keyword" }), diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx index 134e92e62f43a..bc3c131bde61c 100644 --- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -163,6 +163,7 @@ const incomingShareInbox = new IncomingShareInbox({ ? await resolvedPayloadsForFiles() : []; const draft = await buildIncomingShareDraft({ + attachmentIdPrefix: Crypto.randomUUID(), payloads, resolvedPayloads, fileReader: { diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..c10154d82f5d1 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -7,6 +7,7 @@ import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; import { buildIncomingShareDraft, + decodeIncomingShareDraft, hasIncomingShareContent, isShareFileUriUnderOwnedRoots, selectIncomingShareAttachments, @@ -20,11 +21,17 @@ describe("incoming native shares", () => { value: "file:///shared/Screenshot.png", mimeType: "image/png", }; + const file: SharePayload = { + shareType: "file", + value: "file:///shared/report.pdf", + mimeType: "application/pdf", + }; const payloads: SharePayload[] = [ { shareType: "text", value: "Please explain this error" }, { shareType: "url", value: "https://example.com/issue/1" }, { shareType: "text", value: "Please explain this error" }, image, + file, ]; const resolvedImage: ResolvedSharePayload = { ...image, @@ -36,19 +43,38 @@ describe("incoming native shares", () => { }; const removeOwnedFile = vi.fn(() => Promise.resolve()); - const result = await buildIncomingShareDraft({ - id: "share-1", - createdAt: "2026-07-15T10:00:00.000Z", - payloads, - resolvedPayloads: [resolvedImage], - fileReader: { - readBase64: async () => "YWJj", - removeOwnedFile, - }, - }); + const build = (attachmentIdPrefix: string) => + buildIncomingShareDraft({ + attachmentIdPrefix, + id: "share-1", + createdAt: "2026-07-15T10:00:00.000Z", + payloads, + resolvedPayloads: [ + resolvedImage, + { + ...file, + contentUri: file.value, + contentType: "file", + contentMimeType: "application/pdf", + contentSize: 3, + originalName: "report.pdf", + }, + ], + fileReader: { + readBase64: async () => "YWJj", + removeOwnedFile, + }, + }); + + const result = await build("share-1"); + const repeated = await build("second-handoff"); + expect( + new Set([...result.attachments, ...repeated.attachments].map((attachment) => attachment.id)) + .size, + ).toBe(4); expect(result).toEqual({ - schemaVersion: 1, + schemaVersion: 2, id: "share-1", createdAt: "2026-07-15T10:00:00.000Z", text: "Please explain this error\n\nhttps://example.com/issue/1", @@ -62,9 +88,22 @@ describe("incoming native shares", () => { dataUrl: "data:image/png;base64,YWJj", previewUri: "data:image/png;base64,YWJj", }, + { + id: "share-1-file-4", + type: "file", + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 3, + fileUri: "file:///shared/report.pdf", + }, ], warnings: [], }); + expect(decodeIncomingShareDraft(result)).toEqual(result); + expect(decodeIncomingShareDraft({ ...result, schemaVersion: 1 })).toEqual({ + ...result, + schemaVersion: 1, + }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); expect(hasIncomingShareContent(result)).toBe(true); }); @@ -79,6 +118,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(() => Promise.resolve()); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-2", id: "share-2", createdAt: "2026-07-15T10:00:00.000Z", payloads: [image], @@ -113,6 +153,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async (_uri: string) => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-report", id: "share-report", createdAt: "2026-07-15T10:00:00.000Z", payloads: [file], @@ -155,6 +196,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async () => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-video", id: "share-video", createdAt: "2026-08-30T10:00:00.000Z", payloads: [{ ...video, shareType: "video" }], @@ -200,6 +242,7 @@ describe("incoming native shares", () => { }; const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-empty", id: "share-empty", createdAt: "2026-07-15T10:00:00.000Z", payloads: [file], @@ -225,6 +268,7 @@ describe("incoming native shares", () => { const readSize = vi.fn(async (uri: string) => (uri.startsWith("content:") ? null : 42)); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-android-report", id: "share-android-report", createdAt: "2026-07-15T10:00:00.000Z", payloads: [file], @@ -263,6 +307,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async (_uri: string) => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-empty-copy", id: "share-empty-copy", createdAt: "2026-07-15T10:00:00.000Z", payloads: [file], @@ -285,6 +330,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async () => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-no-copy", id: "share-no-copy", createdAt: "2026-07-15T10:00:00.000Z", payloads: [{ shareType: "file", value: sourceUri, mimeType: "application/pdf" }], @@ -307,6 +353,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async (_uri: string) => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-copy", id: "share-copy", createdAt: "2026-07-15T10:00:00.000Z", payloads: [{ shareType: "file", value: payloadUri, mimeType: "application/pdf" }], @@ -389,6 +436,7 @@ describe("incoming native shares", () => { const readBase64 = vi.fn(async () => "YWJj"); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-3", id: "share-3", createdAt: "2026-07-15T10:00:00.000Z", payloads, @@ -434,6 +482,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async () => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-duplicates", id: "share-duplicates", createdAt: "2026-07-16T08:00:00.000Z", payloads: [duplicate, duplicate], @@ -461,6 +510,7 @@ describe("incoming native shares", () => { }; const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-cleanup-failure", id: "share-cleanup-failure", createdAt: "2026-07-16T08:00:00.000Z", payloads: [image], @@ -487,6 +537,7 @@ describe("incoming native shares", () => { const removeOwnedFile = vi.fn(async (_uri: string) => undefined); const result = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-persist-leak", id: "share-persist-leak", createdAt: "2026-07-16T08:00:00.000Z", payloads: [file], diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..5c710581a4f35 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -21,7 +21,7 @@ import type { DraftComposerAttachment } from "../../lib/composerImages"; import { estimateBase64ByteSize } from "../../lib/base64"; export interface IncomingShareDraft { - readonly schemaVersion: 1; + readonly schemaVersion: 1 | 2; readonly id: string; readonly createdAt: string; readonly destination?: IncomingShareDestination; @@ -41,7 +41,7 @@ const IncomingShareDestinationSchema = Schema.Struct({ }); export const IncomingShareDraftSchema = Schema.Struct({ - schemaVersion: Schema.Literal(1), + schemaVersion: Schema.Literals([1, 2]), id: Schema.String, createdAt: Schema.String, destination: Schema.optional(IncomingShareDestinationSchema), @@ -242,6 +242,7 @@ export async function buildIncomingShareDraft(input: { readonly resolvedPayloads: ReadonlyArray; readonly fileReader: IncomingShareFileReader; readonly id: string; + readonly attachmentIdPrefix: string; readonly createdAt: string; }): Promise { const attachments: DraftComposerAttachment[] = []; @@ -355,7 +356,7 @@ export async function buildIncomingShareDraft(input: { } } attachments.push({ - id: `${input.id}-file-${index}`, + id: `${input.attachmentIdPrefix}-file-${index}`, type: "file", name, mimeType, @@ -436,7 +437,7 @@ export async function buildIncomingShareDraft(input: { } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ - id: `${input.id}-image-${index}`, + id: `${input.attachmentIdPrefix}-image-${index}`, type: "image", name: resolved?.originalName ?? fallbackName(uri, index, mimeType), mimeType, @@ -455,7 +456,7 @@ export async function buildIncomingShareDraft(input: { } return { - schemaVersion: 1, + schemaVersion: 2, id: input.id, createdAt: input.createdAt, text: sharedText(input.payloads), diff --git a/apps/mobile/src/features/sharing/share-templates.test.ts b/apps/mobile/src/features/sharing/share-templates.test.ts new file mode 100644 index 0000000000000..4b34b5e1df64b --- /dev/null +++ b/apps/mobile/src/features/sharing/share-templates.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + applyShareTemplate, + selectedShareTemplate, + shareTemplateLabel, + usableShareTemplates, +} from "./share-templates"; + +describe("applyShareTemplate", () => { + it.each([ + { + name: "appends the shared text after a template without a placeholder", + prompt: "Review this for bugs:\n", + shared: "https://example.com/pr/1", + expected: "Review this for bugs:\n\nhttps://example.com/pr/1", + }, + { + name: "preserves shared indentation and trailing newlines", + prompt: " {{shared}} ", + shared: " code\n", + expected: " code\n", + }, + { + name: "fills every placeholder", + prompt: "Summarize {{shared}} and cite {{shared}}.", + shared: "the article", + expected: "Summarize the article and cite the article.", + }, + { + name: "keeps replacement patterns in the shared text literally", + prompt: "Explain: {{shared}}", + shared: "cost is $& or $1", + expected: "Explain: cost is $& or $1", + }, + { + name: "uses the template alone when only files were shared", + prompt: "Describe these images.\n\n{{shared}}", + shared: "", + expected: "Describe these images.", + }, + { + name: "uses the template alone without a placeholder or shared text", + prompt: " Describe these images. ", + shared: "", + expected: "Describe these images.", + }, + ])("$name", ({ prompt, shared, expected }) => { + expect(applyShareTemplate(prompt, shared)).toBe(expected); + }); +}); + +describe("shareTemplateLabel", () => { + it.each([ + { prompt: "\nReview this for bugs:\nMore detail", expected: "Review this for bugs:" }, + { prompt: "Summarize {{shared}}", expected: "Summarize …" }, + { prompt: "{{shared}}", expected: "…" }, + { prompt: " ", expected: "Template" }, + ])("labels $prompt as $expected", ({ prompt, expected }) => { + expect(shareTemplateLabel(prompt)).toBe(expected); + }); +}); + +describe("usableShareTemplates", () => { + it("skips blank templates", () => { + expect( + usableShareTemplates([ + { id: "a", prompt: "Review" }, + { id: "b", prompt: " \n" }, + ]), + ).toEqual([{ id: "a", prompt: "Review" }]); + }); +}); + +describe("selectedShareTemplate", () => { + it.each([ + { id: "same-content", createdAt: "2026-10-31T00:00:00Z", selected: true }, + { id: "same-content", createdAt: "2026-10-31T00:01:00Z", selected: false }, + { id: "other-content", createdAt: "2026-10-31T00:00:00Z", selected: false }, + ])("matches the choice to handoff $id at $createdAt", ({ id, createdAt, selected }) => { + const choice = { + shareId: "same-content", + createdAt: "2026-10-31T00:00:00Z", + template: "Review {{shared}}", + }; + expect(selectedShareTemplate({ id, createdAt }, choice)).toBe(selected ? choice : null); + }); +}); diff --git a/apps/mobile/src/features/sharing/share-templates.ts b/apps/mobile/src/features/sharing/share-templates.ts new file mode 100644 index 0000000000000..aa36e06cb58c1 --- /dev/null +++ b/apps/mobile/src/features/sharing/share-templates.ts @@ -0,0 +1,47 @@ +import { msg } from "gt-react-native"; + +import { m, type MessageResolver } from "../../i18n/messages"; + +export interface ShareTemplate { + readonly id: string; + readonly prompt: string; +} + +export const SHARE_TEMPLATE_PLACEHOLDER = "{{shared}}"; + +/** Puts the shared text where the template says {{shared}}, or after the template. */ +export function applyShareTemplate(prompt: string, sharedText: string): string { + if (prompt.includes(SHARE_TEMPLATE_PLACEHOLDER)) { + // split/join, not replaceAll: shared text may contain `$&`-style replacement patterns. + const result = prompt.trim().split(SHARE_TEMPLATE_PLACEHOLDER).join(sharedText); + return sharedText ? result : result.trim(); + } + const template = prompt.trim(); + return sharedText ? `${template}\n\n${sharedText}` : template; +} + +export function shareTemplateLabel(prompt: string, resolve: MessageResolver = m): string { + const firstLine = prompt.trim().split("\n", 1)[0] ?? ""; + return firstLine.split(SHARE_TEMPLATE_PLACEHOLDER).join("…").trim() || resolve(msg("Template")); +} + +export function usableShareTemplates( + templates: ReadonlyArray | undefined, +): ReadonlyArray { + return (templates ?? []).filter((template) => template.prompt.trim().length > 0); +} + +export interface ShareTemplateChoice { + readonly shareId: string; + readonly createdAt: string; + readonly template: string | null; +} + +export function selectedShareTemplate( + share: { readonly id: string; readonly createdAt: string } | null, + choice: ShareTemplateChoice | null, +): ShareTemplateChoice | null { + return share && choice?.shareId === share.id && choice.createdAt === share.createdAt + ? choice + : null; +} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index d1230b01b7973..6b411916df267 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -55,6 +55,7 @@ import { import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; +import { Chip } from "../../components/ui/Chip"; import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences"; import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; @@ -93,7 +94,14 @@ import { resolveNewTaskWorkspaceLabel, } from "./new-task-context-presentation"; import { incomingShareImports, useIncomingShare } from "../sharing/IncomingShareProvider"; +import { + selectedShareTemplate, + type ShareTemplateChoice, + shareTemplateLabel, + usableShareTemplates, +} from "../sharing/share-templates"; import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport"; +import { mobilePreferencesAtom } from "../../state/preferences"; import { newTaskFlowKey } from "./new-task-flow-state"; import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; import { ConnectionStatusDot } from "../connection/ConnectionStatusDot"; @@ -280,6 +288,20 @@ export function NewTaskDraftScreen(props: { const loadedBranchesProjectKeyRef = useRef(null); const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false); const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null; + const preferences = useAtomValue(mobilePreferencesAtom); + const shareTemplates = AsyncResult.isSuccess(preferences) + ? usableShareTemplates(preferences.value.shareTemplates) + : AsyncResult.isFailure(preferences) + ? [] + : null; + const [shareTemplateChoice, setShareTemplateChoice] = useState(null); + const chosenShareTemplate = selectedShareTemplate(incomingShare, shareTemplateChoice); + // Null templates means preferences are still loading, so the choice is not known yet. + const isIncomingShareAwaitingTemplate = Boolean( + incomingShare && + chosenShareTemplate === null && + (shareTemplates === null || shareTemplates.length > 0), + ); const requestedInitialProjectAvailable = Boolean( props.initialProjectRef?.environmentId && props.initialProjectRef.projectId && @@ -322,7 +344,14 @@ export function NewTaskDraftScreen(props: { ); const shareImportTarget = (() => { if (!props.incomingShareId || flowKey === undefined || !flow.draftKey) return null; - if (!selectedProject || !incomingShare || isIncomingShareAwaitingServerConfig) return null; + if ( + !selectedProject || + !incomingShare || + isIncomingShareAwaitingServerConfig || + isIncomingShareAwaitingTemplate + ) { + return null; + } const initialEnvironmentId = props.initialProjectRef?.environmentId; const initialProjectId = props.initialProjectRef?.projectId; if ( @@ -342,6 +371,8 @@ export function NewTaskDraftScreen(props: { projectId: String(selectedProject.id), }, shareId: incomingShare.id, + createdAt: incomingShare.createdAt, + ...(chosenShareTemplate?.template ? { template: chosenShareTemplate.template } : {}), }; })(); const shareImportPhase = useAtomValue( @@ -726,7 +757,9 @@ export function NewTaskDraftScreen(props: { : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown) ? gt("Choose a base branch before creating a worktree.") : null - : gt("Wait for shared content to finish importing."); + : isIncomingShareAwaitingTemplate && !isImportingShare + ? gt("Choose a template for the shared content.") + : gt("Wait for shared content to finish importing."); const chooseProject = () => { if (isComposerInteractionLocked) { return; @@ -753,6 +786,40 @@ export function NewTaskDraftScreen(props: { onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")} /> ); + // A remounted route has no choice while its earlier import still runs; that import keeps its own. + const shareTemplatePicker = + incomingShare && shareTemplates && isIncomingShareAwaitingTemplate && !isImportingShare ? ( + + + {gt("Use a template for the shared content?")} + + + {shareTemplates.map((template) => ( + + setShareTemplateChoice({ + shareId: incomingShare.id, + createdAt: incomingShare.createdAt, + template: template.prompt, + }) + } + /> + ))} + + setShareTemplateChoice({ + shareId: incomingShare.id, + createdAt: incomingShare.createdAt, + template: null, + }) + } + /> + + + ) : null; const shareUnavailableNotice = isIncomingShareUnavailable ? ( The shared content is no longer in the inbox. You can continue editing this task draft. @@ -946,6 +1013,7 @@ export function NewTaskDraftScreen(props: { const draftControls = (viewportHeight: number) => ( + {shareTemplatePicker} {projectClone && projectClone.phase !== "done" && selectedProject ? ( + {shareTemplatePicker} = []): IncomingShareDraft { return { - schemaVersion: 1, + schemaVersion: 2, id: "share-1", createdAt: "2026-01-01T00:00:00.000Z", text: "shared text", @@ -71,6 +75,7 @@ function importTarget(overrides: Partial = {}): ShareImportTa draftKey: "draft-a", destination, shareId: "share-1", + createdAt: "2026-01-01T00:00:00.000Z", ...overrides, }; } @@ -155,6 +160,50 @@ describe("incoming share imports", () => { expect(deps.onWarnings).toHaveBeenCalledWith(["too big"]); }); + it("wraps each share handoff once in its chosen template", async () => { + const { drafts, inbox, imports, watch, deps } = setup({ + mergeIntoDraft: async (draftKey, content) => { + const next = mergeComposerDraftContentState(Object.fromEntries(drafts), draftKey, content); + for (const [key, value] of Object.entries(next)) drafts.set(key, value); + return { skippedAttachmentCount: 0 }; + }, + }); + const legacyDraft: ComposerDraft = { + text: "User edited the imported context", + attachments: [], + importedShareIds: ["share-1"], + }; + drafts.set("draft-a", legacyDraft); + const legacyCreatedAt = "2025-12-31T00:00:00.000Z"; + inbox.set("share-1", { + ...share(), + schemaVersion: 1, + createdAt: legacyCreatedAt, + destination, + }); + const legacyTarget = importTarget({ createdAt: legacyCreatedAt }); + watch(legacyTarget); + await imports.settled(legacyTarget); + expect(drafts.get("draft-a")).toEqual(legacyDraft); + for (const [createdAt, template] of [ + ["2026-01-01T00:00:00.000Z", "Review {{shared}} for bugs."], + ["2026-01-02T00:00:00.000Z", "Summarize {{shared}}."], + ["2026-01-03T00:00:00.000Z", "Summarize {{shared}}."], + ] as const) { + inbox.set("share-1", { ...share(), createdAt }); + const target = { ...importTarget({ template }), createdAt }; + watch(target); + await imports.settled(target); + const draft = drafts.get("draft-a")!; + expect(draft.text).toContain(template.replace("{{shared}}", "shared text")); + drafts.set("draft-a", { ...draft, text: `${draft.text}\nuser edit` }); + } + expect(drafts.get("draft-a")?.text).toBe( + "User edited the imported context\n\nReview shared text for bugs.\nuser edit\n\nSummarize shared text.\nuser edit\n\nSummarize shared text.\nuser edit", + ); + expect(deps.consume).toHaveBeenCalledTimes(4); + }); + it("runs once when its atom node is removed and rebuilt", async () => { const { imports, deps } = setup(); const tasks: Array<() => void> = []; diff --git a/apps/mobile/src/features/threads/incomingShareImport.ts b/apps/mobile/src/features/threads/incomingShareImport.ts index b59ec254bc1b8..edd9036f71557 100644 --- a/apps/mobile/src/features/threads/incomingShareImport.ts +++ b/apps/mobile/src/features/threads/incomingShareImport.ts @@ -9,6 +9,7 @@ import type { IncomingShareDraft, selectIncomingShareAttachmentsForServer, } from "../sharing/incoming-share-model"; +import { applyShareTemplate } from "../sharing/share-templates"; export type ShareImportPhase = | "idle" @@ -67,6 +68,9 @@ export interface ShareImportTarget { readonly draftKey: string; readonly destination: IncomingShareDestination; readonly shareId: string; + readonly createdAt: string; + /** The share template prompt that wraps the shared text. */ + readonly template?: string; } export interface ShareImportDeps { @@ -92,6 +96,7 @@ export interface ShareImportDeps { readonly text: string; readonly attachments: ReadonlyArray; readonly sourceShareId: string; + readonly sourceShareCreatedAt?: string; }, ) => Promise<{ readonly skippedAttachmentCount: number }>; readonly selectAttachments: ( @@ -135,6 +140,8 @@ function keyOf(target: ShareImportTarget): string { target.destination.environmentId, target.destination.projectId, target.shareId, + target.createdAt, + target.template ?? null, ]); } @@ -195,7 +202,7 @@ export function makeIncomingShareImports(deps: ShareImportDeps) { async function runImport(key: string, entry: Entry): Promise { const { signal } = entry.controller; - const { shareId, destination, draftKey } = entry.target; + const { shareId, destination, draftKey, template } = entry.target; // A phase atom node of a superseded import may still be cached; rebuilding // it lets a route that switches back start over instead of showing the // abandoned import's last phase. @@ -221,9 +228,10 @@ export function makeIncomingShareImports(deps: ShareImportDeps) { let skippedAttachmentCount: number; try { ({ skippedAttachmentCount } = await deps.mergeIntoDraft(draftKey, { - text: share.text, + text: template === undefined ? share.text : applyShareTemplate(template, share.text), attachments: selected.attachments, sourceShareId: shareId, + ...(share.schemaVersion === 2 ? { sourceShareCreatedAt: share.createdAt } : {}), })); } finally { // The merge publishes before it persists, so read it back even when diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c9d43d96b3eb8..7b78ee2743e85 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3630,6 +3630,13 @@ "ae4287de15deb58a": "Vergessen", "2595c662f9daa600": "{title} vergessen", "a71ffae963a09dca": "Einstellung auswählen", + "05adacd1d97ec306": "Diese Vorlage löschen?", + "42ea22546885274d": "Vorlagen zum Teilen", + "ef59f23642c83dd2": "Wenn du Inhalte aus einer anderen App mit T3 Code teilst, wähle eine Vorlage, um Anweisungen hinzuzufügen. Schreibe {placeholder} an die Stelle, an der der geteilte Text erscheinen soll. Andernfalls wird er am Ende angefügt.", + "725bd4ce416f19e0": "Vorlagen-Prompt", + "b7a9622856e507ab": "Prüfe dies auf Fehler:\n\n{placeholder}", + "118eaa88003fa0b9": "Vorlage löschen", + "bb280711a7596fe0": "Vorlage hinzufügen", "f0e853acd2006d53": "Verknüpfte Umgebungen", "0b83813eb16a9bc0": "Lass Agenten auf einem Rechner auf deinen anderen Rechnern arbeiten und deren Agenten auf ihm. Schalte es für jeden Rechner ein. Solange es aus ist, startet nichts Neues über eine Verknüpfung; laufende Aufgaben werden beendet.", "f9904f78d3003f58": "Schneller Worktree-Checkout", @@ -3807,6 +3814,8 @@ "4c2495d10dfbf72f": "warteschlange", "4ebe2aa17b91e168": "umlenken", "48f04bb3132077ef": "während der agent läuft", + "3ec7f55d1b9549d3": "Vorlagen zum Teilen", + "bff46ab745448b38": "Teilen-Menü", "ffb1ded95eb81974": "archivieren", "3d5aeb06f2128b12": "archiviert", "2a34f68d985e9fde": "wiederherstellen", @@ -3863,6 +3872,7 @@ "971906eaa531a64f": "Die Größe von ''{name}'' konnte nicht ermittelt werden.", "92f90005f30260fc": "Ein geteiltes Element war kein unterstütztes Bild.", "77c817a599cdd17d": "''{name}'' ist kein unterstützter Bildtyp.", + "341a91c8fbfb9617": "Vorlage", "4778160a14d1d87c": "Thread", "45ab2f1cbdc47569": "Terminal-Ausgabe wird angezeigt.", "704a962a4d7fde12": "Natives Terminal nicht verfügbar. Textansicht wird verwendet.", @@ -4122,7 +4132,10 @@ "a87c89c0fa9c11b1": "Warte, bis das Klonen des Projekts abgeschlossen ist.", "de06416f37a154f7": "Thread wird gestartet…", "885ac12ea424bf58": "Wähle einen Basis-Branch, bevor du einen Worktree erstellst.", + "49bd4f55da0e20eb": "Wähle eine Vorlage für die geteilten Inhalte.", "f271eabe60ef8527": "Warte, bis der Import der geteilten Inhalte abgeschlossen ist.", + "cfac6290b1366ce6": "Eine Vorlage für die geteilten Inhalte verwenden?", + "0efb0997a672a19f": "Keine Vorlage", "06b6bb85f2e34802": "Was sollen wir in {project} bauen?", "1cc924f00febd08c": "Öffnet die Projektauswahl", "79ca5bab2b8e2539": "Projekt: {project}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7a89a1cf37c22..7615c5fb77c57 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3631,6 +3631,13 @@ "ae4287de15deb58a": "Forget", "2595c662f9daa600": "Forget {title}", "a71ffae963a09dca": "Select a setting", + "05adacd1d97ec306": "Delete this template?", + "42ea22546885274d": "Share templates", + "ef59f23642c83dd2": "When you share to T3 Code from another app, choose a template to wrap what you shared. Write {placeholder} where the shared text goes, or it goes at the end.", + "725bd4ce416f19e0": "Template prompt", + "b7a9622856e507ab": "Review this for bugs:\n\n{placeholder}", + "118eaa88003fa0b9": "Delete template", + "bb280711a7596fe0": "Add template", "f0e853acd2006d53": "Linked environments", "0b83813eb16a9bc0": "Let agents on a machine work on your other machines, and theirs on it. Turn it on for each machine. While off, nothing new starts over a link; running tasks finish.", "f9904f78d3003f58": "Fast worktree checkout", @@ -3808,6 +3815,8 @@ "4c2495d10dfbf72f": "queue", "4ebe2aa17b91e168": "steer", "48f04bb3132077ef": "while the agent is running", + "3ec7f55d1b9549d3": "share templates", + "bff46ab745448b38": "share sheet", "ffb1ded95eb81974": "archive", "3d5aeb06f2128b12": "archived", "2a34f68d985e9fde": "restore", @@ -3864,6 +3873,7 @@ "971906eaa531a64f": "The size of ''{name}'' could not be determined.", "92f90005f30260fc": "One shared item was not a supported image.", "77c817a599cdd17d": "''{name}'' is not a supported image type.", + "341a91c8fbfb9617": "Template", "4778160a14d1d87c": "Thread", "45ab2f1cbdc47569": "Viewing terminal output.", "704a962a4d7fde12": "Native terminal unavailable. Using text fallback.", @@ -4123,7 +4133,10 @@ "a87c89c0fa9c11b1": "Wait for the project clone to finish.", "de06416f37a154f7": "Starting the thread…", "885ac12ea424bf58": "Choose a base branch before creating a worktree.", + "49bd4f55da0e20eb": "Choose a template for the shared content.", "f271eabe60ef8527": "Wait for shared content to finish importing.", + "cfac6290b1366ce6": "Use a template for the shared content?", + "0efb0997a672a19f": "No template", "06b6bb85f2e34802": "What should we build in {project}?", "1cc924f00febd08c": "Opens the project picker", "79ca5bab2b8e2539": "Project: {project}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 288dbfc7da2cf..2563ac8619a14 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3625,6 +3625,13 @@ "ae4287de15deb58a": "Olvidar", "2595c662f9daa600": "Olvidar {title}", "a71ffae963a09dca": "Selecciona un ajuste", + "05adacd1d97ec306": "¿Eliminar esta plantilla?", + "42ea22546885274d": "Plantillas para compartir", + "ef59f23642c83dd2": "Cuando compartas contenido con T3 Code desde otra aplicación, elige una plantilla para acompañarlo. Escribe {placeholder} donde deba ir el texto compartido; si no, se añadirá al final.", + "725bd4ce416f19e0": "Instrucciones de la plantilla", + "b7a9622856e507ab": "Revisa esto en busca de errores:\n\n{placeholder}", + "118eaa88003fa0b9": "Eliminar plantilla", + "bb280711a7596fe0": "Añadir plantilla", "f0e853acd2006d53": "Entornos vinculados", "0b83813eb16a9bc0": "Permite que los agentes de una máquina trabajen en tus otras máquinas, y los de ellas en esta. Actívalo en cada máquina. Mientras esté desactivado, no se inicia nada nuevo a través de un vínculo; las tareas en curso terminan.", "f9904f78d3003f58": "Checkout rápido de worktrees", @@ -3802,6 +3809,8 @@ "4c2495d10dfbf72f": "cola", "4ebe2aa17b91e168": "redirigir", "48f04bb3132077ef": "mientras el agente trabaja", + "3ec7f55d1b9549d3": "plantillas para compartir", + "bff46ab745448b38": "hoja para compartir", "ffb1ded95eb81974": "archivar", "3d5aeb06f2128b12": "archivados", "2a34f68d985e9fde": "restaurar", @@ -3858,6 +3867,7 @@ "971906eaa531a64f": "No se pudo determinar el tamaño de «{name}».", "92f90005f30260fc": "Un elemento compartido no era una imagen compatible.", "77c817a599cdd17d": "«{name}» no es un tipo de imagen compatible.", + "341a91c8fbfb9617": "Plantilla", "4778160a14d1d87c": "Hilo", "45ab2f1cbdc47569": "Viendo la salida de la terminal.", "704a962a4d7fde12": "La terminal nativa no está disponible. Se usa texto como alternativa.", @@ -4115,7 +4125,10 @@ "a87c89c0fa9c11b1": "Espera a que termine de clonarse el proyecto.", "de06416f37a154f7": "Iniciando el hilo…", "885ac12ea424bf58": "Elige una rama base antes de crear un worktree.", + "49bd4f55da0e20eb": "Elige una plantilla para el contenido compartido.", "f271eabe60ef8527": "Espera a que termine de importarse el contenido compartido.", + "cfac6290b1366ce6": "¿Usar una plantilla para el contenido compartido?", + "0efb0997a672a19f": "Sin plantilla", "06b6bb85f2e34802": "¿Qué construimos en {project}?", "1cc924f00febd08c": "Abre el selector de proyectos", "79ca5bab2b8e2539": "Proyecto: {project}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 28ec2284fca74..cda88a8ba9d87 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3625,6 +3625,13 @@ "ae4287de15deb58a": "Oublier", "2595c662f9daa600": "Oublier {title}", "a71ffae963a09dca": "Sélectionnez un paramètre", + "05adacd1d97ec306": "Supprimer ce modèle ?", + "42ea22546885274d": "Modèles de partage", + "ef59f23642c83dd2": "Lorsque vous partagez du contenu avec T3 Code depuis une autre application, choisissez un modèle pour y ajouter des instructions. Écrivez {placeholder} à l’endroit où le texte partagé doit apparaître ; sinon, il sera ajouté à la fin.", + "725bd4ce416f19e0": "Consigne du modèle", + "b7a9622856e507ab": "Recherche des bugs dans ce contenu :\n\n{placeholder}", + "118eaa88003fa0b9": "Supprimer le modèle", + "bb280711a7596fe0": "Ajouter un modèle", "f0e853acd2006d53": "Environnements associés", "0b83813eb16a9bc0": "Permet aux agents d’une machine de travailler sur vos autres machines, et aux leurs de travailler sur celle-ci. Activez l’option sur chaque machine. Tant qu’elle est désactivée, rien de nouveau ne démarre via une association ; les tâches en cours se terminent.", "f9904f78d3003f58": "Checkout rapide des worktrees", @@ -3802,6 +3809,8 @@ "4c2495d10dfbf72f": "file d’attente", "4ebe2aa17b91e168": "réorienter", "48f04bb3132077ef": "pendant que l’agent travaille", + "3ec7f55d1b9549d3": "modèles de partage", + "bff46ab745448b38": "feuille de partage", "ffb1ded95eb81974": "archiver", "3d5aeb06f2128b12": "archivés", "2a34f68d985e9fde": "restaurer", @@ -3858,6 +3867,7 @@ "971906eaa531a64f": "La taille de « {name} » n’a pas pu être déterminée.", "92f90005f30260fc": "Un élément partagé n’était pas une image prise en charge.", "77c817a599cdd17d": "« {name} » n’est pas un type d’image pris en charge.", + "341a91c8fbfb9617": "Modèle", "4778160a14d1d87c": "Fil", "45ab2f1cbdc47569": "Affichage de la sortie du terminal.", "704a962a4d7fde12": "Terminal natif indisponible. Utilisation de la version texte.", @@ -4116,7 +4126,10 @@ "a87c89c0fa9c11b1": "Attendez la fin du clonage du projet.", "de06416f37a154f7": "Démarrage du fil…", "885ac12ea424bf58": "Choisissez une branche de base avant de créer un worktree.", + "49bd4f55da0e20eb": "Choisissez un modèle pour le contenu partagé.", "f271eabe60ef8527": "Attendez la fin de l’import du contenu partagé.", + "cfac6290b1366ce6": "Utiliser un modèle pour le contenu partagé ?", + "0efb0997a672a19f": "Aucun modèle", "06b6bb85f2e34802": "Que devons-nous construire dans {project} ?", "1cc924f00febd08c": "Ouvre le sélecteur de projet", "79ca5bab2b8e2539": "Projet : {project}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f6741fdb8b775..6107ba2bf9b05 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3622,6 +3622,13 @@ "ae4287de15deb58a": "削除", "2595c662f9daa600": "{title} を削除", "a71ffae963a09dca": "設定を選択", + "05adacd1d97ec306": "このテンプレートを削除しますか?", + "42ea22546885274d": "共有テンプレート", + "ef59f23642c83dd2": "他のアプリから T3 Code に共有するときに、テンプレートを選んで指示を追加できます。共有テキストを挿入する位置に {placeholder} と入力してください。指定がない場合は末尾に追加されます。", + "725bd4ce416f19e0": "テンプレートのプロンプト", + "b7a9622856e507ab": "次の内容のバグを確認してください:\n\n{placeholder}", + "118eaa88003fa0b9": "テンプレートを削除", + "bb280711a7596fe0": "テンプレートを追加", "f0e853acd2006d53": "リンクされた環境", "0b83813eb16a9bc0": "マシン上のエージェントがあなたの他のマシンで作業し、他のマシンのエージェントがそのマシンで作業できるようにします。各マシンでオンにしてください。オフの間はリンク経由で新しい処理は開始されませんが、実行中のタスクは完了します。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", @@ -3799,6 +3806,8 @@ "4c2495d10dfbf72f": "キュー", "4ebe2aa17b91e168": "軌道修正", "48f04bb3132077ef": "エージェントの実行中", + "3ec7f55d1b9549d3": "共有テンプレート", + "bff46ab745448b38": "共有シート", "ffb1ded95eb81974": "アーカイブ", "3d5aeb06f2128b12": "アーカイブ済み", "2a34f68d985e9fde": "復元", @@ -3855,6 +3864,7 @@ "971906eaa531a64f": "''{name}'' のサイズを特定できませんでした。", "92f90005f30260fc": "共有された項目の 1 つは対応している画像ではありませんでした。", "77c817a599cdd17d": "''{name}'' は対応している画像形式ではありません。", + "341a91c8fbfb9617": "テンプレート", "4778160a14d1d87c": "スレッド", "45ab2f1cbdc47569": "ターミナルの出力を表示しています。", "704a962a4d7fde12": "ネイティブのターミナルを利用できません。テキスト表示で代替しています。", @@ -4109,7 +4119,10 @@ "a87c89c0fa9c11b1": "プロジェクトのクローンが完了するまでお待ちください。", "de06416f37a154f7": "スレッドを開始しています…", "885ac12ea424bf58": "ワークツリーを作成する前にベースブランチを選んでください。", + "49bd4f55da0e20eb": "共有コンテンツのテンプレートを選択してください。", "f271eabe60ef8527": "共有されたコンテンツのインポートが完了するまでお待ちください。", + "cfac6290b1366ce6": "共有コンテンツにテンプレートを使用しますか?", + "0efb0997a672a19f": "テンプレートなし", "06b6bb85f2e34802": "{project} で何を作りますか?", "1cc924f00febd08c": "プロジェクトの選択メニューを開きます", "79ca5bab2b8e2539": "プロジェクト: {project}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b1ef20ba0f347..577f68782cb29 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3626,6 +3626,13 @@ "ae4287de15deb58a": "삭제", "2595c662f9daa600": "{title} 삭제", "a71ffae963a09dca": "설정 선택", + "05adacd1d97ec306": "이 템플릿을 삭제할까요?", + "42ea22546885274d": "공유 템플릿", + "ef59f23642c83dd2": "다른 앱에서 T3 Code로 공유할 때 템플릿을 선택하여 지침을 추가할 수 있습니다. 공유한 텍스트가 들어갈 위치에 {placeholder}를 입력하세요. 지정하지 않으면 끝에 추가됩니다.", + "725bd4ce416f19e0": "템플릿 프롬프트", + "b7a9622856e507ab": "다음 내용에서 버그를 검토해 주세요:\n\n{placeholder}", + "118eaa88003fa0b9": "템플릿 삭제", + "bb280711a7596fe0": "템플릿 추가", "f0e853acd2006d53": "연결된 환경", "0b83813eb16a9bc0": "한 머신의 에이전트가 다른 머신에서, 다른 머신의 에이전트가 이 머신에서 작업하도록 허용합니다. 머신마다 켜세요. 꺼져 있으면 링크를 통해 새 작업이 시작되지 않으며, 실행 중인 작업은 끝까지 진행됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", @@ -3803,6 +3810,8 @@ "4c2495d10dfbf72f": "대기열", "4ebe2aa17b91e168": "방향 조정", "48f04bb3132077ef": "에이전트 실행 중", + "3ec7f55d1b9549d3": "공유 템플릿", + "bff46ab745448b38": "공유 시트", "ffb1ded95eb81974": "보관", "3d5aeb06f2128b12": "보관됨", "2a34f68d985e9fde": "복원", @@ -3859,6 +3868,7 @@ "971906eaa531a64f": "‘{name}’의 크기를 확인할 수 없습니다.", "92f90005f30260fc": "공유된 항목 하나가 지원되는 이미지가 아닙니다.", "77c817a599cdd17d": "‘{name}’은(는) 지원되지 않는 이미지 형식입니다.", + "341a91c8fbfb9617": "템플릿", "4778160a14d1d87c": "스레드", "45ab2f1cbdc47569": "터미널 출력을 보는 중입니다.", "704a962a4d7fde12": "네이티브 터미널을 사용할 수 없습니다. 텍스트 대체 모드를 사용합니다.", @@ -4113,7 +4123,10 @@ "a87c89c0fa9c11b1": "프로젝트 복제가 끝날 때까지 기다리세요.", "de06416f37a154f7": "스레드 시작 중…", "885ac12ea424bf58": "워크트리를 만들기 전에 기준 브랜치를 선택하세요.", + "49bd4f55da0e20eb": "공유한 콘텐츠에 사용할 템플릿을 선택하세요.", "f271eabe60ef8527": "공유된 콘텐츠 가져오기가 끝날 때까지 기다리세요.", + "cfac6290b1366ce6": "공유한 콘텐츠에 템플릿을 사용할까요?", + "0efb0997a672a19f": "템플릿 없음", "06b6bb85f2e34802": "{project}에서 무엇을 만들까요?", "1cc924f00febd08c": "프로젝트 선택기를 엽니다", "79ca5bab2b8e2539": "프로젝트: {project}", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b40494fca3885..810589494d479 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3625,6 +3625,13 @@ "ae4287de15deb58a": "Esquecer", "2595c662f9daa600": "Esquecer {title}", "a71ffae963a09dca": "Selecione uma configuração", + "05adacd1d97ec306": "Excluir este modelo?", + "42ea22546885274d": "Modelos de compartilhamento", + "ef59f23642c83dd2": "Ao compartilhar conteúdo com o T3 Code de outro aplicativo, escolha um modelo para incluir instruções. Escreva {placeholder} onde o texto compartilhado deve ficar; caso contrário, ele será adicionado ao final.", + "725bd4ce416f19e0": "Instruções do modelo", + "b7a9622856e507ab": "Revise isto em busca de erros:\n\n{placeholder}", + "118eaa88003fa0b9": "Excluir modelo", + "bb280711a7596fe0": "Adicionar modelo", "f0e853acd2006d53": "Ambientes vinculados", "0b83813eb16a9bc0": "Permite que os agentes de uma máquina trabalhem nas suas outras máquinas, e os delas nela. Ative em cada máquina. Enquanto desativado, nada novo começa por um vínculo; as tarefas em execução terminam.", "f9904f78d3003f58": "Checkout rápido de worktree", @@ -3802,6 +3809,8 @@ "4c2495d10dfbf72f": "fila", "4ebe2aa17b91e168": "direcionar", "48f04bb3132077ef": "enquanto o agente está em execução", + "3ec7f55d1b9549d3": "modelos de compartilhamento", + "bff46ab745448b38": "menu de compartilhamento", "ffb1ded95eb81974": "arquivar", "3d5aeb06f2128b12": "arquivadas", "2a34f68d985e9fde": "restaurar", @@ -3858,6 +3867,7 @@ "971906eaa531a64f": "Não foi possível determinar o tamanho de ''{name}''.", "92f90005f30260fc": "Um item compartilhado não era uma imagem compatível.", "77c817a599cdd17d": "''{name}'' não é um tipo de imagem compatível.", + "341a91c8fbfb9617": "Modelo", "4778160a14d1d87c": "Thread", "45ab2f1cbdc47569": "Exibindo a saída do terminal.", "704a962a4d7fde12": "Terminal nativo indisponível. Usando texto alternativo.", @@ -4116,7 +4126,10 @@ "a87c89c0fa9c11b1": "Aguarde a clonagem do projeto terminar.", "de06416f37a154f7": "Iniciando a thread…", "885ac12ea424bf58": "Escolha um branch base antes de criar um worktree.", + "49bd4f55da0e20eb": "Escolha um modelo para o conteúdo compartilhado.", "f271eabe60ef8527": "Aguarde o conteúdo compartilhado terminar de ser importado.", + "cfac6290b1366ce6": "Usar um modelo para o conteúdo compartilhado?", + "0efb0997a672a19f": "Sem modelo", "06b6bb85f2e34802": "O que vamos construir em {project}?", "1cc924f00febd08c": "Abre o seletor de projetos", "79ca5bab2b8e2539": "Projeto: {project}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index cadf07e57eda9..a26063df29334 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -3679,6 +3679,13 @@ "ae4287de15deb58a": "Забыть", "2595c662f9daa600": "Забыть {title}", "a71ffae963a09dca": "Выберите настройку", + "05adacd1d97ec306": "Удалить этот шаблон?", + "42ea22546885274d": "Шаблоны для отправки", + "ef59f23642c83dd2": "Когда вы отправляете содержимое в T3 Code из другого приложения, выберите шаблон, чтобы добавить инструкции. Напишите {placeholder} там, где должен появиться отправленный текст. Иначе он будет добавлен в конец.", + "725bd4ce416f19e0": "Запрос шаблона", + "b7a9622856e507ab": "Проверь это на ошибки:\n\n{placeholder}", + "118eaa88003fa0b9": "Удалить шаблон", + "bb280711a7596fe0": "Добавить шаблон", "f0e853acd2006d53": "Привязанные окружения", "0b83813eb16a9bc0": "Позвольте агентам на машине работать на ваших других машинах, а их агентам — на ней. Включите это на каждой машине. Пока выключено, по привязке ничего нового не запускается; запущенные задачи завершатся.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", @@ -3856,6 +3863,8 @@ "4c2495d10dfbf72f": "очередь", "4ebe2aa17b91e168": "корректировка", "48f04bb3132077ef": "пока агент работает", + "3ec7f55d1b9549d3": "шаблоны для отправки", + "bff46ab745448b38": "меню отправки", "ffb1ded95eb81974": "архивировать", "3d5aeb06f2128b12": "в архиве", "2a34f68d985e9fde": "восстановить", @@ -3912,6 +3921,7 @@ "971906eaa531a64f": "Не удалось определить размер «{name}».", "92f90005f30260fc": "Один из элементов не является поддерживаемым изображением.", "77c817a599cdd17d": "«{name}» — неподдерживаемый тип изображения.", + "341a91c8fbfb9617": "Шаблон", "4778160a14d1d87c": "Тред", "45ab2f1cbdc47569": "Просмотр вывода терминала.", "704a962a4d7fde12": "Нативный терминал недоступен. Используется текстовый режим.", @@ -4170,7 +4180,10 @@ "a87c89c0fa9c11b1": "Дождитесь окончания клонирования проекта.", "de06416f37a154f7": "Запуск треда…", "885ac12ea424bf58": "Выберите базовую ветку перед созданием рабочего дерева.", + "49bd4f55da0e20eb": "Выберите шаблон для отправленного содержимого.", "f271eabe60ef8527": "Дождитесь окончания импорта общего контента.", + "cfac6290b1366ce6": "Использовать шаблон для отправленного содержимого?", + "0efb0997a672a19f": "Без шаблона", "06b6bb85f2e34802": "Что будем создавать в {project}?", "1cc924f00febd08c": "Открывает выбор проекта", "79ca5bab2b8e2539": "Проект: {project}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3a0273aef36fd..81411dfe45945 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3631,6 +3631,13 @@ "ae4287de15deb58a": "Glöm", "2595c662f9daa600": "Glöm {title}", "a71ffae963a09dca": "Välj en inställning", + "05adacd1d97ec306": "Radera den här mallen?", + "42ea22546885274d": "Delningsmallar", + "ef59f23642c83dd2": "När du delar innehåll till T3 Code från en annan app väljer du en mall för att lägga till instruktioner. Skriv {placeholder} där den delade texten ska placeras, annars läggs den till i slutet.", + "725bd4ce416f19e0": "Mallens prompt", + "b7a9622856e507ab": "Granska detta efter buggar:\n\n{placeholder}", + "118eaa88003fa0b9": "Radera mall", + "bb280711a7596fe0": "Lägg till mall", "f0e853acd2006d53": "Länkade miljöer", "0b83813eb16a9bc0": "Låt agenter på en dator arbeta på dina andra datorer, och deras på den. Aktivera det på varje dator. När det är av startar inget nytt via en länk; pågående uppgifter slutförs.", "f9904f78d3003f58": "Snabb utcheckning av worktree", @@ -3808,6 +3815,8 @@ "4c2495d10dfbf72f": "köa", "4ebe2aa17b91e168": "styr om", "48f04bb3132077ef": "medan agenten körs", + "3ec7f55d1b9549d3": "delningsmallar", + "bff46ab745448b38": "delningsmeny", "ffb1ded95eb81974": "arkivera", "3d5aeb06f2128b12": "arkiverade", "2a34f68d985e9fde": "återställ", @@ -3864,6 +3873,7 @@ "971906eaa531a64f": "Storleken på ''{name}'' kunde inte fastställas.", "92f90005f30260fc": "Ett delat objekt var inte en bild som stöds.", "77c817a599cdd17d": "''{name}'' är inte en bildtyp som stöds.", + "341a91c8fbfb9617": "Mall", "4778160a14d1d87c": "Tråd", "45ab2f1cbdc47569": "Visar terminalutdata.", "704a962a4d7fde12": "Den inbyggda terminalen är inte tillgänglig. Använder textreserv.", @@ -4122,7 +4132,10 @@ "a87c89c0fa9c11b1": "Vänta tills kloningen av projektet är klar.", "de06416f37a154f7": "Startar tråden…", "885ac12ea424bf58": "Välj en basgren innan du skapar en worktree.", + "49bd4f55da0e20eb": "Välj en mall för det delade innehållet.", "f271eabe60ef8527": "Vänta tills det delade innehållet har importerats.", + "cfac6290b1366ce6": "Använd en mall för det delade innehållet?", + "0efb0997a672a19f": "Ingen mall", "06b6bb85f2e34802": "Vad ska vi bygga i {project}?", "1cc924f00febd08c": "Öppnar projektväljaren", "79ca5bab2b8e2539": "Projekt: {project}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f1c394c60c606..c2935ea3617e6 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3627,6 +3627,13 @@ "ae4287de15deb58a": "移除", "2595c662f9daa600": "忘记 {title}", "a71ffae963a09dca": "选择一项设置", + "05adacd1d97ec306": "删除此模板?", + "42ea22546885274d": "分享模板", + "ef59f23642c83dd2": "从其他应用分享到 T3 Code 时,选择一个模板来添加说明。在需要插入分享文本的位置写入 {placeholder};否则,文本会添加到末尾。", + "725bd4ce416f19e0": "模板提示词", + "b7a9622856e507ab": "检查以下内容中的错误:\n\n{placeholder}", + "118eaa88003fa0b9": "删除模板", + "bb280711a7596fe0": "添加模板", "f0e853acd2006d53": "关联环境", "0b83813eb16a9bc0": "让一台机器上的智能体在你的其他机器上工作,也让其他机器的智能体在它上面工作。请在每台机器上开启此功能。关闭时,不会通过关联启动新任务;正在运行的任务会继续完成。", "f9904f78d3003f58": "快速创建工作树", @@ -3804,6 +3811,8 @@ "4c2495d10dfbf72f": "加入队列", "4ebe2aa17b91e168": "引导当前执行", "48f04bb3132077ef": "智能体运行时", + "3ec7f55d1b9549d3": "分享模板", + "bff46ab745448b38": "分享面板", "ffb1ded95eb81974": "归档", "3d5aeb06f2128b12": "已归档", "2a34f68d985e9fde": "恢复", @@ -3860,6 +3869,7 @@ "971906eaa531a64f": "无法确定“{name}”的大小。", "92f90005f30260fc": "有一个共享项不是受支持的图片。", "77c817a599cdd17d": "“{name}”不是受支持的图片类型。", + "341a91c8fbfb9617": "模板", "4778160a14d1d87c": "会话", "45ab2f1cbdc47569": "正在查看终端输出。", "704a962a4d7fde12": "原生终端不可用。正在使用文本回退模式。", @@ -4117,7 +4127,10 @@ "a87c89c0fa9c11b1": "请等待项目克隆完成。", "de06416f37a154f7": "正在启动会话…", "885ac12ea424bf58": "创建工作树前请先选择基础分支。", + "49bd4f55da0e20eb": "为分享的内容选择一个模板。", "f271eabe60ef8527": "请等待共享内容导入完成。", + "cfac6290b1366ce6": "为分享的内容使用模板?", + "0efb0997a672a19f": "不使用模板", "06b6bb85f2e34802": "要在 {project} 中构建什么?", "1cc924f00febd08c": "打开项目选择器", "79ca5bab2b8e2539": "项目:{project}", diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 71d095b0b4fb5..a2e0053055797 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -24,6 +24,7 @@ import type { ComposerEnterBehavior } from "../lib/composerEnterBehavior"; import type { FollowUpBehavior } from "../lib/followUpBehavior"; import { isMicrophoneKind, type MicrophoneEntry } from "../lib/microphonePriority"; import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme"; +import type { ShareTemplate } from "../features/sharing/share-templates"; import * as MobileDatabase from "./mobile-database"; import * as MobileSecureStorage from "./mobile-secure-storage"; import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage"; @@ -165,6 +166,7 @@ export interface Preferences { /** The client `language` setting: a locale code or "system". Unset means English. */ readonly language?: string; readonly microphones?: ReadonlyArray; + readonly shareTemplates?: ReadonlyArray; readonly projectGroupingEnabled?: boolean; readonly projectGroupingMode?: SidebarProjectGroupingMode; readonly toolCallVisibility?: ToolCallVisibility; @@ -255,6 +257,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { followUpBehavior?: FollowUpBehavior; language?: string; microphones?: ReadonlyArray; + shareTemplates?: ReadonlyArray; projectGroupingEnabled?: boolean; projectGroupingMode?: SidebarProjectGroupingMode; toolCallVisibility?: ToolCallVisibility; @@ -378,6 +381,16 @@ function sanitizePreferences(parsed: Preferences): Preferences { : []; }); } + if (Array.isArray(parsed.shareTemplates)) { + preferences.shareTemplates = parsed.shareTemplates.flatMap((entry): ShareTemplate[] => + typeof entry === "object" && + entry !== null && + typeof entry.id === "string" && + typeof entry.prompt === "string" + ? [{ id: entry.id, prompt: entry.prompt }] + : [], + ); + } if (typeof parsed.projectGroupingEnabled === "boolean") { preferences.projectGroupingEnabled = parsed.projectGroupingEnabled; } diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 0f0e4a69419fb..0f1b0f471ee39 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -2363,6 +2363,7 @@ describe("mobile composer drafts", () => { it("lets a shared file through the send check", async () => { const { attachments } = await buildIncomingShareDraft({ + attachmentIdPrefix: "share-1", id: "share-1", createdAt: "2026-07-15T10:00:00.000Z", payloads: [ diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 57b620de5264b..a6082a7c414b6 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -465,6 +465,7 @@ export interface ComposerDraftContent { readonly context?: OrchestrationMessageContext; readonly attachments: ReadonlyArray; readonly sourceShareId?: string; + readonly sourceShareCreatedAt?: string; } export interface ComposerDraftWorkspaceSelection { @@ -1791,7 +1792,12 @@ export function mergeComposerDraftContentState( content: ComposerDraftContent, ): Record { const existing = normalizeDraft(current[draftKey]); - if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) { + const receipt = + content.sourceShareId && + (content.sourceShareCreatedAt + ? JSON.stringify([content.sourceShareId, content.sourceShareCreatedAt]) + : content.sourceShareId); + if (receipt && existing.importedShareIds?.includes(receipt)) { return current; } const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id)); @@ -1808,9 +1814,11 @@ export function mergeComposerDraftContentState( ); const text = mergeComposerDraftText(existing.text, content.text); const context = mergeReferencedComposerContext(text, existing.context, content.context); - const importedShareIds = content.sourceShareId - ? [...(existing.importedShareIds ?? []), content.sourceShareId] - : existing.importedShareIds; + // Retain the content id for restored routes; the handoff receipt guards duplicate merges. + const importedShareIds = + content.sourceShareId && receipt + ? [...new Set([...(existing.importedShareIds ?? []), content.sourceShareId, receipt])] + : existing.importedShareIds; if ( text === existing.text && attachments.length === existing.attachments.length && diff --git a/docs/user/composer.md b/docs/user/composer.md index 89a96f120d4d0..ca2caedcefefd 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -58,6 +58,12 @@ also send files to T3 Code through another app's system share sheet. On Android, you can also drag images from another app into the message input in split screen. +To wrap shared text and links in a prompt you reuse, add a template in +**Settings → Chat → Share templates** on mobile. Write `{{shared}}` where the +shared text goes; otherwise it goes after the template. When you have templates, +a new share asks which one to use before it fills the draft. Shared files still +attach. + See [images and videos](#images-and-videos-in-messages) for previewing and saving media. ## Send while the agent is working