Skip to content

Commit 4702514

Browse files
feat(web,mobile): the move card can link a machine and move there
Besides the linked machines, the card offers machines this client is connected to that the thread's environment has no link to yet, where the client's session may create one. Picking one asks what agents here may do there; "Link and move" then creates the code there, links the two and moves the thread. The choice starts on the agent's suggestion and is blank without one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent c184516 commit 4702514

23 files changed

Lines changed: 336 additions & 38 deletions

File tree

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

Lines changed: 133 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
import {
2+
HANDOFF_LINK_DEFAULT_ACCESS,
3+
handoffLinkCandidates,
24
handoffRequestDisplay,
35
type HandoffRequestItem,
6+
handoffRequestTarget,
47
} from "@t3tools/client-runtime/handoff-request";
5-
import { defaultHandoffTarget } from "@t3tools/client-runtime/state/peerLinks";
8+
import {
9+
linkRequestFailureMessage,
10+
type LinkableMachine,
11+
} from "@t3tools/client-runtime/link-request";
612
import {
713
isAtomCommandInterrupted,
814
squashAtomCommandFailure,
915
} from "@t3tools/client-runtime/state/runtime";
10-
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
16+
import {
17+
AuthAccessWriteScope,
18+
type AuthMcpClientAccess,
19+
type EnvironmentId,
20+
type OrchestrationV2ProjectedTurnItem,
21+
} from "@t3tools/contracts";
22+
import * as Result from "effect/Result";
1123
import { T, msg, useGT, useMessages } from "gt-react-native";
1224
import { useRef, useState } from "react";
1325
import { View, type ColorValue } from "react-native";
@@ -18,10 +30,14 @@ import { Button } from "../../components/ui/Button";
1830
import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
1931
import { scopedThreadKey } from "../../lib/scopedEntities";
2032
import { SettingsSection } from "../settings/components/SettingsSection";
33+
import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
34+
import { mintPairingCodeOn } from "../../state/peerPairingCode";
2135
import { useEnvironmentQuery } from "../../state/query";
36+
import { useEnvironmentScope } from "../../state/session";
2237
import { threadHandoffEnvironment, useCanMoveThreads } from "../../state/threadHandoff";
2338
import { useAtomCommand } from "../../state/use-atom-command";
2439
import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
40+
import { LINK_ACCESS_CHOICES } from "./LinkRequestCard";
2541

2642
const TITLE = msg("Move this thread");
2743
const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
@@ -56,6 +72,7 @@ function PendingHandoffRequest(props: {
5672
readonly item: HandoffRequestItem;
5773
}) {
5874
const gt = useGT();
75+
const m = useMessages();
5976
const { item } = props;
6077
const canMove = useCanMoveThreads(props.environmentId);
6178
const targets = useEnvironmentQuery(
@@ -66,7 +83,13 @@ function PendingHandoffRequest(props: {
6683
);
6784
const start = useAtomCommand(threadHandoffEnvironment.start, { reportFailure: false });
6885
const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
86+
const link = useAtomCommand(peerLinkEnvironment.link, {
87+
// The failure cause holds the request, and with it the code; keep it out of the logs.
88+
reportFailure: false,
89+
reportDefect: false,
90+
});
6991
const [picked, setPicked] = useState<EnvironmentId | null>(null);
92+
const [access, setAccess] = useState<AuthMcpClientAccess>(HANDOFF_LINK_DEFAULT_ACCESS);
7093
const [busy, setBusy] = useState<"move" | "decline" | null>(null);
7194
const [error, setError] = useState<string | null>(null);
7295
// Two taps can land before a re-render; this guard is synchronous.
@@ -76,7 +99,23 @@ function PendingHandoffRequest(props: {
7699
scopedThreadKey(props.environmentId, item.threadId),
77100
);
78101
const options = targets.data?.options ?? [];
79-
const chosen = defaultHandoffTarget(options, picked ?? item.environmentId);
102+
// Machines this client is connected to that the thread's environment has no link to yet.
103+
const linkable = handoffLinkCandidates(useLinkableMachines(props.environmentId, true)).filter(
104+
(machine) => !options.some((option) => option.environmentId === machine.environmentId),
105+
);
106+
const pickedLinkable = linkable.find((machine) => machine.environmentId === picked);
107+
// This device creates the link's code there, which its session must be allowed to.
108+
const mayLink = useEnvironmentScope(pickedLinkable?.environmentId ?? null, AuthAccessWriteScope);
109+
const toLink = mayLink ? pickedLinkable : undefined;
110+
const chosen =
111+
pickedLinkable === undefined
112+
? handoffRequestTarget(options, picked ?? item.environmentId)
113+
: undefined;
114+
const move = (environmentId: EnvironmentId) =>
115+
start({
116+
environmentId: props.environmentId,
117+
input: { threadId: item.threadId, environmentId, turnItemId: item.id },
118+
});
80119

81120
const answer = async (
82121
key: "move" | "decline",
@@ -95,6 +134,44 @@ function PendingHandoffRequest(props: {
95134
setError(failure instanceof Error ? failure.message : gt("The thread could not be moved."));
96135
};
97136

137+
/** Links the thread's environment to `machine`; resolves to what went wrong, or null. */
138+
const linkTo = async (machine: LinkableMachine): Promise<unknown> => {
139+
const [url, ...alternateUrls] = machine.urls;
140+
if (url === undefined) return "interrupted";
141+
const code = await mintPairingCodeOn(machine.environmentId, access);
142+
if (Result.isFailure(code)) return code.failure;
143+
const linked = await link({
144+
environmentId: props.environmentId,
145+
input: {
146+
url,
147+
...(alternateUrls.length === 0 ? {} : { alternateUrls }),
148+
pairingCode: code.success,
149+
access,
150+
expectedEnvironmentId: machine.environmentId,
151+
expectedLabel: machine.label,
152+
},
153+
});
154+
if (linked._tag !== "Failure") return null;
155+
return isAtomCommandInterrupted(linked) ? "interrupted" : squashAtomCommandFailure(linked);
156+
};
157+
158+
/** Links to a machine this client is connected to, then moves the thread there. */
159+
const linkAndMove = async (machine: LinkableMachine) => {
160+
if (inFlight.current) return;
161+
inFlight.current = true;
162+
setBusy("move");
163+
setError(null);
164+
const failure = await linkTo(machine);
165+
inFlight.current = false;
166+
setBusy(null);
167+
if (failure !== null) {
168+
if (failure !== "interrupted") setError(linkRequestFailureMessage(failure, m));
169+
return;
170+
}
171+
targets.refresh();
172+
await answer("move", () => move(machine.environmentId));
173+
};
174+
98175
return (
99176
<View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
100177
<View className="gap-1">
@@ -106,7 +183,7 @@ function PendingHandoffRequest(props: {
106183
? gt("A message is still waiting to send from this device. Send or discard it first.")
107184
: targets.data === null
108185
? (targets.error ?? gt("Asking linked machines…"))
109-
: options.length === 0
186+
: options.length === 0 && linkable.length === 0
110187
? gt("This machine has no linked machines.")
111188
: gt(
112189
"It moves with its conversation and its code, uncommitted changes included. This copy becomes read-only.",
@@ -122,7 +199,7 @@ function PendingHandoffRequest(props: {
122199
<T>Only someone who can run agents on this machine can move it or decline.</T>
123200
</Text>
124201
) : null}
125-
{options.length > 0 ? (
202+
{options.length > 0 || linkable.length > 0 ? (
126203
<SettingsSection title={gt("Machine")}>
127204
{options.map((option, index) => (
128205
<ListChoiceRow
@@ -135,26 +212,64 @@ function PendingHandoffRequest(props: {
135212
onPress={() => setPicked(option.environmentId)}
136213
/>
137214
))}
215+
{linkable.map((machine, index) => (
216+
<ListChoiceRow
217+
key={machine.environmentId}
218+
label={machine.label}
219+
description={gt("Not linked yet")}
220+
selected={pickedLinkable?.environmentId === machine.environmentId}
221+
separated={options.length + index > 0}
222+
disabled={busy !== null || !canMove}
223+
onPress={() => setPicked(machine.environmentId)}
224+
/>
225+
))}
138226
</SettingsSection>
139227
) : null}
228+
{pickedLinkable !== undefined && !mayLink ? (
229+
<Text className="font-sans text-xs text-foreground-muted">
230+
{gt(
231+
"This device may not create a link on {machine}. Link it from Settings on a device that can.",
232+
{ machine: pickedLinkable.label },
233+
)}
234+
</Text>
235+
) : null}
236+
{toLink !== undefined ? (
237+
<>
238+
<Text className="font-sans text-xs text-foreground-muted">
239+
{gt(
240+
"This machine is not linked to {machine} yet. Moving the thread links them first, with a code this device creates there. Choose what agents here may do there.",
241+
{ machine: toLink.label },
242+
)}
243+
</Text>
244+
<SettingsSection title={gt("What agents here may do there")}>
245+
{LINK_ACCESS_CHOICES.map((choice, index) => (
246+
<ListChoiceRow
247+
key={choice.access}
248+
label={m(choice.label)}
249+
description={m(choice.description)}
250+
selected={choice.access === access}
251+
separated={index > 0}
252+
disabled={busy !== null}
253+
onPress={() => setAccess(choice.access)}
254+
/>
255+
))}
256+
</SettingsSection>
257+
</>
258+
) : null}
140259
<Button
141-
label={gt("Move")}
260+
label={toLink === undefined ? gt("Move") : gt("Link and move")}
142261
tone="primary"
143262
fullWidth
144263
loading={busy === "move"}
145-
disabled={busy !== null || outboxWaiting || !canMove || chosen === undefined}
264+
disabled={
265+
busy !== null ||
266+
outboxWaiting ||
267+
!canMove ||
268+
(chosen === undefined && toLink === undefined)
269+
}
146270
onPress={() => {
147-
if (chosen === undefined) return;
148-
void answer("move", () =>
149-
start({
150-
environmentId: props.environmentId,
151-
input: {
152-
threadId: item.threadId,
153-
environmentId: chosen.environmentId,
154-
turnItemId: item.id,
155-
},
156-
}),
157-
);
271+
if (toLink !== undefined) void linkAndMove(toLink);
272+
else if (chosen !== undefined) void answer("move", () => move(chosen.environmentId));
158273
}}
159274
/>
160275
<Button

‎apps/mobile/src/i18n/translations/de.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4767,6 +4767,10 @@
47674767
"7417d72c5c18c78f": "Verschieben nach {machine} fehlgeschlagen",
47684768
"b3da0064b6c4d977": "Wenn du eine Nachricht sendest, bleibt er stattdessen hier.",
47694769
"6de54bd779ddbea2": "Diese Kopie ist schreibgeschützt.",
4770+
"44c60318d5f90913": "Noch nicht verknüpft",
4771+
"63b5ce60561d68ac": "Dieses Gerät darf auf {machine} keine Verknüpfung erstellen. Verknüpfe den Rechner in den Einstellungen auf einem Gerät, das das darf.",
4772+
"8a86ede7e9633733": "Dieser Rechner ist noch nicht mit {machine} verknüpft. Beim Verschieben werden beide zuerst verknüpft, mit einem Code, den dieses Gerät dort erstellt. Wähle, was Agenten von hier dort tun dürfen.",
4773+
"e4e02a383f25eee8": "Verknüpfen und verschieben",
47704774
"9f122f4c410241c0": "Verschieben",
47714775
"26aeccb614ec69f1": "Angenommen",
47724776
"71b73be0c5a65a98": "Für {machine} angenommen",

‎apps/mobile/src/i18n/translations/en.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4769,6 +4769,10 @@
47694769
"7417d72c5c18c78f": "Could not move to {machine}",
47704770
"b3da0064b6c4d977": "Sending a message keeps it here instead.",
47714771
"6de54bd779ddbea2": "This copy is read-only.",
4772+
"44c60318d5f90913": "Not linked yet",
4773+
"63b5ce60561d68ac": "This device may not create a link on {machine}. Link it from Settings on a device that can.",
4774+
"8a86ede7e9633733": "This machine is not linked to {machine} yet. Moving the thread links them first, with a code this device creates there. Choose what agents here may do there.",
4775+
"e4e02a383f25eee8": "Link and move",
47724776
"9f122f4c410241c0": "Move",
47734777
"26aeccb614ec69f1": "Accepted",
47744778
"71b73be0c5a65a98": "Accepted for {machine}",

‎apps/mobile/src/i18n/translations/es.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4760,6 +4760,10 @@
47604760
"7417d72c5c18c78f": "No se pudo mover a {machine}",
47614761
"b3da0064b6c4d977": "Si envías un mensaje, se queda aquí.",
47624762
"6de54bd779ddbea2": "Esta copia es de solo lectura.",
4763+
"44c60318d5f90913": "Aún sin vincular",
4764+
"63b5ce60561d68ac": "Este dispositivo no puede crear un vínculo en {machine}. Vincúlala desde Ajustes en un dispositivo que pueda.",
4765+
"8a86ede7e9633733": "Esta máquina aún no está vinculada a {machine}. Al mover el hilo, primero se vinculan con un código que este dispositivo crea allí. Elige qué pueden hacer allí los agentes de aquí.",
4766+
"e4e02a383f25eee8": "Vincular y mover",
47634767
"9f122f4c410241c0": "Mover",
47644768
"26aeccb614ec69f1": "Aceptado",
47654769
"71b73be0c5a65a98": "Aceptado para {machine}",

‎apps/mobile/src/i18n/translations/fr.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4761,6 +4761,10 @@
47614761
"7417d72c5c18c78f": "Impossible de déplacer vers {machine}",
47624762
"b3da0064b6c4d977": "Envoyer un message le garde ici.",
47634763
"6de54bd779ddbea2": "Cette copie est en lecture seule.",
4764+
"44c60318d5f90913": "Pas encore liée",
4765+
"63b5ce60561d68ac": "Cet appareil ne peut pas créer de lien sur {machine}. Liez-la depuis les Réglages sur un appareil autorisé.",
4766+
"8a86ede7e9633733": "Cette machine n’est pas encore liée à {machine}. Le déplacement du fil les lie d’abord, avec un code que cet appareil crée là-bas. Choisissez ce que les agents d’ici peuvent y faire.",
4767+
"e4e02a383f25eee8": "Lier et déplacer",
47644768
"9f122f4c410241c0": "Déplacer",
47654769
"26aeccb614ec69f1": "Accepté",
47664770
"71b73be0c5a65a98": "Accepté pour {machine}",

‎apps/mobile/src/i18n/translations/ja.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4740,6 +4740,10 @@
47404740
"7417d72c5c18c78f": "{machine} に移動できませんでした",
47414741
"b3da0064b6c4d977": "メッセージを送信すると、ここに残ります。",
47424742
"6de54bd779ddbea2": "このコピーは読み取り専用です。",
4743+
"44c60318d5f90913": "未リンク",
4744+
"63b5ce60561d68ac": "このデバイスは {machine} でリンクを作成できません。作成できるデバイスの設定からリンクしてください。",
4745+
"8a86ede7e9633733": "このマシンはまだ {machine} にリンクされていません。スレッドを移動すると、このデバイスが向こうで作成するコードを使って先にリンクします。こちらのエージェントが向こうでできることを選んでください。",
4746+
"e4e02a383f25eee8": "リンクして移動",
47434747
"9f122f4c410241c0": "移動",
47444748
"26aeccb614ec69f1": "承認済み",
47454749
"71b73be0c5a65a98": "{machine} への移動を承認",

‎apps/mobile/src/i18n/translations/ko.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4745,6 +4745,10 @@
47454745
"7417d72c5c18c78f": "{machine}(으)로 이동할 수 없습니다",
47464746
"b3da0064b6c4d977": "메시지를 보내면 여기에 그대로 남습니다.",
47474747
"6de54bd779ddbea2": "이 사본은 읽기 전용입니다.",
4748+
"44c60318d5f90913": "아직 연결되지 않음",
4749+
"63b5ce60561d68ac": "이 기기는 {machine}에서 연결을 만들 수 없습니다. 만들 수 있는 기기의 설정에서 연결하세요.",
4750+
"8a86ede7e9633733": "이 머신은 아직 {machine}에 연결되어 있지 않습니다. 스레드를 옮기면 이 기기가 그쪽에서 만든 코드로 먼저 연결합니다. 이쪽 에이전트가 그쪽에서 할 수 있는 일을 선택하세요.",
4751+
"e4e02a383f25eee8": "연결하고 이동",
47484752
"9f122f4c410241c0": "이동",
47494753
"26aeccb614ec69f1": "수락됨",
47504754
"71b73be0c5a65a98": "{machine}(으)로 이동 수락됨",

‎apps/mobile/src/i18n/translations/pt-BR.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4761,6 +4761,10 @@
47614761
"7417d72c5c18c78f": "Não foi possível mover para {machine}",
47624762
"b3da0064b6c4d977": "Enviar uma mensagem a mantém aqui.",
47634763
"6de54bd779ddbea2": "Esta cópia é somente leitura.",
4764+
"44c60318d5f90913": "Ainda não vinculada",
4765+
"63b5ce60561d68ac": "Este dispositivo não pode criar um vínculo em {machine}. Vincule-a nas Configurações em um dispositivo que possa.",
4766+
"8a86ede7e9633733": "Esta máquina ainda não está vinculada a {machine}. Ao mover a conversa, elas são vinculadas primeiro, com um código que este dispositivo cria lá. Escolha o que os agentes daqui podem fazer lá.",
4767+
"e4e02a383f25eee8": "Vincular e mover",
47644768
"9f122f4c410241c0": "Mover",
47654769
"26aeccb614ec69f1": "Aceito",
47664770
"71b73be0c5a65a98": "Aceito para {machine}",

‎apps/mobile/src/i18n/translations/ru.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4839,6 +4839,10 @@
48394839
"7417d72c5c18c78f": "Не удалось перенести на {machine}",
48404840
"b3da0064b6c4d977": "Если отправить сообщение, он останется здесь.",
48414841
"6de54bd779ddbea2": "Эта копия доступна только для чтения.",
4842+
"44c60318d5f90913": "Ещё не связана",
4843+
"63b5ce60561d68ac": "Это устройство не может создать связь на {machine}. Свяжите её в настройках на устройстве, которому это разрешено.",
4844+
"8a86ede7e9633733": "Эта машина ещё не связана с {machine}. При переносе треда они сначала связываются с помощью кода, который это устройство создаёт там. Выберите, что агентам отсюда разрешено делать там.",
4845+
"e4e02a383f25eee8": "Связать и перенести",
48424846
"9f122f4c410241c0": "Переместить",
48434847
"26aeccb614ec69f1": "Принято",
48444848
"71b73be0c5a65a98": "Принято для {machine}",

‎apps/mobile/src/i18n/translations/sv.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4767,6 +4767,10 @@
47674767
"7417d72c5c18c78f": "Det gick inte att flytta till {machine}",
47684768
"b3da0064b6c4d977": "Om du skickar ett meddelande stannar den här i stället.",
47694769
"6de54bd779ddbea2": "Den här kopian är skrivskyddad.",
4770+
"44c60318d5f90913": "Inte länkad än",
4771+
"63b5ce60561d68ac": "Den här enheten får inte skapa en länk på {machine}. Länka den från Inställningar på en enhet som får.",
4772+
"8a86ede7e9633733": "Den här maskinen är inte länkad till {machine} än. När tråden flyttas länkas de först, med en kod som den här enheten skapar där. Välj vad agenter här får göra där.",
4773+
"e4e02a383f25eee8": "Länka och flytta",
47704774
"9f122f4c410241c0": "Flytta",
47714775
"26aeccb614ec69f1": "Godkänd",
47724776
"71b73be0c5a65a98": "Godkänd för {machine}",

0 commit comments

Comments
 (0)