diff --git a/apps/mobile/src/features/threads/ThreadHeader.tsx b/apps/mobile/src/features/threads/ThreadHeader.tsx index d85956dabbc18..4346f79f209bc 100644 --- a/apps/mobile/src/features/threads/ThreadHeader.tsx +++ b/apps/mobile/src/features/threads/ThreadHeader.tsx @@ -23,6 +23,8 @@ export function ThreadHeader(props: { readonly hasThreadCwd: boolean; readonly inspectorMode: ThreadInspectorMode | null; readonly onOpenFilesInspector: () => void; + /** Present only on a delegated child the user may pop out. */ + readonly onPopOut?: () => void; }) { const gt = useGT(); const m = useMessages(); @@ -44,6 +46,16 @@ export function ThreadHeader(props: { }, ] : []; + if (props.onPopOut) { + actions.push({ + accessibilityLabel: gt("Pop out to top level"), + icon: "arrow.up.right.circle", + subtitle: gt("Make it an ordinary thread"), + overflowOnly: true, + separateBackground: false, + onPress: props.onPopOut, + }); + } const menus = [gitMenu, terminalMenu].filter((menu): menu is AppBarMenu => menu !== null); return ( diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 8f111fc2c69c8..6007cf61a40c3 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -95,7 +95,10 @@ import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-s import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { useThreadComposerState } from "../../state/use-thread-composer-state"; -import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships"; +import { + resolveMergeBackTargetThreadId, + threadPopOutAvailability, +} from "@t3tools/client-runtime/state/thread-relationships"; import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows"; import { threadEnvironment } from "../../state/threads"; import { @@ -466,6 +469,45 @@ function ThreadRouteContent( const navigation = useNavigation(); const selectDetail = useSelectWorkspaceDetail(); const openPullRequest = useOpenPullRequest(); + const popOut = useAtomCommand(threadEnvironment.popOut, { reportFailure: false }); + const popOutBusyRef = useRef(false); + const popOutAvailability = + selectedThread && canOperateThread + ? threadPopOutAvailability(selectedThread.source) + : "unsupported"; + const handlePopOut = () => { + if (!selectedThread || popOutBusyRef.current) return; + if (popOutAvailability === "blocked") { + Dialog.alert(gt("Can't pop out yet"), gt("Wait for it to finish or stop it first.")); + return; + } + const environmentId = selectedThread.environmentId; + const threadId = selectedThread.id; + Dialog.confirm({ + title: gt("Pop out to top level?"), + message: gt( + "It becomes an ordinary thread in your list and stops reporting to the thread that started it.", + ), + confirmText: gt("Pop out"), + onConfirm: () => { + if (popOutBusyRef.current) return; + popOutBusyRef.current = true; + void popOut({ environmentId, input: { threadId } }) + .then((result) => { + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert( + gt("Could not pop out thread"), + error instanceof Error ? error.message : gt("Try again."), + ); + } + }) + .finally(() => { + popOutBusyRef.current = false; + }); + }, + }); + }; const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back"); const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail); const mergeBackRun = @@ -1059,6 +1101,7 @@ function ThreadRouteContent( inspectorMode={inspectorMode} onOpenFilesInspector={handleOpenFilesInspector} onReturnToThread={props.onReturnToThread} + onPopOut={popOutAvailability === "unsupported" ? undefined : handlePopOut} /> ) } diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 2e22b2efc6288..42bb15a9e6cfa 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4800,6 +4800,8 @@ "7fa8a4d836b4d075": "Dieser Rechner hat keine verknüpften Rechner. Verknüpfe einen in den Einstellungen der Desktop- oder Web-App.", "05ba3b5f06a7acfe": "Dateien schließen", "c7e4f052c3d6c066": "Dateien öffnen", + "c440ceeaf0452d52": "Auf oberste Ebene verschieben", + "8dcc52104281c7d2": "In einen normalen Thread umwandeln", "740ee1b96278f02f": "Audio · {size}", "93ade1a4fd485bc3": "Audio", "e8043d133bb85048": "Audio pausieren", @@ -4835,6 +4837,12 @@ "d506b798402041ab": "Jetzt senden", "9a62f694ba5c35c5": "Thread wird geöffnet…", "bb24a2960c689a20": "Dieser Thread ist im aktuellen mobilen Snapshot nicht verfügbar.", + "172e0baea818e9aa": "Verschieben noch nicht möglich", + "dd4ea2dfb2476c35": "Warte, bis er fertig ist, oder stoppe ihn zuerst.", + "4249bde5600d6792": "Auf oberste Ebene verschieben?", + "b000660ae40f4586": "Er wird zu einem normalen Thread in deiner Liste und meldet keine Ergebnisse mehr an den Thread, der ihn gestartet hat.", + "8df226bf3314e35d": "Verschieben", + "84eccdaa4d8f3c01": "Thread konnte nicht verschoben werden", "41ca8f475c481866": "Subagent von {title}", "f3e00e6c416eab38": "Von {origin}", "bdfb9e7660ab25d3": "Thread konnte nicht fortgesetzt werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index f069a2c165e33..fcd473cd97022 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4802,6 +4802,8 @@ "7fa8a4d836b4d075": "This machine has no linked machines. Link one in Settings on desktop or web.", "05ba3b5f06a7acfe": "Close files", "c7e4f052c3d6c066": "Open files", + "c440ceeaf0452d52": "Pop out to top level", + "8dcc52104281c7d2": "Make it an ordinary thread", "740ee1b96278f02f": "Audio · {size}", "93ade1a4fd485bc3": "Audio", "e8043d133bb85048": "Pause audio", @@ -4837,6 +4839,12 @@ "d506b798402041ab": "Send now", "9a62f694ba5c35c5": "Opening thread…", "bb24a2960c689a20": "This thread is not available in the current mobile snapshot.", + "172e0baea818e9aa": "Can't pop out yet", + "dd4ea2dfb2476c35": "Wait for it to finish or stop it first.", + "4249bde5600d6792": "Pop out to top level?", + "b000660ae40f4586": "It becomes an ordinary thread in your list and stops reporting to the thread that started it.", + "8df226bf3314e35d": "Pop out", + "84eccdaa4d8f3c01": "Could not pop out thread", "41ca8f475c481866": "Subagent of {title}", "f3e00e6c416eab38": "From {origin}", "bdfb9e7660ab25d3": "Could not resume thread", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 22c5eb71d05f7..f9dede69caaa7 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4793,6 +4793,8 @@ "7fa8a4d836b4d075": "Esta máquina no tiene máquinas vinculadas. Vincula una en Ajustes desde la app de escritorio o la web.", "05ba3b5f06a7acfe": "Cerrar archivos", "c7e4f052c3d6c066": "Abrir archivos", + "c440ceeaf0452d52": "Mover al nivel superior", + "8dcc52104281c7d2": "Convertir en un hilo normal", "740ee1b96278f02f": "Audio · {size}", "93ade1a4fd485bc3": "Audio", "e8043d133bb85048": "Pausar audio", @@ -4828,6 +4830,12 @@ "d506b798402041ab": "Enviar ahora", "9a62f694ba5c35c5": "Abriendo hilo…", "bb24a2960c689a20": "Este hilo no está disponible en la instantánea móvil actual.", + "172e0baea818e9aa": "Aún no se puede mover", + "dd4ea2dfb2476c35": "Espera a que termine o detenlo primero.", + "4249bde5600d6792": "¿Mover al nivel superior?", + "b000660ae40f4586": "Se convierte en un hilo normal de tu lista y deja de enviar resultados al hilo que lo inició.", + "8df226bf3314e35d": "Mover", + "84eccdaa4d8f3c01": "No se pudo mover el hilo", "41ca8f475c481866": "Subagente de {title}", "f3e00e6c416eab38": "De {origin}", "bdfb9e7660ab25d3": "No se pudo reanudar el hilo", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 3b1d5f4a54942..37947b28a13fe 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4794,6 +4794,8 @@ "7fa8a4d836b4d075": "Cette machine n’a aucune machine associée. Associez-en une dans les Paramètres de l’app de bureau ou du web.", "05ba3b5f06a7acfe": "Fermer les fichiers", "c7e4f052c3d6c066": "Ouvrir les fichiers", + "c440ceeaf0452d52": "Déplacer au premier niveau", + "8dcc52104281c7d2": "En faire un fil ordinaire", "740ee1b96278f02f": "Audio · {size}", "93ade1a4fd485bc3": "Audio", "e8043d133bb85048": "Mettre l’audio en pause", @@ -4829,6 +4831,12 @@ "d506b798402041ab": "Envoyer maintenant", "9a62f694ba5c35c5": "Ouverture du fil…", "bb24a2960c689a20": "Ce fil n’est pas disponible dans l’instantané mobile actuel.", + "172e0baea818e9aa": "Déplacement encore impossible", + "dd4ea2dfb2476c35": "Attendez la fin ou arrêtez-le d'abord.", + "4249bde5600d6792": "Déplacer au premier niveau ?", + "b000660ae40f4586": "Il devient un fil ordinaire dans votre liste et ne transmet plus ses résultats au fil qui l'a lancé.", + "8df226bf3314e35d": "Déplacer", + "84eccdaa4d8f3c01": "Impossible de déplacer le fil", "41ca8f475c481866": "Sous-agent de {title}", "f3e00e6c416eab38": "Depuis {origin}", "bdfb9e7660ab25d3": "Impossible de reprendre le fil", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index fabaedfc87450..6a53a1922c2cf 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4773,6 +4773,8 @@ "7fa8a4d836b4d075": "このマシンにはリンクされたマシンがありません。デスクトップまたは Web の設定でリンクしてください。", "05ba3b5f06a7acfe": "ファイルを閉じる", "c7e4f052c3d6c066": "ファイルを開く", + "c440ceeaf0452d52": "最上位に移動", + "8dcc52104281c7d2": "通常のスレッドにする", "740ee1b96278f02f": "音声 · {size}", "93ade1a4fd485bc3": "音声", "e8043d133bb85048": "音声を一時停止", @@ -4808,6 +4810,12 @@ "d506b798402041ab": "今すぐ送信", "9a62f694ba5c35c5": "スレッドを開いています…", "bb24a2960c689a20": "このスレッドは現在のモバイルのスナップショットでは利用できません。", + "172e0baea818e9aa": "まだ移動できません", + "dd4ea2dfb2476c35": "完了するまで待つか、先に停止してください。", + "4249bde5600d6792": "最上位に移動しますか?", + "b000660ae40f4586": "一覧の通常のスレッドになり、開始元のスレッドへの結果報告を停止します。", + "8df226bf3314e35d": "移動", + "84eccdaa4d8f3c01": "スレッドを移動できませんでした", "41ca8f475c481866": "{title} のサブエージェント", "f3e00e6c416eab38": "{origin} から", "bdfb9e7660ab25d3": "スレッドを再開できませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ab31b0e912bd9..4a102e872390a 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4778,6 +4778,8 @@ "7fa8a4d836b4d075": "이 머신에는 연결된 머신이 없습니다. 데스크톱 또는 웹의 설정에서 연결하세요.", "05ba3b5f06a7acfe": "파일 닫기", "c7e4f052c3d6c066": "파일 열기", + "c440ceeaf0452d52": "최상위로 이동", + "8dcc52104281c7d2": "일반 스레드로 전환", "740ee1b96278f02f": "오디오 · {size}", "93ade1a4fd485bc3": "오디오", "e8043d133bb85048": "오디오 일시 중지", @@ -4813,6 +4815,12 @@ "d506b798402041ab": "지금 보내기", "9a62f694ba5c35c5": "스레드 여는 중…", "bb24a2960c689a20": "이 스레드는 현재 모바일 스냅샷에서 사용할 수 없습니다.", + "172e0baea818e9aa": "아직 이동할 수 없음", + "dd4ea2dfb2476c35": "완료될 때까지 기다리거나 먼저 중지하세요.", + "4249bde5600d6792": "최상위로 이동할까요?", + "b000660ae40f4586": "목록의 일반 스레드가 되며, 이 스레드를 시작한 스레드에 결과를 보고하지 않습니다.", + "8df226bf3314e35d": "이동", + "84eccdaa4d8f3c01": "스레드를 이동하지 못했습니다", "41ca8f475c481866": "{title}의 서브에이전트", "f3e00e6c416eab38": "출처: {origin}", "bdfb9e7660ab25d3": "스레드를 재개할 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pl.json b/apps/mobile/src/i18n/translations/pl.json index 78e9df4c547b8..55f0c5a823743 100644 --- a/apps/mobile/src/i18n/translations/pl.json +++ b/apps/mobile/src/i18n/translations/pl.json @@ -4769,6 +4769,8 @@ "11bb30071c8d00e4": "Link działa raz i wygasa po 24 godzinach.", "05ba3b5f06a7acfe": "Zamknij pliki", "c7e4f052c3d6c066": "Otwórz pliki", + "c440ceeaf0452d52": "Wydziel na najwyższy poziom", + "8dcc52104281c7d2": "Zmień go w zwykły wątek", "740ee1b96278f02f": "Audio · {size}", "93ade1a4fd485bc3": "Audio", "e8043d133bb85048": "Wstrzymaj audio", @@ -4804,6 +4806,12 @@ "d506b798402041ab": "Wyślij teraz", "9a62f694ba5c35c5": "Otwieranie wątku…", "bb24a2960c689a20": "Ten wątek nie jest dostępny w bieżącym snapshotcie mobilnym.", + "172e0baea818e9aa": "Nie można jeszcze wydzielić", + "dd4ea2dfb2476c35": "Poczekaj, aż się zakończy, lub najpierw go zatrzymaj.", + "4249bde5600d6792": "Wydzielić na najwyższy poziom?", + "b000660ae40f4586": "Stanie się zwykłym wątkiem na Twojej liście i przestanie raportować do wątku, który go uruchomił.", + "8df226bf3314e35d": "Wydziel", + "84eccdaa4d8f3c01": "Nie można wydzielić wątku", "41ca8f475c481866": "Subagent wątku {title}", "f3e00e6c416eab38": "Z {origin}", "bdfb9e7660ab25d3": "Nie udało się wznowić wątku", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index f821f8d0dfc33..561fced58fd52 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4794,6 +4794,8 @@ "7fa8a4d836b4d075": "Esta máquina não tem máquinas vinculadas. Vincule uma em Configurações no desktop ou na web.", "05ba3b5f06a7acfe": "Fechar arquivos", "c7e4f052c3d6c066": "Abrir arquivos", + "c440ceeaf0452d52": "Mover para o nível superior", + "8dcc52104281c7d2": "Tornar uma conversa comum", "740ee1b96278f02f": "Áudio · {size}", "93ade1a4fd485bc3": "Áudio", "e8043d133bb85048": "Pausar áudio", @@ -4829,6 +4831,12 @@ "d506b798402041ab": "Enviar agora", "9a62f694ba5c35c5": "Abrindo thread…", "bb24a2960c689a20": "Esta thread não está disponível no snapshot móvel atual.", + "172e0baea818e9aa": "Ainda não é possível mover", + "dd4ea2dfb2476c35": "Espere terminar ou pare primeiro.", + "4249bde5600d6792": "Mover para o nível superior?", + "b000660ae40f4586": "Ela se torna uma conversa comum na sua lista e deixa de enviar resultados à conversa que a iniciou.", + "8df226bf3314e35d": "Mover", + "84eccdaa4d8f3c01": "Não foi possível mover a conversa", "41ca8f475c481866": "Subagente de {title}", "f3e00e6c416eab38": "De {origin}", "bdfb9e7660ab25d3": "Não foi possível retomar a thread", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 1f7d54839cd07..6c8b631a9d32d 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4872,6 +4872,8 @@ "7fa8a4d836b4d075": "У этой машины нет привязанных машин. Привяжите машину в Настройках на компьютере или в веб-версии.", "05ba3b5f06a7acfe": "Закрыть файлы", "c7e4f052c3d6c066": "Открыть файлы", + "c440ceeaf0452d52": "Переместить на верхний уровень", + "8dcc52104281c7d2": "Сделать обычной веткой", "740ee1b96278f02f": "Аудио · {size}", "93ade1a4fd485bc3": "Аудио", "e8043d133bb85048": "Приостановить аудио", @@ -4907,6 +4909,12 @@ "d506b798402041ab": "Отправить сейчас", "9a62f694ba5c35c5": "Открытие треда…", "bb24a2960c689a20": "Этот тред недоступен в текущем мобильном снимке.", + "172e0baea818e9aa": "Пока нельзя переместить", + "dd4ea2dfb2476c35": "Дождитесь завершения или сначала остановите.", + "4249bde5600d6792": "Переместить на верхний уровень?", + "b000660ae40f4586": "Она станет обычной веткой в списке и перестанет отправлять результаты в ветку, которая её запустила.", + "8df226bf3314e35d": "Переместить", + "84eccdaa4d8f3c01": "Не удалось переместить ветку", "41ca8f475c481866": "Субагент {title}", "f3e00e6c416eab38": "Из {origin}", "bdfb9e7660ab25d3": "Не удалось возобновить тред", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index bec38529c9d75..687d5d7db19e5 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4800,6 +4800,8 @@ "7fa8a4d836b4d075": "Den här datorn har inga länkade datorer. Länka en i Inställningar på datorn eller webben.", "05ba3b5f06a7acfe": "Stäng filer", "c7e4f052c3d6c066": "Öppna filer", + "c440ceeaf0452d52": "Flytta till översta nivån", + "8dcc52104281c7d2": "Gör den till en vanlig tråd", "740ee1b96278f02f": "Ljud · {size}", "93ade1a4fd485bc3": "Ljud", "e8043d133bb85048": "Pausa ljudet", @@ -4835,6 +4837,12 @@ "d506b798402041ab": "Skicka nu", "9a62f694ba5c35c5": "Öppnar tråden…", "bb24a2960c689a20": "Tråden är inte tillgänglig i den aktuella mobilögonblicksbilden.", + "172e0baea818e9aa": "Kan inte flytta ännu", + "dd4ea2dfb2476c35": "Vänta tills den är klar eller stoppa den först.", + "4249bde5600d6792": "Flytta till översta nivån?", + "b000660ae40f4586": "Den blir en vanlig tråd i listan och slutar rapportera till tråden som startade den.", + "8df226bf3314e35d": "Flytta", + "84eccdaa4d8f3c01": "Kunde inte flytta tråden", "41ca8f475c481866": "Subagent till {title}", "f3e00e6c416eab38": "Från {origin}", "bdfb9e7660ab25d3": "Kunde inte återuppta tråden", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index e10b59531e7ce..50c5dc6e5e329 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4782,6 +4782,8 @@ "7fa8a4d836b4d075": "这台机器没有已关联的机器。请在桌面端或网页端的设置中关联一台。", "05ba3b5f06a7acfe": "关闭文件", "c7e4f052c3d6c066": "打开文件", + "c440ceeaf0452d52": "移至顶层", + "8dcc52104281c7d2": "设为普通会话", "740ee1b96278f02f": "音频 · {size}", "93ade1a4fd485bc3": "音频", "e8043d133bb85048": "暂停音频", @@ -4817,6 +4819,12 @@ "d506b798402041ab": "立即发送", "9a62f694ba5c35c5": "正在打开会话…", "bb24a2960c689a20": "当前移动端快照中没有此会话。", + "172e0baea818e9aa": "暂时无法移出", + "dd4ea2dfb2476c35": "请等待完成,或先停止。", + "4249bde5600d6792": "移至顶层?", + "b000660ae40f4586": "它将成为列表中的普通会话,并停止向启动它的会话报告结果。", + "8df226bf3314e35d": "移出", + "84eccdaa4d8f3c01": "无法移出会话", "41ca8f475c481866": "{title} 的子智能体", "f3e00e6c416eab38": "来自 {origin}", "bdfb9e7660ab25d3": "无法继续会话", diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f99b664f0f6b2..3e6c472941299 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3180,6 +3180,22 @@ const make = Effect.gen(function* () { } return yield* remoteDelegation.cancel(scope, remoteTask, input); } + // Pop-out needs every task in the child to have ended, and it leaves this thread's control. + const childShell = yield* threadManagement + .getThreadShell(childThreadId) + .pipe(Effect.mapError(threadManagementFailure)); + if (childShell?.lineage.detachedFrom?.threadId === scope.thread.threadId) { + if (!isTerminalTaskStatus(current.status)) { + return yield* failure( + "invalid_request", + `Thread ${childThreadId} was popped out to top level and no longer belongs to this task.`, + ); + } + return { + taskId: input.taskId, + status: current.status, + } satisfies OrchestratorMcpTaskCancelResult; + } const key = yield* requestKey(input.clientRequestId); const parentProjection = yield* loadThreadRecords(scope.thread.threadId, []); // Cancelling stops the child and every task under it, each a write to a diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index bb1b4a2f095ce..14e707a3f067b 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -682,6 +682,60 @@ it.effect("rejects an unknown organize target instead of archiving the calling t ); }); +it.effect("allows an agent to pop out only its own child", () => { + const dispatched: Array = []; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const otherThreadId = ThreadId.make("mcp-core-child"); + for (const target of [undefined, threadId, otherThreadId, ThreadId.make("unrelated")]) { + const result = yield* server + .callTool({ + name: "t3_thread_organize", + arguments: { action: "pop_out", ...(target === undefined ? {} : { threadId: target }) }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + if (target === otherThreadId) expect(result.isError).not.toBe(true); + else + expect(declaredFailure(result)).toMatchObject({ + code: "invalid_request", + message: expect.stringContaining("cannot pop itself out"), + }); + } + expect(dispatched).toMatchObject([{ type: "thread.detach", threadId: otherThreadId }]); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: ({ threadId: id }) => { + const shell = McpToolAccessTestkit.liveThreadShell(id); + return Effect.succeed( + McpToolAccessTestkit.idleThreadProjection({ + ...shell, + lineage: { + ...shell.lineage, + parentThreadId: id === ThreadId.make("mcp-core-child") ? threadId : null, + }, + }), + ); + }, + dispatch: (command) => { + dispatched.push(command); + return Effect.succeed({ sequence: 1 } as never); + }, + }), + ), + ), + ), + ); +}); + it.effect("keeps unexpected handler defects private through the production registration", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 5caab0039400a..9dbfd4e13cf81 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -416,7 +416,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { ), t3_thread_organize: writesThread((input) => Effect.gen(function* () { - const { threads, projection, caller } = yield* readThread(input.threadId); + const { threads, projection, caller, scope } = yield* readThread(input.threadId); const common = { commandId: yield* newCommandId(), threadId: projection.thread.id }; if (input.action === "settle") { return yield* threads @@ -441,6 +441,21 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { case "mark_unread": command = { ...common, type: "thread.mark-unread" }; break; + case "pop_out": + // Otherwise a child could leave its parent's Stop on its own. + if ( + scope.client?.senderThread !== undefined || + (caller !== undefined && + (caller.id === projection.thread.id || + caller.id !== projection.thread.lineage.parentThreadId)) + ) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: "A thread cannot pop itself out; its parent or the user can.", + }); + } + command = { ...common, type: "thread.detach" }; + break; case "pin": { // Always send a key, as the client does: the reducer ignores it for a // thread that is already pinned, and a projection read before this diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 121a4370fa4dd..36a9f45c4424d 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -33,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.", + "Pin, snooze, settle, archive, mark unread, or pop out a finished child. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread waits for a clean turn end and empty queue.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), @@ -47,6 +47,7 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", { "archive", "unarchive", "mark_unread", + "pop_out", ]), snoozedUntil: Schema.optional(IsoDateTime), }), diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 4b159bbaf360e..a2ea9e05346eb 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -21,6 +21,7 @@ import { ProviderThreadId, ProviderTurnId, RunId, + isListedThreadLineage, RuntimeRequestId, ThreadId, TurnItemId, @@ -1426,6 +1427,14 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { ); }); +const refusalOf = (dispatch: Effect.Effect) => + dispatch.pipe( + Effect.flip, + Effect.map((error) => + error._tag === "OrchestratorDispatchError" ? String(error.cause) : error._tag, + ), + ); + const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`); const parentProviderThreadId = (threadId: ThreadId) => @@ -2781,6 +2790,184 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( }), ); + it.effect("pops a reported child out in place, and its later turns stay its own", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:pop-out-parent"); + const projectId = ProjectId.make("project:pop-out"); + const parentRunId = RunId.make("run:pop-out-parent"); + const rootNodeId = NodeId.make("node:pop-out-parent"); + yield* seedParentWithTerminalTask({ + threadId: parentThreadId, + projectId, + runId: parentRunId, + rootNodeId, + taskId: NodeId.make("node:pop-out-seed"), + deliveryState: "acknowledged", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "pop-out-child", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const popOut = (name: string) => + orchestrator.dispatch({ + type: "thread.detach", + commandId: CommandId.make(`command:pop-out:${name}`), + threadId: child.childThreadId, + }); + assert.include( + yield* refusalOf(popOut("unreported")), + "has a delegated task whose result has not reached its parent", + ); + yield* orchestrator.recoverDelegatedTasks; + yield* orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make("command:pop-out:acknowledge"), + parentThreadId, + taskId: child.taskId, + observedByRunId: parentRunId, + }); + yield* popOut("reported"); + + const popped = yield* orchestrator.getThreadProjection(child.childThreadId); + assert.deepStrictEqual(popped.thread.lineage, { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: parentThreadId, + detachedFrom: { threadId: parentThreadId }, + }); + assert.deepStrictEqual(yield* orchestrator.listAppOwnedChildThreadIds(parentThreadId), []); + const shell = (yield* orchestrator.getShellSnapshot()).threads.find( + (row) => row.id === child.childThreadId, + ); + assert.isTrue(shell !== undefined && isListedThreadLineage(shell.lineage)); + + // The old parent's agent can still message it, but that starts no task of its own. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make("command:pop-out:followup"), + threadId: child.childThreadId, + senderThreadId: parentThreadId, + messageId: MessageId.make("message:pop-out:followup"), + text: "Keep going on your own.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + const followup = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find( + (run) => run.ordinal === 2, + ); + assert.isDefined(followup); + assert.isUndefined(followup?.delegatedTaskId); + const tasks = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.filter( + (task) => task.childThreadId === child.childThreadId, + ); + assert.deepStrictEqual( + tasks.map((task) => [task.id, task.status, task.completionDelivery?.state]), + [[child.taskId, "completed", "acknowledged"]], + ); + }), + ); + + it.effect( + "refuses to pop out a working child, a provider's subagent, or a top-level thread", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:pop-out-refused-parent"); + const projectId = ProjectId.make("project:pop-out-refused"); + const parentRunId = RunId.make("run:pop-out-refused-parent"); + const rootNodeId = NodeId.make("node:pop-out-refused-parent"); + yield* seedParentWithTerminalTask({ + threadId: parentThreadId, + projectId, + runId: parentRunId, + rootNodeId, + taskId: NodeId.make("node:pop-out-refused-seed"), + deliveryState: "acknowledged", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "pop-out-refused-child", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + yield* orchestrator.recoverDelegatedTasks; + yield* orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make("command:pop-out-refused:acknowledge"), + parentThreadId, + taskId: child.taskId, + observedByRunId: parentRunId, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make("command:pop-out-refused:followup"), + threadId: child.childThreadId, + senderThreadId: parentThreadId, + messageId: MessageId.make("message:pop-out-refused:followup"), + text: "One more thing.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + const providerChildThreadId = ThreadId.make("thread:pop-out-refused-native"); + const created = (yield* orchestrator.getThreadProjection(child.childThreadId)).thread; + yield* sink.write({ + events: [ + { + id: EventId.make("event:pop-out-refused-native"), + type: "thread.created", + threadId: providerChildThreadId, + occurredAt: now, + payload: { + ...created, + id: providerChildThreadId, + creationSource: "provider", + forkedFrom: null, + }, + }, + ], + }); + const refusals = []; + for (const threadId of [child.childThreadId, providerChildThreadId, parentThreadId]) { + refusals.push( + yield* refusalOf( + orchestrator.dispatch({ + type: "thread.detach", + commandId: CommandId.make(`command:pop-out-refused:${threadId}`), + threadId, + }), + ), + ); + } + assert.deepStrictEqual(refusals, [ + `Thread ${child.childThreadId} is still working. Wait for it to finish or stop it first.`, + `Thread ${providerChildThreadId} is run by its provider's own subagent tool and cannot be popped out.`, + `Thread ${parentThreadId} is not a delegated child thread.`, + ]); + }), + ); + it.effect("checkpoint retry releases a pending sibling after its wake offer failed", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c28e92accb179..21ab9d438425c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -30,6 +30,8 @@ import { isCompactionCommandMessage, isDeliveredProviderTurn, isOrchestrationV2WorkActive, + isDelegatedChildThread, + isDelegatedTaskReported, isProviderNativeSubagentThread, MessageId, type NodeId, @@ -435,6 +437,10 @@ export interface OrchestratorV2DispatchResult { } export interface OrchestratorV2Shape { + readonly withDelegatedTasksStopLock: ( + threadId: ThreadId, + walk: (dispatch: OrchestratorV2Shape["dispatch"]) => Effect.Effect, + ) => Effect.Effect; readonly resumeQueuedRuns: Effect.Effect; readonly recoverDelegatedTasks: Effect.Effect; readonly recoverDelegatedTask: ( @@ -682,6 +688,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.snooze": case "thread.unsnooze": case "thread.auto-settle.set": + case "thread.detach": case "thread.pin": case "thread.unpin": case "thread.pin.reorder": @@ -6072,6 +6079,95 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + // Only finished, reported work may leave: an in-flight task's result would have nowhere to go. + const dispatchThreadDetach = Effect.fn("orchestrationV2.dispatch.threadDetach")(function* ( + command: Extract, + events: Ref.Ref>, + ) { + const refuse = (cause: string) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} ${cause}`, + }); + const child = yield* loadProjectionForCommand(command, [ + "runs", + "runtimeRequests", + "providerThreads", + "providerSessions", + "subagents", + ]); + const thread = child.thread; + if (thread.deletedAt !== null) return yield* refuse("is deleted."); + if (thread.archivedAt !== null) return yield* refuse("is archived."); + if (isProviderNativeSubagentThread(thread)) { + return yield* refuse("is run by its provider's own subagent tool and cannot be popped out."); + } + const parentThreadId = thread.lineage.parentThreadId; + if (!isDelegatedChildThread(thread) || parentThreadId === null) { + return yield* refuse("is not a delegated child thread."); + } + if ( + threadHasUnfinishedWork(child) || + child.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0) || + child.subagents.some((task) => isOrchestrationV2WorkActive(task.status)) + ) { + return yield* refuse("is still working. Wait for it to finish or stop it first."); + } + for (const session of child.providerSessions) { + if (yield* sessionHasBackgroundWork(session, child.providerThreads)) { + return yield* refuse("is still working. Wait for it to finish or stop it first."); + } + } + const tasks = (yield* projectionStore + .getThreadRecords(parentThreadId, ["subagents"]) + .pipe(mapDispatchError(command))).subagents.filter( + (task) => task.origin === "app_owned" && task.childThreadId === thread.id, + ); + const spawningRunIds = tasks.flatMap((task) => + task.completionDelivery === undefined && task.runId !== null ? [task.runId] : [], + ); + const liveSpawningRunIds = new Set( + spawningRunIds.length === 0 + ? [] + : (yield* projectionStore + .getThreadRecords(parentThreadId, ["runs"], { runIds: spawningRunIds }) + .pipe(mapDispatchError(command))).runs + .filter(isLiveRun) + .map((run) => run.id), + ); + if ( + tasks.some( + (task) => + !isDelegatedTaskReported(task, task.runId !== null && liveSpawningRunIds.has(task.runId)), + ) + ) { + return yield* refuse( + "has a delegated task whose result has not reached its parent. Wait for it to finish or stop it first.", + ); + } + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "thread.detached", + threadId: thread.id, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: { + ...thread, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: thread.lineage.rootThreadId, + detachedFrom: { threadId: parentThreadId }, + }, + updatedAt: now, + }, + }); + }); + const dispatchProviderSessionDetach = Effect.fn("orchestrationV2.dispatch.providerSessionDetach")( function* ( command: Extract, @@ -15105,6 +15201,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); if (projection.thread.deletedAt !== null) return undefined; + if ( + command.expectedParentThreadId !== undefined && + projection.thread.lineage.parentThreadId !== command.expectedParentThreadId + ) + return undefined; // Queued after the interrupt, since a thread's effects run in order. const stopDelegatedTasks = command.stopDelegatedTasks === false || @@ -15483,8 +15584,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); /** - * Thread lineage and fork origin are immutable, so this - * is safe to read without holding either thread's dispatch lock. + * Safe to read without holding either thread's dispatch lock: fork origin is immutable and + * lineage only ever leaves a parent (pop-out), so a stale read names the parent the child had, + * and work under that parent's lock re-reads the child's lineage. */ const appOwnedSubagentParentThreadId = Effect.fn("Orchestrator.appOwnedSubagentParentThreadId")( function* (childThreadId: ThreadId) { @@ -16692,6 +16794,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.guest-message.dismiss": yield* dispatchGuestShare(command, events, effects); break; + case "thread.detach": + yield* dispatchThreadDetach(command, events); + break; case "provider-session.detach": yield* dispatchProviderSessionDetach(command, events, effects); break; @@ -17385,8 +17490,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? withSubagentParentLock(message.threadId, dispatch) : dispatch, ); - // Answering a message-mode question can also start a follow-up. - return yield* command.type === "runtime-request.respond" + // Answering a message-mode question can also start a follow-up, and a pop-out must not + // race the parent writing a follow-up task for the child. + return yield* command.type === "runtime-request.respond" || command.type === "thread.detach" ? withSubagentParentLock(command.threadId, dispatch) : dispatch; }); @@ -17861,6 +17967,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio { messageRoles: ["user"] }, ) .pipe(mapDispatchError(command)); + if (child.thread.lineage.parentThreadId !== input.parentThreadId) return; const followUpRun = child.runs .filter((run) => run.delegatedTaskId === input.taskId) .toSorted((a, b) => b.ordinal - a.ordinal)[0]; @@ -17912,6 +18019,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio new OrchestratorProjectionError({ threadId: ThreadId.make("thread:shell"), cause }); return OrchestratorV2.of({ + withDelegatedTasksStopLock: Effect.fn("Orchestrator.withDelegatedTasksStopLock")( + (threadId, walk) => + threadDispatch.withLock( + threadId, + walk((command) => + commandThreadId(command) === threadId + ? dispatchWithReceiptEffect(command) + : dispatchWithReceipt(command), + ), + ), + ), resumeQueuedRuns, recoverDelegatedTasks, recoverDelegatedTask, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index b36f3b9844622..f010d5be8af09 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -110,7 +110,7 @@ import { DEFERRED_COMMAND_MESSAGE_CONDITION, JAVASCRIPT_TRIM_WHITESPACE, } from "./deferredCommandMessage.ts"; -import { readableSearchText } from "./messageSearchIndex.ts"; +import { indexThreadMessages, readableSearchText } from "./messageSearchIndex.ts"; import { isFoldableWorkItem, isThreadHistoryUserTurn, @@ -1077,6 +1077,7 @@ export function applyToProjection( case "thread.unsettled": case "thread.snoozed": case "thread.unsnoozed": + case "thread.detached": case "thread.auto-settle-set": case "thread.pinned": case "thread.unpinned": @@ -2580,6 +2581,7 @@ export const layer: Layer.Layer sql<{ readonly child_thread_id: string }>`SELECT child_thread_id - FROM orchestration_v2_projection_subagents + FROM orchestration_v2_projection_subagents AS task WHERE thread_id = ${threadId} AND origin = 'app_owned' AND child_thread_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_threads AS child + WHERE child.thread_id = task.child_thread_id + AND json_extract(child.payload_json, '$.lineage.detachedFrom.threadId') = ${threadId} + ) ORDER BY COALESCE(started_at, ''), subagent_id ASC`.pipe( Effect.map((rows) => [...new Set(rows.map((row) => ThreadId.make(row.child_thread_id)))]), Effect.mapError(controlReadError(threadId)), diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index e06b7cba1e0f4..018bf5990b6f5 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -89,6 +89,16 @@ describe("subagent shell events", () => { ).toBe(true); expect(subagents.has("new-child")).toBe(true); }); + + it("publishes a popped-out child's transcript once it leaves its parent", () => { + const subagents = new Set(["child"]); + expect(shouldPublishShellApplicationEvent(stored("child", "thread.detached"), subagents)).toBe( + true, + ); + expect( + shouldPublishShellApplicationEvent(stored("child", "turn-item.updated"), subagents), + ).toBe(true); + }); }); it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () => diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 2cdf7ce48d02c..3fa9d1687cbbf 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -562,6 +562,10 @@ export function shouldPublishShellApplicationEvent( } return true; } + if (event.type === "thread.detached") { + subagentThreadIds.delete(event.threadId); + return true; + } if (event.type === "thread.deleted") { // Replay and the live tail overlap; keep known IDs so late events stay filtered. return true; diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index b3c7a1042b387..bc7caf3fb403d 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1815,7 +1815,16 @@ const make = Effect.gen(function* () { const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn( "ThreadManagementService.stopDelegatedTasks", )(function* (input) { + if (input.remoteDispatch === undefined) { + return yield* orchestrator.withDelegatedTasksStopLock(input.threadId, (remoteDispatch) => + stopDelegatedTasks({ ...input, remoteDispatch }), + ); + } const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]); + // A child popped out to top level no longer answers to this parent's Stop. + const attachedChildThreadIds = new Set( + yield* orchestrator.listAppOwnedChildThreadIds(input.threadId), + ); const failures: Array< Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError > = []; @@ -1868,7 +1877,7 @@ const make = Effect.gen(function* () { } const threadId = task.childThreadId; // Follow-up tasks reuse a child thread; walk its subtree only once. - if (stoppedChildThreadIds.has(threadId)) continue; + if (stoppedChildThreadIds.has(threadId) || !attachedChildThreadIds.has(threadId)) continue; stoppedChildThreadIds.add(threadId); yield* Effect.gen(function* () { let shouldStop = activeChildThreadIds.has(threadId); @@ -1893,10 +1902,13 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`${input.commandId}:stop:${threadId}`), threadId, stopDelegatedTasks: false, + expectedParentThreadId: input.threadId, ...(input.reason === undefined ? {} : { reason: input.reason }), }); } if (hasAppOwnedChildren) { + const child = yield* orchestrator.getThreadRecords(threadId, []); + if (child.thread.lineage.parentThreadId !== input.threadId) return; yield* stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }); } }).pipe( diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 4d033c87bb4f1..1f0246beb5d3b 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -539,6 +539,28 @@ it.layer(layerTest)("ThreadSearch", (it) => { assert.deepEqual((yield* search.search({ query: "ab" })).matches, []); assert.lengthOf((yield* search.search({ query: "renam be" })).matches, 1); assert.lengthOf((yield* search.search({ query: "renam ab" })).matches, 0); + + // Popping the subagent out lists it, along with what it wrote before. + const created = thread(subagent, project, { subagentOf: parent }); + if (created.type !== "thread.created") throw new Error("expected thread.created"); + yield* projections.apply({ + ...created, + id: EventId.make(`detached:${subagent}`), + type: "thread.detached", + payload: { + ...created.payload, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: parent, + detachedFrom: { threadId: parent }, + }, + }, + }); + assert.deepEqual( + (yield* search.search({ query: "search servi" })).matches.map((match) => match.threadId), + [parent, subagent], + ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index b356bc1a63b74..690043e0c1487 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -729,6 +729,48 @@ it.effect( }).pipe(Effect.provide(layerTest)), ); +it.effect("a parent's Stop no longer reaches a child popped out of it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const parentThreadId = ThreadId.make("thread:stop-popped-parent"); + yield* createWatchingThread(parentThreadId, 1); + yield* send(parentThreadId, "first", "start_immediately"); + const childThreadId = yield* delegate(parentThreadId, "popped child"); + const child = (yield* orchestrator.getThreadProjection(childThreadId)).thread; + const before = yield* threadState(childThreadId); + yield* projections.apply({ + id: EventId.make("event:stop-popped:detached"), + type: "thread.detached", + threadId: childThreadId, + occurredAt: yield* DateTime.now, + payload: { + ...child, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: child.lineage.rootThreadId, + detachedFrom: { threadId: parentThreadId }, + }, + }, + }); + + yield* orchestrator.dispatch({ + type: "thread.stop", + threadId: childThreadId, + commandId: CommandId.make("stop-popped-stale-parent"), + expectedParentThreadId: parentThreadId, + }); + assert.deepEqual(yield* threadState(childThreadId), before); + yield* threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("stop-popped-parent"), + }); + assert.deepEqual(yield* threadState(childThreadId), before); + }).pipe(Effect.provide(layerTest)), +); + it.effect("a repeated Stop that changes nothing still stops the delegated tasks", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/messageSearchIndex.ts b/apps/server/src/orchestration-v2/messageSearchIndex.ts index 1eda63e972c53..8fc5536682b67 100644 --- a/apps/server/src/orchestration-v2/messageSearchIndex.ts +++ b/apps/server/src/orchestration-v2/messageSearchIndex.ts @@ -171,6 +171,31 @@ export const recreateMessageSearchTriggers = Effect.fn("MessageSearchIndex.recre }, ); +/** Indexes a thread's messages that `indexedMessageCondition` skipped while it was a subagent. */ +export const indexThreadMessages = Effect.fn("MessageSearchIndex.indexThread")(function* ( + sql: SqlClient.SqlClient, + threadId: string, +) { + const index = yield* sql` + SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' + `; + if (index.length === 0) return; + const text = yield* indexedText(sql); + yield* sql` + DELETE FROM orchestration_v2_message_search WHERE rowid IN ( + SELECT rowid FROM orchestration_v2_projection_messages WHERE thread_id = ${threadId} + ) + `; + yield* sql` + INSERT INTO orchestration_v2_message_search (rowid, text) + SELECT messages.rowid, ${text("messages")} + FROM orchestration_v2_projection_messages AS messages + WHERE messages.thread_id = ${threadId} + AND ${indexedMessageCondition(sql)} + AND json_extract(messages.payload_json, '$.text') IS NOT NULL + `; +}); + /** * Refills the search index from the messages table. The index is keyed by * message rowid, so anything that may renumber or copy rows (VACUUM, a dev diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 7209626697c7e..e70024bc64780 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -150,6 +150,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray ({ feature: "thread.archive" }), "thread.snooze": () => ({ feature: "thread.snooze" }), "thread.pin": () => ({ feature: "thread.pin" }), + "thread.detach": () => ({ feature: "thread.detach" }), "thread.settle": () => ({ feature: "thread.settle" }), "thread.pull-request.link": () => ({ feature: "thread.pull_request.link" }), "thread.pull-request.watch": (command) => diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 5bb12e88f4034..f5644f2c7b281 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -85,6 +85,9 @@ vi.mock(import("../../state/peerLinks"), () => ({ peerLinkEnvironment: { readThread: {} } as never, useLinkedEnvironments: (() => new Map()) as never, })); +vi.mock(import("../../hooks/useThreadActions"), () => ({ + usePopOutThread: (() => async () => AsyncResult.success(undefined)) as never, +})); vi.mock(import("../../lib/archivedThreadsState"), () => ({ useArchivedThreadSnapshots: (() => ({ snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }], diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index fd459b4849f9a..818bb0268bbe2 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -7,6 +7,10 @@ import { SectionHeaderStatus } from "../ui/collapsible-section-header"; import { SubagentTooltipContent } from "./SubagentTooltipContent"; import { PullRequestGlyph } from "../pullRequest/pullRequestIcons"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { deriveWorkflowGroups, projectedSubagentsToRuntime, @@ -21,6 +25,7 @@ import { threadRelationshipRowStatus, orderWebThreadLineageRows, resolveMergeBackTargetThreadId, + threadPopOutAvailability, type ThreadRelationshipEdge, type ThreadRelationshipWalkRow, } from "@t3tools/client-runtime/state/thread-relationships"; @@ -54,6 +59,7 @@ import { MessagesSquareIcon, MoreHorizontalIcon, PlusIcon, + SquareArrowOutUpRightIcon, SquareIcon, UnplugIcon, } from "lucide-react"; @@ -89,6 +95,7 @@ import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadR import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow"; import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger"; import { openSideThread, resolveThreadOpenRoute } from "../../lib/sideChatPane"; +import { usePopOutThread } from "../../hooks/useThreadActions"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; @@ -238,6 +245,11 @@ function relationshipHint( ? resolve(msg("Open subagent")) : resolve(msg("Open parent agent in this chat")); } + if (edge.kind === "popped_out") { + return edge.sourceThreadId === currentThreadId + ? resolve(msg("Popped out")) + : resolve(msg("Former parent")); + } return edge.sourceThreadId === currentThreadId ? resolve(msg("Open fork in this chat")) : resolve(msg("Open parent thread in this chat")); @@ -540,6 +552,20 @@ export function ThreadRelationshipsPanel(props: { const providersByEnvironment = useEnvironmentProviders(); const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId)); const relationshipShells = useThreadRelationshipShells(ref); + const family = useEnvironmentQuery( + props.showLineage && + projection?.subagents.some( + (task) => + task.origin === "app_owned" && + task.childThreadId !== null && + !relationshipShells.some((thread) => thread.id === task.childThreadId), + ) + ? orchestrationEnvironment.threadFamily({ + environmentId: props.environmentId, + input: { threadId: props.threadId }, + }) + : null, + ); const hiddenKeys = useHiddenThreadKeys(); const hidingAnywhere = useAnyEnvironmentHiding(); const allProjects = useProjects(); @@ -577,6 +603,8 @@ export function ThreadRelationshipsPanel(props: { const mergeErrorToastId = useRef(null); const detachErrorToastId = useRef(null); const [stoppingId, setStoppingId] = useState(null); + const popOutThread = usePopOutThread(); + const [poppingOutId, setPoppingOutId] = useState(null); // Derive graphs after hooks to preserve their compiler cache. const providers = providersByEnvironment.get(props.environmentId); const derivedProviderEntries = deriveProviderInstanceEntries(providers ?? []); @@ -618,6 +646,7 @@ export function ThreadRelationshipsPanel(props: { ); const shells: ReadonlyArray = [ ...relationshipShells, + ...(family.data?.threads ?? []), ...(archivedShells ?? []), ]; const graph = deriveThreadRelationshipGraph({ threads: shells, projection }); @@ -826,6 +855,21 @@ export function ThreadRelationshipsPanel(props: { } }; + const popOut = async (childThreadId: ThreadId) => { + if (poppingOutId !== null) return; + setPoppingOutId(childThreadId); + const result = await popOutThread(scopeThreadRef(props.environmentId, childThreadId)); + setPoppingOutId(null); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: gt("Could not pop out thread"), + description: error instanceof Error ? error.message : undefined, + }); + } + }; + const stopWorkflow = async (subagentId: string) => { if (stoppingId !== null) return; setStoppingId(subagentId); @@ -859,10 +903,11 @@ export function ThreadRelationshipsPanel(props: { ? CornerLeftUpIcon : isSubagent ? BotIcon - : node?.thread?.lineage.sideChat === true - ? MessagesSquareIcon - : GitForkIcon; - + : edge.kind === "popped_out" + ? SquareArrowOutUpRightIcon + : node?.thread?.lineage.sideChat === true + ? MessagesSquareIcon + : GitForkIcon; const projectedAgent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined; const workflowGroup = projectedAgent === undefined ? undefined : workflowGroupsById.get(projectedAgent.id); @@ -879,6 +924,17 @@ export function ThreadRelationshipsPanel(props: { ["pending", "running", "waiting"].includes(agent.nativeStatus))) && agent.startedAt && ["pending", "running", "waiting"].includes(agent.status); + const popOutAvailability = + agent?.origin === "app_owned" && node?.thread != null + ? threadPopOutAvailability( + node.thread, + projected.filter( + (task) => task.origin === "app_owned" && task.childThreadId === threadId, + ), + projection?.runs, + ) + : "unsupported"; + const canPopOut = popOutAvailability !== "unsupported"; const threadTitle = relationshipThreadTitle({ title: workflowGroup?.workflow.workflowName ?? @@ -901,7 +957,7 @@ export function ThreadRelationshipsPanel(props: { workflowGroup?.workflow.status === "running" && agent?.origin === "provider_native" && providerDriver === "claudeAgent"; - const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop) + const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop || canPopOut) ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0" : ""; const project = projects.find((project) => project.id === node?.thread?.projectId); @@ -1067,33 +1123,65 @@ export function ThreadRelationshipsPanel(props: { ) : ( relationshipLink )} - {canStop && agent ? ( -
- void stopSubagent(threadId, agent)} - /> - } - label={ - <> - Stop subagent - - } - side="left" - > - {stoppingId === threadId ? ( - - ) : ( - - )} - + {(canStop && agent) || canPopOut ? ( +
+ {canPopOut ? ( + { + if (popOutAvailability !== "blocked") void popOut(threadId); + }} + /> + } + label={ + popOutAvailability === "blocked" + ? gt("Pop out to top level. Wait for it to finish or stop it first.") + : gt("Pop out to top level") + } + side="left" + > + {poppingOutId === threadId ? ( + + ) : ( + + )} + + ) : null} + {canStop && agent ? ( + void stopSubagent(threadId, agent)} + /> + } + label={ + <> + Stop subagent + + } + side="left" + > + {stoppingId === threadId ? ( + + ) : ( + + )} + + ) : null}
) : null} diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index 7c4d85340f774..54fa9a4126c48 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -90,4 +90,17 @@ describe("buildThreadActionMenuItems", () => { const items = buildThreadActionMenuItems({ ...baseState, canRename: false }); expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual(["rename"]); }); + + it("offers pop-out only for delegated children, disabled with a hint until it can run", () => { + const popOut = (state: Partial) => + buildThreadActionMenuItems({ ...baseState, ...state }).find((item) => item.id === "pop-out"); + expect(popOut({})).toBeUndefined(); + expect(popOut({ popOut: "unsupported" })).toBeUndefined(); + expect(popOut({ popOut: "available" })?.disabled).toBeUndefined(); + expect(popOut({ popOut: "blocked" })).toMatchObject({ + disabled: true, + detail: "Wait for it to finish or stop it first", + }); + expect(popOut({ popOut: "available", canOperate: false })?.disabled).toBe(true); + }); }); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 81160724f8732..934ce0ef2d367 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -1,9 +1,13 @@ import type { ContextMenuItem } from "@t3tools/contracts"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +import type { ThreadPopOutAvailability } from "@t3tools/client-runtime/state/thread-relationships"; + import { msg } from "gt-react"; import { m, type MessageResolver } from "../i18n/messages"; +const POP_OUT_BLOCKED_HINT = msg("Wait for it to finish or stop it first"); + export type ThreadActionMenuId = | "find" | "new-thread-on-branch" @@ -23,6 +27,7 @@ export type ThreadActionMenuId = | "rename" | "regenerate-title" | "mark-unread" + | "pop-out" | "share-guest" | "continue-elsewhere" | "copy" @@ -130,6 +135,7 @@ export interface ThreadActionMenuState { readonly canContinueElsewhere?: boolean; /** A No project thread with its own folder, on a server that can promote it. */ readonly canTurnIntoProject?: boolean; + readonly popOut?: ThreadPopOutAvailability; } /** Local navigation, read markers, and copying remain available to read-only clients. */ @@ -249,6 +255,18 @@ export function buildThreadActionMenuItems( ...(state.hasCompletedRun && !state.isRunning ? [{ id: "mark-unread" as const, label: resolve(msg("Mark unread")), icon: "mail-open" }] : []), + ...(state.popOut === "available" || state.popOut === "blocked" + ? [ + { + id: "pop-out" as const, + label: resolve(msg("Pop out to top level")), + icon: "square-arrow-out-up-right", + ...(state.popOut === "blocked" + ? { disabled: true, detail: resolve(POP_OUT_BLOCKED_HINT) } + : {}), + }, + ] + : []), ...(state.canShareWithGuest ? [{ id: "share-guest" as const, label: resolve(msg("Share with guest")), icon: "user-plus" }] : []), diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 4a7b2b4a3c0d7..3154fd0f5b4bc 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -112,6 +112,11 @@ const ICON_PATHS: Record ({ effects: [] as string[], latestRun: null as { readonly status: string; readonly completedAt: string | null } | null, completed: deferred(), + child: false, + delivery: "pending" as "pending" | "acknowledged", show: vi.fn< ( items: ReadonlyArray>, @@ -60,6 +62,15 @@ vi.mock("../state/entities", () => ({ worktreePath: null, runtime: null, latestRun: state.latestRun, + source: { + creationSource: "server", + status: "completed", + pendingRuntimeRequest: null, + lineage: { + parentThreadId: state.child ? "parent" : null, + relationshipToParent: state.child ? "subagent" : null, + }, + }, }), useProjects: () => [{ id: "project", environmentId: "secondary" }], })); @@ -69,6 +80,20 @@ vi.mock("../state/threadHandoff", () => ({ })); vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" })); vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } })); +vi.mock("../state/orchestration", () => ({ orchestrationEnvironment: { popOutParent: "parent" } })); +vi.mock("../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: () => async () => + AsyncResult.success({ + subagents: [ + { + childThreadId: "thread", + status: "completed", + completionDelivery: { state: state.delivery }, + }, + ], + runs: [], + }), +})); vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => async () => { recordEffect("metadata"); @@ -126,6 +151,7 @@ vi.mock("./useSettings", () => ({ })); vi.mock("./useThreadActions", () => ({ canTurnThreadIntoProject: () => false, + usePopOutThread: () => async () => AsyncResult.success(undefined), useThreadActions: () => Object.fromEntries( [ @@ -169,10 +195,25 @@ beforeEach(() => { state.effects = []; state.latestRun = null; state.completed = deferred(); + state.child = false; + state.delivery = "pending"; state.show.mockReset().mockResolvedValue(null); }); describe("thread menu permissions", () => { + it.each(["pending", "acknowledged"] as const)( + "pop-out waits for %s completion delivery", + async (delivery) => { + state.granted.add("secondary"); + state.child = true; + state.delivery = delivery; + createMenu().openMenu(position); + await vi.waitFor(() => expect(state.show).toHaveBeenCalledOnce()); + const item = state.show.mock.calls[0]![0].find((item) => item.id === "pop-out"); + expect(item).toBeDefined(); + expect(item?.disabled === true).toBe(delivery === "pending"); + }, + ); it.each(["rename", "regenerate-title", "delete", "pin", "settle", "archive"] as const)( "%s rechecks after the native menu closes", async (action) => { @@ -189,6 +230,7 @@ describe("thread menu permissions", () => { it("offers find only to a header that can open it, without task permission", async () => { createMenu().openMenu(position); + await vi.waitFor(() => expect(state.show).toHaveBeenCalledOnce()); expect(state.show.mock.calls[0]![0].some((item) => item.id === "find")).toBe(false); state.show.mockResolvedValue("find"); const onFind = vi.fn(() => recordEffect("find")); @@ -207,10 +249,11 @@ describe("thread menu mark unread", () => { ["completed", true], ["interrupted", false], ["cancelled", false], - ] as const)("a %s latest run offers Mark unread: %s", (status, offered) => { + ] as const)("a %s latest run offers Mark unread: %s", async (status, offered) => { // A stopped run never shows Done, so marking it unread would change nothing. state.latestRun = { status, completedAt: "2026-01-01T00:00:00.000Z" }; createMenu().openMenu(position); + await vi.waitFor(() => expect(state.show).toHaveBeenCalledOnce()); const items = state.show.mock.calls[0]![0]; expect(items.some((item) => item.id === "mark-unread")).toBe(offered); }); diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 644e90da72870..f0df052209e1b 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -12,7 +12,7 @@ import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/threa import { AuthOrchestrationOperateScope, type ScopedThreadRef, - type ThreadId, + ThreadId, type ContextMenuSource, } from "@t3tools/contracts"; import { useRouter } from "@tanstack/react-router"; @@ -52,10 +52,16 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping"; import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { + threadPopOutAvailability, + type ThreadPopOutAvailability, +} from "@t3tools/client-runtime/state/thread-relationships"; +import { orchestrationEnvironment } from "../state/orchestration"; +import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useCopyToClipboard } from "./useCopyToClipboard"; import { useNewThreadHandler } from "./useHandleNewThread"; import { useClientSettings } from "./useSettings"; -import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions"; +import { canTurnThreadIntoProject, usePopOutThread, useThreadActions } from "./useThreadActions"; function failureToast(title: string, error: unknown) { toastManager.add( @@ -98,6 +104,8 @@ export function useThreadActionMenu(input: { markThreadUnread, turnThreadIntoProject, } = useThreadActions(); + const popOutThread = usePopOutThread(); + const loadPopOutParent = useAtomQueryRunner(orchestrationEnvironment.popOutParent); const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { reportFailure: false, }); @@ -121,7 +129,7 @@ export function useThreadActionMenu(input: { }); /** The thread's menu as of now, and a runner for its actions. Null until the thread loads. */ - const readMenu = () => { + const readMenu = (popOut?: ThreadPopOutAvailability) => { if (threadRef === null) return null; const thread = readThreadShell(threadRef); if (!thread) return null; @@ -157,6 +165,7 @@ export function useThreadActionMenu(input: { canContinueElsewhere: threadCanStartHandoff(thread.handoff) && readCanMoveThreads(threadRef.environmentId), canTurnIntoProject: canTurnThreadIntoProject(threadRef), + ...(popOut ? { popOut } : {}), }); const run = async (action: ThreadActionMenuId) => { const api = readLocalApi(); @@ -278,6 +287,9 @@ export function useThreadActionMenu(input: { case "continue-elsewhere": openThreadHandoffDialog(threadRef); return; + case "pop-out": + await reportFailure(m(msg("Failed to pop out thread")), () => popOutThread(threadRef)); + return; case "share-guest": openGuestShareDialog(threadRef); return; @@ -379,11 +391,29 @@ export function useThreadActionMenu(input: { return { items, run }; }; + const resolvePopOut = async (ref: ScopedThreadRef) => { + const thread = readThreadShell(ref); + if (!thread) return undefined; + const popOut = threadPopOutAvailability(thread.source); + if (popOut !== "available" || thread.source.lineage.parentThreadId === null) return popOut; + const parent = await loadPopOutParent({ + environmentId: ref.environmentId, + input: { threadId: ThreadId.make(thread.source.lineage.parentThreadId) }, + }); + return parent._tag === "Success" + ? threadPopOutAvailability( + thread.source, + parent.value.subagents.filter((task) => task.childThreadId === ref.threadId), + parent.value.runs, + ) + : "blocked"; + }; + const openMenu = (position: { x: number; y: number }, source?: ContextMenuSource) => { void (async () => { const api = readLocalApi(); if (!api || threadRef === null) return; - const menu = readMenu(); + const menu = readMenu(await resolvePopOut(threadRef)); if (!menu) { failureToast( m(msg("Thread actions unavailable")), diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index bdebae98ab952..e6072fa00dc7a 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -226,6 +226,17 @@ export async function navigateAfterThreadDeletion(navigate: () => Promise) } } +export function usePopOutThread() { + const popOutThreadMutation = useOrchestrationCommand(threadEnvironment.popOut, { + reportFailure: false, + }); + return (target: ScopedThreadRef) => + popOutThreadMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId }, + }); +} + function useMarkThreadUnread() { const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 21b10e619194b..8c00eac224494 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2834,6 +2834,7 @@ "f50619195a6d0ad2": "{appName} Zugriff auf {owner} geben", "9b771434a1d169dd": "Dort ist es nicht installiert, daher verwenden GitHub-Anfragen für {repository} dein eigenes Login und dessen niedrigeres Rate-Limit.", "5d973795984549fc": "Installieren", + "934fc71948012d25": "Warte, bis er fertig ist, oder stoppe ihn zuerst", "d2ba9ab14fd2e81c": "Kopieren", "a9abbabbd3106847": "Pfad", "bd86c9f5e546d3d9": "Branch", @@ -2851,6 +2852,7 @@ "de30fdae5b3fea98": "Titel neu erzeugen", "dffd2e20f7ff5aa1": "Als ungelesen markieren", "d709a32da2c8bdac": "Auf einem anderen Rechner fortsetzen…", + "c440ceeaf0452d52": "Auf oberste Ebene verschieben", "3364346f40934e88": "Alle Projekte anzeigen", "666f3ac177c116b6": "Nach {project} filtern", "1385e2d8bd696370": "In Projekt umwandeln", @@ -2976,6 +2978,7 @@ "32e2dbf6abe8c748": "Einordnung wird gestartet…", "ce5c66ae967fd7c8": "Thread-Aktionen nicht verfügbar", "d4f0043ab9348e2c": "Dieser Thread wurde noch nicht geladen.", + "f49381c9fa02295f": "Thread konnte nicht verschoben werden", "de2cfd4a757c656a": "Archivieren ist nicht möglich, während der Anbieter aktiv ist.", "8523f86d3c21edf3": "Der Server dieser Umgebung unterstützt das Erledigen noch nicht. Aktualisiere den Server, um „Erledigen“ zu nutzen.", "876b987471f908d4": "Der Server dieser Umgebung unterstützt das Zurückstellen noch nicht. Aktualisiere den Server, um „Zurückstellen“ zu nutzen.", @@ -4408,6 +4411,8 @@ "56567586cbe00c86": "Kontextübergabe in diesem Chat öffnen", "405e76cdd602bbcf": "Subagent öffnen", "520c15dbd507b804": "Übergeordneten Agenten in diesem Chat öffnen", + "d9dd3778e54f2e9c": "Verschoben", + "b39e8916098428d1": "Früherer übergeordneter Thread", "309b160785f6c473": "Fork in diesem Chat öffnen", "6676cd4b8299663f": "Übergeordneten Thread in diesem Chat öffnen", "63e8c7a0ef0513b5": "Verwandte Threads", @@ -4421,12 +4426,15 @@ "8bcded34eb7e7f09": "Zurückführen fehlgeschlagen", "ed2fc31d28c441da": "Agentensitzung konnte nicht getrennt werden", "ba2cf3dd6de0d1a6": "Subagent konnte nicht gestoppt werden", + "84eccdaa4d8f3c01": "Thread konnte nicht verschoben werden", "1c4391ec5c411ba7": "Workflow konnte nicht gestoppt werden", "7af596fd1e3ac2a2": "In {parentTitle} zurückführen", "566239c645ce0fff": "In die Quellunterhaltung zurückführen", "1cfeabb8818f121f": "Schließe einen Lauf in diesem Fork ab, bevor du ihn zurückführst", "36cf99230450eeaf": "Diese Unterhaltung in {parentTitle} zurückführen", "bda1cc7b91e07680": "Diese Unterhaltung in ihre Quelle zurückführen", + "53f5b4a702eaf94e": "{threadTitle} auf oberste Ebene verschieben", + "ba92673b5c365937": "Auf oberste Ebene verschieben. Warte, bis er fertig ist, oder stoppe ihn zuerst.", "de93e39b51ae5ebf": "Subagent {threadTitle} stoppen", "e7b97dccb035f744": "Abstammung · {runningCount} laufen", "3f5e86e6d076a97b": "Abstammung", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e213d5a347b50..0fd07389531b9 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Give {appName} access to {owner}", "9b771434a1d169dd": "It isn't installed there, so GitHub requests for {repository} use your own login and its lower rate limit.", "5d973795984549fc": "Install", + "934fc71948012d25": "Wait for it to finish or stop it first", "d2ba9ab14fd2e81c": "Copy", "a9abbabbd3106847": "Path", "bd86c9f5e546d3d9": "Branch", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Regenerate title", "dffd2e20f7ff5aa1": "Mark unread", "d709a32da2c8bdac": "Continue on another machine…", + "c440ceeaf0452d52": "Pop out to top level", "3364346f40934e88": "Show all projects", "666f3ac177c116b6": "Filter by {project}", "1385e2d8bd696370": "Turn into project", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Starting triage…", "ce5c66ae967fd7c8": "Thread actions unavailable", "d4f0043ab9348e2c": "This thread has not loaded yet.", + "f49381c9fa02295f": "Failed to pop out thread", "de2cfd4a757c656a": "Cannot archive while the provider is active.", "8523f86d3c21edf3": "This environment's server does not support settling yet. Update the server to use Settle.", "876b987471f908d4": "This environment's server does not support snoozing yet. Update the server to use Snooze.", @@ -4407,6 +4410,8 @@ "56567586cbe00c86": "Open context transfer in this chat", "405e76cdd602bbcf": "Open subagent", "520c15dbd507b804": "Open parent agent in this chat", + "d9dd3778e54f2e9c": "Popped out", + "b39e8916098428d1": "Former parent", "309b160785f6c473": "Open fork in this chat", "6676cd4b8299663f": "Open parent thread in this chat", "63e8c7a0ef0513b5": "Related threads", @@ -4420,12 +4425,15 @@ "8bcded34eb7e7f09": "Could not merge back", "ed2fc31d28c441da": "Could not disconnect agent session", "ba2cf3dd6de0d1a6": "Could not stop subagent", + "84eccdaa4d8f3c01": "Could not pop out thread", "1c4391ec5c411ba7": "Could not stop workflow", "7af596fd1e3ac2a2": "Merge back to {parentTitle}", "566239c645ce0fff": "Merge back to source conversation", "1cfeabb8818f121f": "Complete a run in this fork before merging it back", "36cf99230450eeaf": "Merge this conversation back into {parentTitle}", "bda1cc7b91e07680": "Merge this conversation back into its source", + "53f5b4a702eaf94e": "Pop out {threadTitle} to top level", + "ba92673b5c365937": "Pop out to top level. Wait for it to finish or stop it first.", "de93e39b51ae5ebf": "Stop subagent {threadTitle}", "e7b97dccb035f744": "Lineage · {runningCount} running", "3f5e86e6d076a97b": "Lineage", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 86d3585b86fb7..db75d405895be 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Dar a {appName} acceso a {owner}", "9b771434a1d169dd": "No está instalada allí, así que las solicitudes a GitHub para {repository} usan tu propio inicio de sesión y su límite de frecuencia más bajo.", "5d973795984549fc": "Instalar", + "934fc71948012d25": "Espera a que termine o detenlo primero", "d2ba9ab14fd2e81c": "Copiar", "a9abbabbd3106847": "Ruta", "bd86c9f5e546d3d9": "Rama", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Regenerar título", "dffd2e20f7ff5aa1": "Marcar como no leído", "d709a32da2c8bdac": "Continuar en otra máquina…", + "c440ceeaf0452d52": "Mover al nivel superior", "3364346f40934e88": "Mostrar todos los proyectos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Convertir en proyecto", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Iniciando el análisis…", "ce5c66ae967fd7c8": "Acciones del hilo no disponibles", "d4f0043ab9348e2c": "Este hilo aún no se ha cargado.", + "f49381c9fa02295f": "No se pudo mover el hilo", "de2cfd4a757c656a": "No se puede archivar mientras el proveedor está activo.", "8523f86d3c21edf3": "El servidor de este entorno aún no permite resolver hilos. Actualiza el servidor para usar Resolver.", "876b987471f908d4": "El servidor de este entorno aún no permite posponer hilos. Actualiza el servidor para usar Posponer.", @@ -4405,6 +4408,8 @@ "56567586cbe00c86": "Abrir la transferencia de contexto en este chat", "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir el agente principal en este chat", + "d9dd3778e54f2e9c": "Movido", + "b39e8916098428d1": "Hilo padre anterior", "309b160785f6c473": "Abrir la bifurcación en este chat", "6676cd4b8299663f": "Abrir el hilo principal en este chat", "63e8c7a0ef0513b5": "Hilos relacionados", @@ -4418,12 +4423,15 @@ "8bcded34eb7e7f09": "No se pudo fusionar de vuelta", "ed2fc31d28c441da": "No se pudo desconectar la sesión del agente", "ba2cf3dd6de0d1a6": "No se pudo detener el subagente", + "84eccdaa4d8f3c01": "No se pudo mover el hilo", "1c4391ec5c411ba7": "No se pudo detener el flujo de trabajo", "7af596fd1e3ac2a2": "Fusionar de vuelta en {parentTitle}", "566239c645ce0fff": "Fusionar de vuelta en la conversación original", "1cfeabb8818f121f": "Completa una ejecución en esta bifurcación antes de fusionarla de vuelta", "36cf99230450eeaf": "Fusionar esta conversación de vuelta en {parentTitle}", "bda1cc7b91e07680": "Fusionar esta conversación de vuelta en su original", + "53f5b4a702eaf94e": "Mover {threadTitle} al nivel superior", + "ba92673b5c365937": "Mover al nivel superior. Espera a que termine o detenlo primero.", "de93e39b51ae5ebf": "Detener el subagente {threadTitle}", "e7b97dccb035f744": "Linaje · {runningCount} en ejecución", "3f5e86e6d076a97b": "Linaje", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 4172a5c129257..ce5d4320aa5bc 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Donner à {appName} l’accès à {owner}", "9b771434a1d169dd": "L’app n’y est pas installée, les requêtes GitHub pour {repository} utilisent donc votre propre connexion et sa limite de débit plus basse.", "5d973795984549fc": "Installer", + "934fc71948012d25": "Attendez la fin ou arrêtez-le d'abord", "d2ba9ab14fd2e81c": "Copier", "a9abbabbd3106847": "Chemin", "bd86c9f5e546d3d9": "Branche", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Régénérer le titre", "dffd2e20f7ff5aa1": "Marquer comme non lu", "d709a32da2c8bdac": "Continuer sur une autre machine…", + "c440ceeaf0452d52": "Déplacer au premier niveau", "3364346f40934e88": "Afficher tous les projets", "666f3ac177c116b6": "Filtrer par {project}", "1385e2d8bd696370": "Transformer en projet", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Lancement du tri…", "ce5c66ae967fd7c8": "Actions sur le fil indisponibles", "d4f0043ab9348e2c": "Ce fil n’est pas encore chargé.", + "f49381c9fa02295f": "Impossible de déplacer le fil", "de2cfd4a757c656a": "Impossible d’archiver tant que le fournisseur est actif.", "8523f86d3c21edf3": "Le serveur de cet environnement ne permet pas encore de clore les fils. Mettez à jour le serveur pour utiliser Clore.", "876b987471f908d4": "Le serveur de cet environnement ne permet pas encore de reporter les fils. Mettez à jour le serveur pour utiliser Reporter.", @@ -4406,6 +4409,8 @@ "56567586cbe00c86": "Ouvrir le transfert de contexte dans cette discussion", "405e76cdd602bbcf": "Ouvrir le sous-agent", "520c15dbd507b804": "Ouvrir l’agent parent dans cette discussion", + "d9dd3778e54f2e9c": "Déplacé", + "b39e8916098428d1": "Ancien fil parent", "309b160785f6c473": "Ouvrir le fork dans cette discussion", "6676cd4b8299663f": "Ouvrir le fil parent dans cette discussion", "63e8c7a0ef0513b5": "Fils liés", @@ -4419,12 +4424,15 @@ "8bcded34eb7e7f09": "Impossible de fusionner en retour", "ed2fc31d28c441da": "Impossible de déconnecter la session de l’agent", "ba2cf3dd6de0d1a6": "Impossible d’arrêter le sous-agent", + "84eccdaa4d8f3c01": "Impossible de déplacer le fil", "1c4391ec5c411ba7": "Impossible d’arrêter le workflow", "7af596fd1e3ac2a2": "Fusionner dans {parentTitle}", "566239c645ce0fff": "Fusionner dans la conversation source", "1cfeabb8818f121f": "Terminez une exécution dans ce fork avant de le fusionner en retour", "36cf99230450eeaf": "Fusionner cette conversation dans {parentTitle}", "bda1cc7b91e07680": "Fusionner cette conversation dans sa source", + "53f5b4a702eaf94e": "Déplacer {threadTitle} au premier niveau", + "ba92673b5c365937": "Déplacer au premier niveau. Attendez la fin ou arrêtez-le d'abord.", "de93e39b51ae5ebf": "Arrêter le sous-agent {threadTitle}", "e7b97dccb035f744": "Lignée · {runningCount} en cours", "3f5e86e6d076a97b": "Lignée", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 31c47209b4eb5..777957daeb7bd 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2831,6 +2831,7 @@ "f50619195a6d0ad2": "{appName} に {owner} へのアクセスを許可", "9b771434a1d169dd": "そこにはインストールされていないため、{repository} への GitHub リクエストにはあなた自身のログインと、その低いレート制限が使われます。", "5d973795984549fc": "インストール", + "934fc71948012d25": "完了するまで待つか、先に停止してください", "d2ba9ab14fd2e81c": "コピー", "a9abbabbd3106847": "パス", "bd86c9f5e546d3d9": "ブランチ", @@ -2848,6 +2849,7 @@ "de30fdae5b3fea98": "タイトルを再生成", "dffd2e20f7ff5aa1": "未読にする", "d709a32da2c8bdac": "別のマシンで続ける…", + "c440ceeaf0452d52": "最上位に移動", "3364346f40934e88": "すべてのプロジェクトを表示", "666f3ac177c116b6": "{project} で絞り込み", "1385e2d8bd696370": "プロジェクトに変換", @@ -2973,6 +2975,7 @@ "32e2dbf6abe8c748": "トリアージを開始しています…", "ce5c66ae967fd7c8": "スレッドの操作を利用できません", "d4f0043ab9348e2c": "このスレッドはまだ読み込まれていません。", + "f49381c9fa02295f": "スレッドを移動できませんでした", "de2cfd4a757c656a": "プロバイダーがアクティブな間はアーカイブできません。", "8523f86d3c21edf3": "この環境のサーバーはまだ対応済みをサポートしていません。対応済みを使うにはサーバーを更新してください。", "876b987471f908d4": "この環境のサーバーはまだスヌーズをサポートしていません。スヌーズを使うにはサーバーを更新してください。", @@ -4395,6 +4398,8 @@ "56567586cbe00c86": "このチャットでコンテキストの引き継ぎを開く", "405e76cdd602bbcf": "サブエージェントを開く", "520c15dbd507b804": "このチャットで親エージェントを開く", + "d9dd3778e54f2e9c": "移動済み", + "b39e8916098428d1": "以前の親スレッド", "309b160785f6c473": "このチャットでフォークを開く", "6676cd4b8299663f": "このチャットで親スレッドを開く", "63e8c7a0ef0513b5": "関連するスレッド", @@ -4408,12 +4413,15 @@ "8bcded34eb7e7f09": "元に統合できませんでした", "ed2fc31d28c441da": "エージェントのセッションを切断できませんでした", "ba2cf3dd6de0d1a6": "サブエージェントを停止できませんでした", + "84eccdaa4d8f3c01": "スレッドを移動できませんでした", "1c4391ec5c411ba7": "ワークフローを停止できませんでした", "7af596fd1e3ac2a2": "{parentTitle} に統合", "566239c645ce0fff": "元の会話に統合", "1cfeabb8818f121f": "統合する前に、このフォークで実行を 1 回完了してください", "36cf99230450eeaf": "この会話を {parentTitle} に統合", "bda1cc7b91e07680": "この会話を元の会話に統合", + "53f5b4a702eaf94e": "{threadTitle}を最上位に移動", + "ba92673b5c365937": "最上位に移動。完了するまで待つか、先に停止してください。", "de93e39b51ae5ebf": "サブエージェント {threadTitle} を停止", "e7b97dccb035f744": "系譜 · {runningCount} 件実行中", "3f5e86e6d076a97b": "系譜", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index b26bacf20b181..11889c5bafbab 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2832,6 +2832,7 @@ "f50619195a6d0ad2": "{appName}에 {owner} 액세스 권한 부여", "9b771434a1d169dd": "그곳에 설치되어 있지 않아 {repository}에 대한 GitHub 요청에 내 로그인과 그보다 낮은 속도 제한이 적용됩니다.", "5d973795984549fc": "설치", + "934fc71948012d25": "완료될 때까지 기다리거나 먼저 중지하세요", "d2ba9ab14fd2e81c": "복사", "a9abbabbd3106847": "경로", "bd86c9f5e546d3d9": "브랜치", @@ -2849,6 +2850,7 @@ "de30fdae5b3fea98": "제목 다시 생성", "dffd2e20f7ff5aa1": "읽지 않음으로 표시", "d709a32da2c8bdac": "다른 머신에서 계속…", + "c440ceeaf0452d52": "최상위로 이동", "3364346f40934e88": "모든 프로젝트 표시", "666f3ac177c116b6": "{project}(으)로 필터", "1385e2d8bd696370": "프로젝트로 전환", @@ -2974,6 +2976,7 @@ "32e2dbf6abe8c748": "분류를 시작하는 중…", "ce5c66ae967fd7c8": "스레드 작업을 사용할 수 없음", "d4f0043ab9348e2c": "이 스레드를 아직 불러오지 않았습니다.", + "f49381c9fa02295f": "스레드를 이동하지 못했습니다", "de2cfd4a757c656a": "제공자가 활성 상태인 동안에는 보관할 수 없습니다.", "8523f86d3c21edf3": "이 환경의 서버는 아직 정리를 지원하지 않습니다. 정리를 사용하려면 서버를 업데이트하세요.", "876b987471f908d4": "이 환경의 서버는 아직 다시 알림을 지원하지 않습니다. 다시 알림을 사용하려면 서버를 업데이트하세요.", @@ -4392,6 +4395,8 @@ "56567586cbe00c86": "이 채팅에서 컨텍스트 전달 열기", "405e76cdd602bbcf": "서브에이전트 열기", "520c15dbd507b804": "이 채팅에서 상위 에이전트 열기", + "d9dd3778e54f2e9c": "이동됨", + "b39e8916098428d1": "이전 상위 스레드", "309b160785f6c473": "이 채팅에서 포크 열기", "6676cd4b8299663f": "이 채팅에서 상위 스레드 열기", "63e8c7a0ef0513b5": "관련 스레드", @@ -4405,12 +4410,15 @@ "8bcded34eb7e7f09": "다시 병합할 수 없습니다", "ed2fc31d28c441da": "에이전트 세션 연결을 끊을 수 없습니다", "ba2cf3dd6de0d1a6": "서브에이전트를 중지할 수 없습니다", + "84eccdaa4d8f3c01": "스레드를 이동하지 못했습니다", "1c4391ec5c411ba7": "워크플로를 중지할 수 없습니다", "7af596fd1e3ac2a2": "{parentTitle}(으)로 다시 병합", "566239c645ce0fff": "원본 대화로 다시 병합", "1cfeabb8818f121f": "다시 병합하기 전에 이 포크에서 실행을 완료하세요", "36cf99230450eeaf": "이 대화를 {parentTitle}(으)로 다시 병합", "bda1cc7b91e07680": "이 대화를 원본으로 다시 병합", + "53f5b4a702eaf94e": "{threadTitle}을 최상위로 이동", + "ba92673b5c365937": "최상위로 이동. 완료될 때까지 기다리거나 먼저 중지하세요.", "de93e39b51ae5ebf": "서브에이전트 {threadTitle} 중지", "e7b97dccb035f744": "계보 · {runningCount}개 실행 중", "3f5e86e6d076a97b": "계보", diff --git a/apps/web/src/i18n/translations/pl.json b/apps/web/src/i18n/translations/pl.json index 4dda051188ca4..324ec5fbaaf42 100644 --- a/apps/web/src/i18n/translations/pl.json +++ b/apps/web/src/i18n/translations/pl.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Przyznaj aplikacji {appName} dostęp do {owner}", "9b771434a1d169dd": "Nie jest tam zainstalowana, więc żądania GitHub dla {repository} korzystają z Twojego własnego loginu i jego niższego limitu żądań.", "5d973795984549fc": "Zainstaluj", + "934fc71948012d25": "Poczekaj, aż się zakończy, lub najpierw go zatrzymaj", "d2ba9ab14fd2e81c": "Kopiuj", "a9abbabbd3106847": "Ścieżka", "bd86c9f5e546d3d9": "Gałąź", @@ -2974,6 +2975,7 @@ "32e2dbf6abe8c748": "Rozpoczynanie triażu…", "ce5c66ae967fd7c8": "Działania na wątkach niedostępne", "d4f0043ab9348e2c": "Ten wątek nie został jeszcze wczytany.", + "f49381c9fa02295f": "Nie udało się wydzielić wątku", "de2cfd4a757c656a": "Nie można archiwizować, gdy dostawca jest aktywny.", "8523f86d3c21edf3": "Serwer tego środowiska nie obsługuje jeszcze dokańczania. Zaktualizuj serwer, aby użyć Dokończ.", "876b987471f908d4": "Serwer tego środowiska nie obsługuje jeszcze odraczania. Zaktualizuj serwer, aby użyć Odrocz.", @@ -4379,6 +4381,8 @@ "56567586cbe00c86": "Otwórz transfer kontekstu w tym czacie", "405e76cdd602bbcf": "Otwórz subagenta", "520c15dbd507b804": "Otwórz agenta nadrzędnego w tym czacie", + "d9dd3778e54f2e9c": "Wydzielony", + "b39e8916098428d1": "Dawny wątek nadrzędny", "309b160785f6c473": "Otwórz fork w tym czacie", "6676cd4b8299663f": "Otwórz wątek nadrzędny w tym czacie", "63e8c7a0ef0513b5": "Powiązane wątki", @@ -4392,12 +4396,15 @@ "8bcded34eb7e7f09": "Nie udało się scalić z powrotem", "ed2fc31d28c441da": "Nie udało się rozłączyć sesji agenta", "ba2cf3dd6de0d1a6": "Nie udało się zatrzymać subagenta", + "84eccdaa4d8f3c01": "Nie można wydzielić wątku", "1c4391ec5c411ba7": "Nie udało się zatrzymać przepływu pracy", "7af596fd1e3ac2a2": "Scal z powrotem do {parentTitle}", "566239c645ce0fff": "Scal z powrotem do rozmowy źródłowej", "1cfeabb8818f121f": "Zakończ uruchomienie w tym forku przed scaleniem z powrotem", "36cf99230450eeaf": "Scal tę rozmowę z powrotem z {parentTitle}", "bda1cc7b91e07680": "Scal tę rozmowę z powrotem z jej źródłem", + "53f5b4a702eaf94e": "Wydziel {threadTitle} na najwyższy poziom", + "ba92673b5c365937": "Wydziel na najwyższy poziom. Poczekaj, aż się zakończy, lub najpierw go zatrzymaj.", "de93e39b51ae5ebf": "Zatrzymaj subagenta {threadTitle}", "e7b97dccb035f744": "Pochodzenie · {runningCount} w toku", "3f5e86e6d076a97b": "Pochodzenie", @@ -13243,6 +13250,7 @@ "b0fd34adb523d69c": "Upuszczono {item} na {target}.", "f8dbc1bf18416476": "{item} wrócił na swoje miejsce.", "d709a32da2c8bdac": "Kontynuuj na innym komputerze…", + "c440ceeaf0452d52": "Wydziel na najwyższy poziom", "4c31fb11f7b5721e": "Przenoszenie na {machine}", "73a8d7a040b51158": "Ciąg dalszy na {machine}", "8f46ca44db8b107b": "Przeniesienie na {machine} po zakończeniu tej tury", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 2b4586bbb66c6..b469419c90141 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Dar ao {appName} acesso a {owner}", "9b771434a1d169dd": "Ele não está instalado lá, então as solicitações ao GitHub para {repository} usam seu próprio login e o limite de taxa menor dele.", "5d973795984549fc": "Instalar", + "934fc71948012d25": "Espere terminar ou pare primeiro", "d2ba9ab14fd2e81c": "Copiar", "a9abbabbd3106847": "Caminho", "bd86c9f5e546d3d9": "Branch", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Gerar título novamente", "dffd2e20f7ff5aa1": "Marcar como não lida", "d709a32da2c8bdac": "Continuar em outra máquina…", + "c440ceeaf0452d52": "Mover para o nível superior", "3364346f40934e88": "Mostrar todos os projetos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Transformar em projeto", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Iniciando a triagem…", "ce5c66ae967fd7c8": "Ações de thread indisponíveis", "d4f0043ab9348e2c": "Esta thread ainda não foi carregada.", + "f49381c9fa02295f": "Falha ao mover a conversa", "de2cfd4a757c656a": "Não é possível arquivar enquanto o provedor está ativo.", "8523f86d3c21edf3": "O servidor deste ambiente ainda não permite concluir threads. Atualize o servidor para usar Concluir.", "876b987471f908d4": "O servidor deste ambiente ainda não permite adiar threads. Atualize o servidor para usar Adiar.", @@ -4405,6 +4408,8 @@ "56567586cbe00c86": "Abrir a transferência de contexto neste chat", "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir o agente principal neste chat", + "d9dd3778e54f2e9c": "Movida", + "b39e8916098428d1": "Conversa principal anterior", "309b160785f6c473": "Abrir o fork neste chat", "6676cd4b8299663f": "Abrir a thread principal neste chat", "63e8c7a0ef0513b5": "Threads relacionadas", @@ -4418,12 +4423,15 @@ "8bcded34eb7e7f09": "Não foi possível mesclar de volta", "ed2fc31d28c441da": "Não foi possível desconectar a sessão do agente", "ba2cf3dd6de0d1a6": "Não foi possível parar o subagente", + "84eccdaa4d8f3c01": "Não foi possível mover a conversa", "1c4391ec5c411ba7": "Não foi possível parar o workflow", "7af596fd1e3ac2a2": "Mesclar de volta em {parentTitle}", "566239c645ce0fff": "Mesclar de volta na conversa de origem", "1cfeabb8818f121f": "Conclua uma execução neste fork antes de mesclá-lo de volta", "36cf99230450eeaf": "Mesclar esta conversa de volta em {parentTitle}", "bda1cc7b91e07680": "Mesclar esta conversa de volta na origem", + "53f5b4a702eaf94e": "Mover {threadTitle} para o nível superior", + "ba92673b5c365937": "Mover para o nível superior. Espere terminar ou pare primeiro.", "de93e39b51ae5ebf": "Parar o subagente {threadTitle}", "e7b97dccb035f744": "Linhagem · {runningCount} em execução", "3f5e86e6d076a97b": "Linhagem", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 18b16a09ab9a0..dd5fcf8e4c4b9 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Дайте {appName} доступ к {owner}", "9b771434a1d169dd": "Оно там не установлено, поэтому запросы к GitHub для {repository} идут от вашего логина с более низким лимитом.", "5d973795984549fc": "Установить", + "934fc71948012d25": "Дождитесь завершения или сначала остановите", "d2ba9ab14fd2e81c": "Копировать", "a9abbabbd3106847": "Путь", "bd86c9f5e546d3d9": "Ветку", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Сгенерировать название заново", "dffd2e20f7ff5aa1": "Отметить непрочитанным", "d709a32da2c8bdac": "Продолжить на другой машине…", + "c440ceeaf0452d52": "Переместить на верхний уровень", "3364346f40934e88": "Показать все проекты", "666f3ac177c116b6": "Фильтр: {project}", "1385e2d8bd696370": "Превратить в проект", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Запуск разбора проблемы…", "ce5c66ae967fd7c8": "Действия с тредом недоступны", "d4f0043ab9348e2c": "Этот тред ещё не загрузился.", + "f49381c9fa02295f": "Не удалось переместить ветку", "de2cfd4a757c656a": "Нельзя архивировать, пока провайдер активен.", "8523f86d3c21edf3": "Сервер этого окружения пока не поддерживает разбор тредов. Обновите сервер, чтобы использовать «Разобрать».", "876b987471f908d4": "Сервер этого окружения пока не поддерживает откладывание. Обновите сервер, чтобы использовать «Отложить».", @@ -4405,6 +4408,8 @@ "56567586cbe00c86": "Открыть передачу контекста в этом чате", "405e76cdd602bbcf": "Открыть субагента", "520c15dbd507b804": "Открыть родительского агента в этом чате", + "d9dd3778e54f2e9c": "Перемещена", + "b39e8916098428d1": "Бывшая родительская ветка", "309b160785f6c473": "Открыть ответвление в этом чате", "6676cd4b8299663f": "Открыть родительский тред в этом чате", "63e8c7a0ef0513b5": "Связанные треды", @@ -4418,12 +4423,15 @@ "8bcded34eb7e7f09": "Не удалось влить обратно", "ed2fc31d28c441da": "Не удалось отключить сеанс агента", "ba2cf3dd6de0d1a6": "Не удалось остановить субагента", + "84eccdaa4d8f3c01": "Не удалось переместить ветку", "1c4391ec5c411ba7": "Не удалось остановить воркфлоу", "7af596fd1e3ac2a2": "Влить обратно в {parentTitle}", "566239c645ce0fff": "Влить обратно в исходную беседу", "1cfeabb8818f121f": "Завершите запуск в этом ответвлении, прежде чем вливать его обратно", "36cf99230450eeaf": "Влить эту беседу обратно в {parentTitle}", "bda1cc7b91e07680": "Влить эту беседу обратно в исходную", + "53f5b4a702eaf94e": "Переместить {threadTitle} на верхний уровень", + "ba92673b5c365937": "Переместить на верхний уровень. Дождитесь завершения или сначала остановите.", "de93e39b51ae5ebf": "Остановить субагента {threadTitle}", "e7b97dccb035f744": "Родословная · выполняется: {runningCount}", "3f5e86e6d076a97b": "Родословная", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d0c3e0ec2eea4..2fea9ce1350df 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2833,6 +2833,7 @@ "f50619195a6d0ad2": "Ge {appName} åtkomst till {owner}", "9b771434a1d169dd": "Den är inte installerad där, så GitHub-begäranden för {repository} använder din egen inloggning och dess lägre hastighetsgräns.", "5d973795984549fc": "Installera", + "934fc71948012d25": "Vänta tills den är klar eller stoppa den först", "d2ba9ab14fd2e81c": "Kopiera", "a9abbabbd3106847": "Sökväg", "bd86c9f5e546d3d9": "Gren", @@ -2850,6 +2851,7 @@ "de30fdae5b3fea98": "Generera om titel", "dffd2e20f7ff5aa1": "Markera som oläst", "d709a32da2c8bdac": "Fortsätt på en annan dator…", + "c440ceeaf0452d52": "Flytta till översta nivån", "3364346f40934e88": "Visa alla projekt", "666f3ac177c116b6": "Filtrera efter {project}", "1385e2d8bd696370": "Gör om till projekt", @@ -2975,6 +2977,7 @@ "32e2dbf6abe8c748": "Startar felsökning…", "ce5c66ae967fd7c8": "Trådåtgärder är inte tillgängliga", "d4f0043ab9348e2c": "Den här tråden har inte lästs in än.", + "f49381c9fa02295f": "Kunde inte flytta tråden", "de2cfd4a757c656a": "Kan inte arkivera medan leverantören är aktiv.", "8523f86d3c21edf3": "Den här miljöns server stöder inte markering som klar än. Uppdatera servern för att använda Markera som klar.", "876b987471f908d4": "Den här miljöns server stöder inte snooze än. Uppdatera servern för att använda Snooza.", @@ -4406,6 +4409,8 @@ "56567586cbe00c86": "Öppna kontextöverföringen i den här chatten", "405e76cdd602bbcf": "Öppna subagent", "520c15dbd507b804": "Öppna den överordnade agenten i den här chatten", + "d9dd3778e54f2e9c": "Flyttad", + "b39e8916098428d1": "Tidigare överordnad tråd", "309b160785f6c473": "Öppna forken i den här chatten", "6676cd4b8299663f": "Öppna den överordnade tråden i den här chatten", "63e8c7a0ef0513b5": "Relaterade trådar", @@ -4419,12 +4424,15 @@ "8bcded34eb7e7f09": "Kunde inte merga tillbaka", "ed2fc31d28c441da": "Kunde inte koppla från agentsessionen", "ba2cf3dd6de0d1a6": "Kunde inte stoppa subagenten", + "84eccdaa4d8f3c01": "Kunde inte flytta tråden", "1c4391ec5c411ba7": "Kunde inte stoppa arbetsflödet", "7af596fd1e3ac2a2": "Merga tillbaka till {parentTitle}", "566239c645ce0fff": "Merga tillbaka till källkonversationen", "1cfeabb8818f121f": "Slutför en körning i den här forken innan du mergar tillbaka den", "36cf99230450eeaf": "Merga tillbaka den här konversationen till {parentTitle}", "bda1cc7b91e07680": "Merga tillbaka den här konversationen till källan", + "53f5b4a702eaf94e": "Flytta {threadTitle} till översta nivån", + "ba92673b5c365937": "Flytta till översta nivån. Vänta tills den är klar eller stoppa den först.", "de93e39b51ae5ebf": "Stoppa subagenten {threadTitle}", "e7b97dccb035f744": "Härkomst · {runningCount} körs", "3f5e86e6d076a97b": "Härkomst", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index f247fe77666fe..2c73f704e2f0d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2837,6 +2837,7 @@ "f50619195a6d0ad2": "授予 {appName} 访问 {owner} 的权限", "9b771434a1d169dd": "该处尚未安装此应用,因此对 {repository} 的 GitHub 请求会使用你自己的登录身份,受较低的速率限制。", "5d973795984549fc": "安装", + "934fc71948012d25": "请等待完成,或先停止", "d2ba9ab14fd2e81c": "复制", "a9abbabbd3106847": "路径", "bd86c9f5e546d3d9": "分支", @@ -2854,6 +2855,7 @@ "de30fdae5b3fea98": "重新生成标题", "dffd2e20f7ff5aa1": "标为未读", "d709a32da2c8bdac": "在另一台机器上继续…", + "c440ceeaf0452d52": "移至顶层", "3364346f40934e88": "显示所有项目", "666f3ac177c116b6": "按 {project} 筛选", "1385e2d8bd696370": "转换为项目", @@ -2979,6 +2981,7 @@ "32e2dbf6abe8c748": "正在开始问题排查…", "ce5c66ae967fd7c8": "会话操作不可用", "d4f0043ab9348e2c": "此会话尚未加载。", + "f49381c9fa02295f": "移出会话失败", "de2cfd4a757c656a": "提供方仍在运行时无法归档。", "8523f86d3c21edf3": "此环境的服务器尚不支持收尾。请更新服务器后再使用“收尾”。", "876b987471f908d4": "此环境的服务器尚不支持暂缓。请更新服务器后再使用“暂缓”。", @@ -4411,6 +4414,8 @@ "56567586cbe00c86": "在此对话中打开上下文转移", "405e76cdd602bbcf": "打开子智能体", "520c15dbd507b804": "在此对话中打开父智能体", + "d9dd3778e54f2e9c": "已移出", + "b39e8916098428d1": "原父会话", "309b160785f6c473": "在此对话中打开分叉", "6676cd4b8299663f": "在此对话中打开父会话", "63e8c7a0ef0513b5": "相关会话", @@ -4424,12 +4429,15 @@ "8bcded34eb7e7f09": "无法合并回去", "ed2fc31d28c441da": "无法断开智能体会话", "ba2cf3dd6de0d1a6": "无法停止子智能体", + "84eccdaa4d8f3c01": "无法移出会话", "1c4391ec5c411ba7": "无法停止工作流", "7af596fd1e3ac2a2": "合并回 {parentTitle}", "566239c645ce0fff": "合并回原对话", "1cfeabb8818f121f": "请先在这个分叉中完成一次运行,再合并回去", "36cf99230450eeaf": "将此对话合并回 {parentTitle}", "bda1cc7b91e07680": "把这段对话合并回原对话", + "53f5b4a702eaf94e": "将 {threadTitle} 移至顶层", + "ba92673b5c365937": "移至顶层。请等待完成,或先停止。", "de93e39b51ae5ebf": "停止子智能体 {threadTitle}", "e7b97dccb035f744": "会话关系 · {runningCount} 个运行中", "3f5e86e6d076a97b": "会话关系", diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index af437e4a3bb8e..f53ca2a030c37 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -74,6 +74,7 @@ The server automatically links open PRs matching an unsettled thread's branch. O - **Usage limits**: When a provider hits a rate/usage limit (**Limited**), press **Resume** in an empty composer after reset (or send a message). If the provider reports a reset time, choose **Resume at reset** or **Snooze until reset**—or enable defaults in **Settings → Threads** (**Resume after usage limits** / **Snooze until limits reset**). - **Subagents**: Follow delegated work from the conversation card or **Agents**. Stopping a parent thread also stops its delegated subagents. Subagents started internally by the provider are read-only; message the parent thread instead. +- **Pop out a subagent**: Choose **Pop out to top level** from a delegated thread's menu or its row in the parent's **Lineage** (on mobile, in the thread header; under the overflow menu on Android). It keeps its history, model, and folder, gets its own sidebar row, and no longer reports to or stops with the parent. Available once the delegated task has finished and its result reached the parent; stop it first if you can't wait. - **Running dev servers** (web/desktop): The thread details card lists local servers started by the thread's terminals or Claude agent with their ports. Click one to open it in the browser panel, or **Stop** to end it (macOS/Linux only). - **Customize thread details**: Right-click the thread details card or open **Settings → Appearance → Thread details** to show/hide rows. diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index f0b168ee72ab4..3fd7450096c95 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -719,6 +719,17 @@ export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread" }); }); +export type PopOutThreadInput = ThreadCommandInput; +export const popOutThread = Effect.fn("EnvironmentCommands.popOutThread")(function* ( + input: PopOutThreadInput, +) { + return yield* dispatch({ + type: "thread.detach", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }); +}); + export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")( function* (input: UpdateThreadMetadataInput) { const commandId = yield* allocateCommandId(input); diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 2c70c8d54027f..704b6c4647735 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -255,6 +255,12 @@ export function createOrchestrationEnvironmentAtoms( staleTimeMs: 0, idleTtlMs: 0, }), + popOutParent: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:orchestration:pop-out-parent", + tag: ORCHESTRATION_V2_WS_METHODS.getThreadProjection, + staleTimeMs: 0, + idleTtlMs: 0, + }), // Read right before deleting a worktree, so never served from cache. worktreeThreadIds: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:worktree-thread-ids", diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 96d35a999b5e9..74528cb4b2d9f 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -325,6 +325,7 @@ export function applyOrchestrationV2ProjectionEvent( case "thread.unsettled": case "thread.snoozed": case "thread.unsnoozed": + case "thread.detached": case "thread.auto-settle-set": case "thread.pinned": case "thread.unpinned": diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 3b3d8d903caeb..6b2e4fdacd175 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -37,6 +37,7 @@ import { forkSideChat, forkThreadFromRun, markThreadUnread, + popOutThread, mergeThreadBack, promoteQueuedRun, resumeThreadQueue, @@ -343,6 +344,12 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency, }), + popOut: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:pop-out", + execute: popOutThread, + scheduler, + concurrency, + }), updateMetadata: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:update-metadata", execute: updateThreadMetadata, @@ -540,6 +547,7 @@ export function createThreadEnvironmentAtoms( }; const commands = { ...sent, + popOut: rowAction(sent.popOut), delete: rowAction(sent.delete), archive: rowAction(sent.archive), unarchive: rowAction(sent.unarchive), diff --git a/packages/client-runtime/src/state/threadRelationships.test.ts b/packages/client-runtime/src/state/threadRelationships.test.ts index 90dc68c21dd82..a88eae25e25ad 100644 --- a/packages/client-runtime/src/state/threadRelationships.test.ts +++ b/packages/client-runtime/src/state/threadRelationships.test.ts @@ -7,6 +7,7 @@ import { immediateThreadRelationships, orderWebThreadLineageRows, resolveMergeBackTargetThreadId, + threadPopOutAvailability, threadRelationshipRowStatus, } from "./threadRelationships.ts"; @@ -207,6 +208,88 @@ describe("thread relationships", () => { ); }); + it("shows a popped-out child to its former parent instead of as its subagent", () => { + const parent = ThreadId.make("thread-parent"); + const child = ThreadId.make("thread-popped"); + const graph = deriveThreadRelationshipGraph({ + threads: [ + { + id: parent, + status: "completed", + forkedFrom: null, + lineage: { rootThreadId: parent, parentThreadId: null, relationshipToParent: null }, + }, + { + id: child, + status: "running", + forkedFrom: { type: "node", nodeId: "task" }, + lineage: { + rootThreadId: parent, + parentThreadId: null, + relationshipToParent: null, + detachedFrom: { threadId: parent }, + }, + }, + ] as never, + projection: { + thread: { id: parent }, + subagents: [{ childThreadId: child, status: "completed" }], + contextTransfers: [{ sourceThreadId: parent, targetThreadId: child, status: "consumed" }], + } as never, + }); + const edgeTo = (from: ThreadId) => + immediateThreadRelationships(graph, from).map((row) => [row.edge.kind, row.edge.status]); + expect(edgeTo(parent)).toEqual([["popped_out", "running"]]); + expect(edgeTo(child)).toEqual([["popped_out", "running"]]); + expect(graph.edges.some((edge) => edge.kind === "subagent")).toBe(false); + }); + + it.each([ + ["an idle delegated child whose tasks reported", {}, [], "available"], + ["a running child", { status: "running" }, [], "blocked"], + ["a child waiting on a question", { pendingRuntimeRequest: {} }, [], "blocked"], + [ + "a child whose result has not reached its parent", + {}, + [{ status: "completed", completionDelivery: { state: "pending" } }], + "blocked", + ], + ["a provider's own subagent", { creationSource: "provider" }, [], "unsupported"], + [ + "a terminal task whose spawning run is still live", + {}, + [{ status: "completed", runId: "parent-run" }], + "blocked", + ], + [ + "a top-level thread", + { lineage: { parentThreadId: null, relationshipToParent: null } }, + [], + "unsupported", + ], + ])("pop-out for %s", (_name, overrides, tasks, expected) => { + const thread = { + creationSource: "server", + lineage: { + parentThreadId: "parent", + relationshipToParent: "subagent", + rootThreadId: "parent", + }, + activityRunStatus: null, + status: "idle", + pendingRuntimeRequest: null, + pendingBackgroundTasks: [], + ...overrides, + }; + expect( + threadPopOutAvailability( + thread as never, + tasks as never, + [{ id: "parent-run", status: "running" }] as never, + ), + ).toBe(expected); + }); + it("keeps the live shell when an archived snapshot contains the same thread id", () => { const parent = ThreadId.make("thread-parent"); const staleParent = ThreadId.make("thread-stale-parent"); diff --git a/packages/client-runtime/src/state/threadRelationships.ts b/packages/client-runtime/src/state/threadRelationships.ts index 26ff658a5191b..a546ee6476ef9 100644 --- a/packages/client-runtime/src/state/threadRelationships.ts +++ b/packages/client-runtime/src/state/threadRelationships.ts @@ -1,5 +1,10 @@ import { + isDelegatedChildThread, + isDelegatedTaskReported, + isLiveSubagentShell, isOrchestrationV2WorkActive, + type OrchestrationV2Subagent, + type OrchestrationV2Run, type OrchestrationV2ThreadShell, type ThreadId, } from "@t3tools/contracts"; @@ -7,7 +12,7 @@ import * as DateTime from "effect/DateTime"; import type { ThreadStructure } from "./models.ts"; -export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer"; +export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "popped_out" | "transfer"; export interface ThreadRelationshipNode { readonly threadId: ThreadId; @@ -87,6 +92,16 @@ export function deriveThreadRelationshipGraph(input: { ? [...threads, { ...selectedThread, activityRunStatus: null, status: null }] : threads; for (const thread of lineageThreads) { + const detachedFrom = thread.lineage.detachedFrom?.threadId; + if (detachedFrom !== undefined) { + addEdge({ + sourceThreadId: detachedFrom, + targetThreadId: thread.id, + kind: "popped_out", + status: thread.activityRunStatus ?? thread.status, + }); + continue; + } const parentThreadId = thread.forkedFrom?.type === "run" ? thread.forkedFrom.threadId @@ -105,6 +120,7 @@ export function deriveThreadRelationshipGraph(input: { for (const subagent of input.projection.subagents) { if (subagent.childThreadId === null) continue; const child = threadsById.get(subagent.childThreadId); + if (child?.lineage.detachedFrom?.threadId === ownerThreadId) continue; addEdge({ sourceThreadId: ownerThreadId, targetThreadId: subagent.childThreadId, @@ -206,3 +222,41 @@ export function orderWebThreadLineageRows(input: { return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0; }); } + +export type ThreadPopOutAvailability = "unsupported" | "blocked" | "available"; + +/** + * Whether a delegated child can be popped out to top level: once it is idle and every task it was + * given has reported to its parent. The server re-checks against the parent's records. + */ +export function threadPopOutAvailability( + thread: Pick< + OrchestrationV2ThreadShell, + | "lineage" + | "creationSource" + | "activityRunStatus" + | "status" + | "pendingRuntimeRequest" + | "pendingBackgroundTasks" + >, + tasks: ReadonlyArray< + Pick + > = [], + runs: ReadonlyArray> = [], +): ThreadPopOutAvailability { + if (!isDelegatedChildThread(thread)) return "unsupported"; + return isLiveSubagentShell(thread) || + tasks.some( + (task) => + !isDelegatedTaskReported( + task, + runs.some( + (run) => + run.id === task.runId && + (run.status === "preparing" || run.status === "starting" || run.status === "running"), + ), + ), + ) + ? "blocked" + : "available"; +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index d03ddb8f57783..76d75d345efd8 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -237,6 +237,8 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({ sideChat: Schema.optional(Schema.Boolean), /** An agent step of a workflow run, which the thread's `workflowRun` names. */ workflowStep: Schema.optional(Schema.Boolean), + /** The parent a delegated child was popped out of; it keeps the parent's `rootThreadId`. */ + detachedFrom: Schema.optional(Schema.Struct({ threadId: ThreadId })), }); export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type; @@ -668,6 +670,38 @@ export function isProviderNativeSubagentThread( return thread.lineage.relationshipToParent === "subagent" && thread.creationSource === "provider"; } +/** A T3 delegate_task child still under its parent, the kind that can be popped out to top level. */ +export function isDelegatedChildThread( + thread: Pick, +): boolean { + return ( + thread.lineage.relationshipToParent === "subagent" && + thread.lineage.parentThreadId !== null && + thread.creationSource !== "provider" + ); +} + +/** + * Whether a delegated task ended and its result reached the parent. A task with no delivery + * record leaves its result to the turn that spawned it, so it counts once that turn has ended. + */ +export function isDelegatedTaskReported( + task: Pick, + spawningRunLive: boolean, +): boolean { + if ( + task.status !== "completed" && + task.status !== "failed" && + task.status !== "cancelled" && + task.status !== "interrupted" + ) + return false; + const delivery = task.completionDelivery?.state; + return delivery === undefined + ? !spawningRunLive + : delivery === "acknowledged" || delivery === "delivered" || delivery === "disposed"; +} + export const IDLE_COMPACTION_TEXT = "/compact"; /** @@ -2293,6 +2327,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([ "thread.unsettled", "thread.snoozed", "thread.unsnoozed", + "thread.detached", "thread.pinned", "thread.auto-settle-set", "thread.unpinned", @@ -3267,6 +3302,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ "thread.unsettled", "thread.snoozed", "thread.unsnoozed", + "thread.detached", "thread.pinned", "thread.auto-settle-set", "thread.unpinned", @@ -3421,6 +3457,7 @@ export const OrchestrationV2Command = Schema.Union([ * do under their caller's dispatch limit. Otherwise Stop also stops every task under the thread. */ stopDelegatedTasks: Schema.optional(Schema.Boolean), + expectedParentThreadId: Schema.optional(ThreadId), }), Schema.Struct({ type: Schema.Literal("thread.create"), @@ -3539,6 +3576,11 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, enabled: Schema.Boolean, }), + Schema.Struct({ + type: Schema.Literal("thread.detach"), + commandId: CommandId, + threadId: ThreadId, + }), Schema.Struct({ type: Schema.Literal("thread.pin"), commandId: CommandId,