From a62dccd8cb7caa1cd359aae186136592e3a157be Mon Sep 17 00:00:00 2001 From: Ivan Malison Date: Fri, 20 Nov 2026 17:51:21 -0800 Subject: [PATCH] Replay thread-pop-out merge-time changes Original commit: b783904d0cf2e3de9c34470f9fee9b16004caa1c Includes the cumulative changes through these earlier commits: - 90de6ebf5742 feat(server): pop a finished delegated child out to top level - ceda750e6f9d feat(web): pop out a delegated child from its menu or the parent's lineage - e5fd1e03886e Merge remote-tracking branch 'github/main' into t3code/main/thread-pop-out - 7ac13bf3b52d fix: tighten pop-out guards and keep the tool text within budget - 85ba10ebe731 feat(mobile): pop out a delegated child from its thread header - e415f889c817 Merge upstream main 1001bc71fc into carried topic - 98c84a9b0313 Merge upstream main 70833b2f55 into carried topic - c7bfcd078586 Merge remote-tracking branch 'github/main' into takeover-34236 - 764f09ed5100 fix: keep delegated pop-out and parent stops consistent - dcb85fe7c7cf fix: keep pop-out available after shell reloads - 65db615bdd52 Merge upstream main 6234afba12 into thread pop-out - 34f39b4ef76c Merge commit '399ea10f4e' into t3code/main/thread-pop-out - 49708f38bf82 Merge remote-tracking branch 'github/main' into takeover-34236-head - 4ca5aff5e526 fix: translate pop-out controls for current main --- .../src/features/threads/ThreadHeader.tsx | 12 ++ .../features/threads/ThreadRouteScreen.tsx | 45 ++++- apps/mobile/src/i18n/translations/de.json | 8 + apps/mobile/src/i18n/translations/en.json | 8 + apps/mobile/src/i18n/translations/es.json | 8 + apps/mobile/src/i18n/translations/fr.json | 8 + apps/mobile/src/i18n/translations/ja.json | 8 + apps/mobile/src/i18n/translations/ko.json | 8 + apps/mobile/src/i18n/translations/pt-BR.json | 8 + apps/mobile/src/i18n/translations/ru.json | 8 + apps/mobile/src/i18n/translations/sv.json | 8 + apps/mobile/src/i18n/translations/zh.json | 8 + apps/server/src/mcp/OrchestratorMcpService.ts | 16 ++ apps/server/src/mcp/toolkits/core.test.ts | 54 +++++ .../src/mcp/toolkits/thread/handlers.ts | 17 +- apps/server/src/mcp/toolkits/thread/tools.ts | 3 +- .../DelegatedCompletionDelivery.test.ts | 187 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 126 +++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 13 +- .../src/orchestration-v2/ShellStream.test.ts | 10 + .../src/orchestration-v2/ShellStream.ts | 4 + .../ThreadManagementService.ts | 22 ++- .../src/orchestration-v2/ThreadSearch.test.ts | 22 +++ .../src/orchestration-v2/ThreadStop.test.ts | 42 ++++ .../orchestration-v2/messageSearchIndex.ts | 25 +++ .../testkit/OrchestratorScenario.ts | 1 + apps/server/src/relay/AgentAwarenessRelay.ts | 1 + apps/server/src/telemetry/FeatureUsage.ts | 1 + ...hreadRelationshipsControl.browser.test.tsx | 3 + .../chat/ThreadRelationshipsControl.tsx | 151 +++++++++++--- .../components/threadActionMenu.logic.test.ts | 13 ++ .../src/components/threadActionMenu.logic.ts | 18 ++ apps/web/src/contextMenuFallback.ts | 5 + .../web/src/hooks/useThreadActionMenu.test.ts | 41 ++++ apps/web/src/hooks/useThreadActionMenu.ts | 32 ++- apps/web/src/hooks/useThreadActions.ts | 11 ++ apps/web/src/i18n/translations/de.json | 8 + apps/web/src/i18n/translations/en.json | 8 + apps/web/src/i18n/translations/es.json | 8 + apps/web/src/i18n/translations/fr.json | 8 + apps/web/src/i18n/translations/ja.json | 8 + apps/web/src/i18n/translations/ko.json | 8 + apps/web/src/i18n/translations/pt-BR.json | 8 + apps/web/src/i18n/translations/ru.json | 8 + apps/web/src/i18n/translations/sv.json | 8 + apps/web/src/i18n/translations/zh.json | 8 + docs/user/thread-sidebar.md | 7 + .../client-runtime/src/operations/commands.ts | 11 ++ .../client-runtime/src/state/orchestration.ts | 6 + .../src/state/orchestrationV2Projection.ts | 1 + .../src/state/threadCommands.ts | 8 + .../src/state/threadRelationships.test.ts | 83 ++++++++ .../src/state/threadRelationships.ts | 56 +++++- packages/contracts/src/orchestrationV2.ts | 42 ++++ 54 files changed, 1200 insertions(+), 49 deletions(-) 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 8f509de9e674a..d71a89edba4dc 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 { @@ -465,6 +468,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 = @@ -1048,6 +1090,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 1fe7fdc60bce9..6b3589721ac6d 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4698,6 +4698,8 @@ "11bb30071c8d00e4": "Der Link kann einmal verwendet werden und läuft nach 24 Stunden ab.", "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", @@ -4733,6 +4735,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 84c6fd8dfd893..bd2c34b6620e7 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4700,6 +4700,8 @@ "11bb30071c8d00e4": "The link works once and expires in 24 hours.", "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", @@ -4735,6 +4737,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 d3fb1c8188ddb..bf5d68e1fe596 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4691,6 +4691,8 @@ "11bb30071c8d00e4": "El enlace solo se puede usar una vez y caduca en 24 horas.", "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", @@ -4726,6 +4728,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 2d4f3cb8084fc..3fd69a7218a19 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4692,6 +4692,8 @@ "11bb30071c8d00e4": "Le lien est à usage unique et expire dans 24 heures.", "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", @@ -4727,6 +4729,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 68bcbddda6f02..ab88499fd81b7 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4672,6 +4672,8 @@ "11bb30071c8d00e4": "リンクは 1 回だけ使用でき、24 時間後に期限が切れます。", "05ba3b5f06a7acfe": "ファイルを閉じる", "c7e4f052c3d6c066": "ファイルを開く", + "c440ceeaf0452d52": "最上位に移動", + "8dcc52104281c7d2": "通常のスレッドにする", "740ee1b96278f02f": "音声 · {size}", "93ade1a4fd485bc3": "音声", "e8043d133bb85048": "音声を一時停止", @@ -4707,6 +4709,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 ce3e8aba332c7..b97169589dcbb 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4677,6 +4677,8 @@ "11bb30071c8d00e4": "링크는 한 번만 사용할 수 있으며 24시간 후 만료됩니다.", "05ba3b5f06a7acfe": "파일 닫기", "c7e4f052c3d6c066": "파일 열기", + "c440ceeaf0452d52": "최상위로 이동", + "8dcc52104281c7d2": "일반 스레드로 전환", "740ee1b96278f02f": "오디오 · {size}", "93ade1a4fd485bc3": "오디오", "e8043d133bb85048": "오디오 일시 중지", @@ -4712,6 +4714,12 @@ "d506b798402041ab": "지금 보내기", "9a62f694ba5c35c5": "스레드 여는 중…", "bb24a2960c689a20": "이 스레드는 현재 모바일 스냅샷에서 사용할 수 없습니다.", + "172e0baea818e9aa": "아직 이동할 수 없음", + "dd4ea2dfb2476c35": "완료될 때까지 기다리거나 먼저 중지하세요.", + "4249bde5600d6792": "최상위로 이동할까요?", + "b000660ae40f4586": "목록의 일반 스레드가 되며, 이 스레드를 시작한 스레드에 결과를 보고하지 않습니다.", + "8df226bf3314e35d": "이동", + "84eccdaa4d8f3c01": "스레드를 이동하지 못했습니다", "41ca8f475c481866": "{title}의 서브에이전트", "f3e00e6c416eab38": "출처: {origin}", "bdfb9e7660ab25d3": "스레드를 재개할 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 8cb5744485eaa..8a542efd951b4 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4692,6 +4692,8 @@ "11bb30071c8d00e4": "O link só pode ser usado uma vez e expira em 24 horas.", "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", @@ -4727,6 +4729,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 7dcacfc04efc6..02ec477d27b1a 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4770,6 +4770,8 @@ "11bb30071c8d00e4": "Ссылкой можно воспользоваться один раз, срок её действия истекает через 24 часа.", "05ba3b5f06a7acfe": "Закрыть файлы", "c7e4f052c3d6c066": "Открыть файлы", + "c440ceeaf0452d52": "Переместить на верхний уровень", + "8dcc52104281c7d2": "Сделать обычной веткой", "740ee1b96278f02f": "Аудио · {size}", "93ade1a4fd485bc3": "Аудио", "e8043d133bb85048": "Приостановить аудио", @@ -4805,6 +4807,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 6e18ff09a8318..b06194e066433 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4698,6 +4698,8 @@ "11bb30071c8d00e4": "Länken kan användas en gång och går ut om 24 timmar.", "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", @@ -4733,6 +4735,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 1bea8cf8142f2..8b84eb2b56476 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4681,6 +4681,8 @@ "11bb30071c8d00e4": "链接仅限使用一次,并在 24 小时后过期。", "05ba3b5f06a7acfe": "关闭文件", "c7e4f052c3d6c066": "打开文件", + "c440ceeaf0452d52": "移至顶层", + "8dcc52104281c7d2": "设为普通会话", "740ee1b96278f02f": "音频 · {size}", "93ade1a4fd485bc3": "音频", "e8043d133bb85048": "暂停音频", @@ -4716,6 +4718,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 f13623c232838..b731fc4ea410c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3039,6 +3039,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 33c356af4e7e1..2b189f97cf08c 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -636,6 +636,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 220ed39eb3c81..4b46ea8922bd8 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -402,7 +402,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 @@ -427,6 +427,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 9803e8b4fa690..da73f3bddb26e 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -32,7 +32,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), @@ -46,6 +46,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 3d6575bd6a405..8149f5febbbe3 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, @@ -1364,6 +1365,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) => @@ -2465,6 +2474,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 6920d26d3502f..6d4a26ad55370 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, @@ -407,6 +409,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: ( @@ -654,6 +660,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": @@ -5834,6 +5841,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, @@ -14459,6 +14555,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 || @@ -14828,8 +14929,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) { @@ -15976,6 +16078,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; @@ -16621,8 +16726,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; }); @@ -17094,6 +17200,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]; @@ -17150,6 +17257,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 e10bc5340d646..3bb81a13dc0ba 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -109,7 +109,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, @@ -1059,6 +1059,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": @@ -2512,6 +2513,7 @@ export const layer: Layer.Layer = case "thread.unsettled": case "thread.snoozed": case "thread.unsnoozed": + case "thread.detached": case "thread.auto-settle-set": case "thread.pinned": case "thread.unpinned": @@ -2576,6 +2578,7 @@ export const layer: Layer.Layer = deleted_at = excluded.deleted_at, payload_json = excluded.payload_json `; + if (event.type === "thread.detached") yield* indexThreadMessages(sql, event.threadId); break; } case "run.created": @@ -3365,6 +3368,7 @@ export const layer: Layer.Layer = event.type !== "thread.unsettled" && event.type !== "thread.snoozed" && event.type !== "thread.unsnoozed" && + event.type !== "thread.detached" && event.type !== "thread.auto-settle-set" && event.type !== "thread.pinned" && event.type !== "thread.unpinned" && @@ -6780,8 +6784,13 @@ export const layer: Layer.Layer = threadId, ) => 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 fbc610235dd01..8735412407d6d 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -86,6 +86,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 5ee1005b16830..01f9ecb037e06 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -544,6 +544,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 45b5e9effa8cf..9967aa68651dd 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1706,7 +1706,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 > = []; @@ -1750,17 +1759,26 @@ 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* dispatch({ type: "thread.stop", commandId: CommandId.make(`${input.commandId}:stop:${threadId}`), threadId, stopDelegatedTasks: false, + expectedParentThreadId: input.threadId, ...(input.reason === undefined ? {} : { reason: input.reason }), }).pipe( Effect.andThen( - stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }), + Effect.gen(function* () { + const child = yield* orchestrator.getThreadRecords(threadId, []); + if (child.thread.lineage.parentThreadId !== input.threadId) return; + yield* stopDelegatedTasks({ + threadId, + commandId: input.commandId, + reason: input.reason, + }); + }), ), Effect.catch((error) => Effect.logWarning("Unable to stop a delegated task", { diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 399224533089d..676c49f1277dd 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -516,6 +516,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 fc52191d32b29..10f635bf0c60a 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -611,6 +611,48 @@ it.effect.each(["run.interrupt", "thread.stop"] as const)( }).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 0855d01171f3f..40c1d6bb0cbb8 100644 --- a/apps/server/src/orchestration-v2/messageSearchIndex.ts +++ b/apps/server/src/orchestration-v2/messageSearchIndex.ts @@ -159,6 +159,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 15ac7ecb8d3fe..f80971d5bda37 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 666ce784b3afc..8c09888c4a860 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -52,6 +52,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 b005fa877b745..bca5b91f36844 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, TooltipTrigger } from "../ui/tooltip"; @@ -237,6 +244,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")); @@ -484,6 +496,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(); @@ -521,6 +547,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 ?? []); @@ -562,6 +590,7 @@ export function ThreadRelationshipsPanel(props: { ); const shells: ReadonlyArray = [ ...relationshipShells, + ...(family.data?.threads ?? []), ...(archivedShells ?? []), ]; const graph = deriveThreadRelationshipGraph({ threads: shells, projection }); @@ -770,6 +799,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); @@ -803,10 +847,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); @@ -823,6 +868,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 ?? @@ -845,7 +901,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); @@ -1012,32 +1068,65 @@ export function ThreadRelationshipsPanel(props: { ) : ( relationshipLink )} - {canStop && agent ? ( -
- - void stopSubagent(threadId, agent)} - /> - } - > - {stoppingId === threadId ? ( - - ) : ( - - )} - - - Stop subagent - - + {(canStop && agent) || canPopOut ? ( +
+ {canPopOut ? ( + + { + if (popOutAvailability !== "blocked") void popOut(threadId); + }} + /> + } + > + {poppingOutId === threadId ? ( + + ) : ( + + )} + + + {popOutAvailability === "blocked" + ? gt("Pop out to top level. Wait for it to finish or stop it first.") + : gt("Pop out to top level")} + + + ) : null} + {canStop && agent ? ( + + void stopSubagent(threadId, agent)} + /> + } + > + {stoppingId === threadId ? ( + + ) : ( + + )} + + + Stop subagent + + + ) : null}
) : null} diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index 0c13e765131cc..503cdc7bc82af 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -79,4 +79,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 dc2d7687a2be6..79bb44a742e3a 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" | "copy" | "copy-path" @@ -123,6 +128,7 @@ export interface ThreadActionMenuState { readonly canShareWithGuest?: 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. */ @@ -220,6 +226,18 @@ export function buildThreadActionMenuItems( ] : []), { id: "mark-unread", 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 f4abe911aa72a..e07e6d6cd5587 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -112,6 +112,11 @@ const ICON_PATHS: Record ({ granted: new Set(), effects: [] as string[], completed: deferred(), + child: false, + delivery: "pending" as "pending" | "acknowledged", show: vi.fn< ( items: ReadonlyArray>, @@ -58,11 +60,34 @@ vi.mock("../state/entities", () => ({ worktreePath: null, runtime: null, latestRun: null, + source: { + creationSource: "server", + status: "completed", + pendingRuntimeRequest: null, + lineage: { + parentThreadId: state.child ? "parent" : null, + relationshipToParent: state.child ? "subagent" : null, + }, + }, }), useProjects: () => [{ id: "project", environmentId: "secondary" }], })); 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"); @@ -120,6 +145,7 @@ vi.mock("./useSettings", () => ({ })); vi.mock("./useThreadActions", () => ({ canTurnThreadIntoProject: () => false, + usePopOutThread: () => async () => AsyncResult.success(undefined), useThreadActions: () => Object.fromEntries( [ @@ -162,10 +188,25 @@ beforeEach(() => { state.granted = new Set(["primary"]); state.effects = []; 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) => { diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 4e5914d078c57..f09edbc7506f0 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -9,11 +9,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; -import { - AuthOrchestrationOperateScope, - type ScopedThreadRef, - type ThreadId, -} from "@t3tools/contracts"; +import { AuthOrchestrationOperateScope, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import { useRouter } from "@tanstack/react-router"; import { msg } from "gt-react"; @@ -47,10 +43,13 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping"; import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { 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( @@ -92,6 +91,8 @@ export function useThreadActionMenu(input: { markThreadUnread, turnThreadIntoProject, } = useThreadActions(); + const popOutThread = usePopOutThread(); + const loadPopOutParent = useAtomQueryRunner(orchestrationEnvironment.popOutParent); const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { reportFailure: false, }); @@ -138,6 +139,21 @@ export function useThreadActionMenu(input: { }; const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); + let popOut = threadPopOutAvailability(thread.source); + if (popOut === "available" && thread.source.lineage.parentThreadId !== null) { + const parent = await loadPopOutParent({ + environmentId: threadRef.environmentId, + input: { threadId: ThreadId.make(thread.source.lineage.parentThreadId) }, + }); + popOut = + parent._tag === "Success" + ? threadPopOutAvailability( + thread.source, + parent.value.subagents.filter((task) => task.childThreadId === threadRef.threadId), + parent.value.runs, + ) + : "blocked"; + } const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), canFind: onFind !== undefined, @@ -154,6 +170,7 @@ export function useThreadActionMenu(input: { snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), + popOut, }); const clicked = await settlePromise(() => api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -270,6 +287,9 @@ export function useThreadActionMenu(input: { case "mark-unread": markThreadUnread(threadRef); return; + case "pop-out": + await reportFailure(m(msg("Failed to pop out thread")), () => popOutThread(threadRef)); + return; case "share-guest": openGuestShareDialog(threadRef); return; diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 2a591127044d1..d9de0fcf88652 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 16f3d83c8b2e6..4795d74348935 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2770,6 +2770,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", @@ -2786,6 +2787,7 @@ "6dd1f458bcd6a2ea": "Wird neu erzeugt…", "de30fdae5b3fea98": "Titel neu erzeugen", "dffd2e20f7ff5aa1": "Als ungelesen markieren", + "c440ceeaf0452d52": "Auf oberste Ebene verschieben", "3364346f40934e88": "Alle Projekte anzeigen", "666f3ac177c116b6": "Nach {project} filtern", "1385e2d8bd696370": "In Projekt umwandeln", @@ -2911,6 +2913,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.", @@ -4284,6 +4287,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", @@ -4297,12 +4302,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 c4534c680b95f..c4a5dd9af038b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2769,6 +2769,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", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Regenerating…", "de30fdae5b3fea98": "Regenerate title", "dffd2e20f7ff5aa1": "Mark unread", + "c440ceeaf0452d52": "Pop out to top level", "3364346f40934e88": "Show all projects", "666f3ac177c116b6": "Filter by {project}", "1385e2d8bd696370": "Turn into project", @@ -2910,6 +2912,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.", @@ -4283,6 +4286,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", @@ -4296,12 +4301,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 ff83b277dc0d6..713a8d50535eb 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2769,6 +2769,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", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Regenerando…", "de30fdae5b3fea98": "Regenerar título", "dffd2e20f7ff5aa1": "Marcar como no leído", + "c440ceeaf0452d52": "Mover al nivel superior", "3364346f40934e88": "Mostrar todos los proyectos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Convertir en proyecto", @@ -2910,6 +2912,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.", @@ -4281,6 +4284,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", @@ -4294,12 +4299,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 939d36465b041..b863a79beeebc 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2769,6 +2769,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", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Régénération…", "de30fdae5b3fea98": "Régénérer le titre", "dffd2e20f7ff5aa1": "Marquer comme non lu", + "c440ceeaf0452d52": "Déplacer au premier niveau", "3364346f40934e88": "Afficher tous les projets", "666f3ac177c116b6": "Filtrer par {project}", "1385e2d8bd696370": "Transformer en projet", @@ -2910,6 +2912,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.", @@ -4282,6 +4285,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", @@ -4295,12 +4300,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 51fe276edc353..59710605ff526 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2767,6 +2767,7 @@ "f50619195a6d0ad2": "{appName} に {owner} へのアクセスを許可", "9b771434a1d169dd": "そこにはインストールされていないため、{repository} への GitHub リクエストにはあなた自身のログインと、その低いレート制限が使われます。", "5d973795984549fc": "インストール", + "934fc71948012d25": "完了するまで待つか、先に停止してください", "d2ba9ab14fd2e81c": "コピー", "a9abbabbd3106847": "パス", "bd86c9f5e546d3d9": "ブランチ", @@ -2783,6 +2784,7 @@ "6dd1f458bcd6a2ea": "再生成しています…", "de30fdae5b3fea98": "タイトルを再生成", "dffd2e20f7ff5aa1": "未読にする", + "c440ceeaf0452d52": "最上位に移動", "3364346f40934e88": "すべてのプロジェクトを表示", "666f3ac177c116b6": "{project} で絞り込み", "1385e2d8bd696370": "プロジェクトに変換", @@ -2908,6 +2910,7 @@ "32e2dbf6abe8c748": "トリアージを開始しています…", "ce5c66ae967fd7c8": "スレッドの操作を利用できません", "d4f0043ab9348e2c": "このスレッドはまだ読み込まれていません。", + "f49381c9fa02295f": "スレッドを移動できませんでした", "de2cfd4a757c656a": "プロバイダーがアクティブな間はアーカイブできません。", "8523f86d3c21edf3": "この環境のサーバーはまだ対応済みをサポートしていません。対応済みを使うにはサーバーを更新してください。", "876b987471f908d4": "この環境のサーバーはまだスヌーズをサポートしていません。スヌーズを使うにはサーバーを更新してください。", @@ -4272,6 +4275,8 @@ "56567586cbe00c86": "このチャットでコンテキストの引き継ぎを開く", "405e76cdd602bbcf": "サブエージェントを開く", "520c15dbd507b804": "このチャットで親エージェントを開く", + "d9dd3778e54f2e9c": "移動済み", + "b39e8916098428d1": "以前の親スレッド", "309b160785f6c473": "このチャットでフォークを開く", "6676cd4b8299663f": "このチャットで親スレッドを開く", "63e8c7a0ef0513b5": "関連するスレッド", @@ -4285,12 +4290,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 51c3b0a06a006..574ca6655d7de 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2768,6 +2768,7 @@ "f50619195a6d0ad2": "{appName}에 {owner} 액세스 권한 부여", "9b771434a1d169dd": "그곳에 설치되어 있지 않아 {repository}에 대한 GitHub 요청에 내 로그인과 그보다 낮은 속도 제한이 적용됩니다.", "5d973795984549fc": "설치", + "934fc71948012d25": "완료될 때까지 기다리거나 먼저 중지하세요", "d2ba9ab14fd2e81c": "복사", "a9abbabbd3106847": "경로", "bd86c9f5e546d3d9": "브랜치", @@ -2784,6 +2785,7 @@ "6dd1f458bcd6a2ea": "다시 생성하는 중…", "de30fdae5b3fea98": "제목 다시 생성", "dffd2e20f7ff5aa1": "읽지 않음으로 표시", + "c440ceeaf0452d52": "최상위로 이동", "3364346f40934e88": "모든 프로젝트 표시", "666f3ac177c116b6": "{project}(으)로 필터", "1385e2d8bd696370": "프로젝트로 전환", @@ -2909,6 +2911,7 @@ "32e2dbf6abe8c748": "분류를 시작하는 중…", "ce5c66ae967fd7c8": "스레드 작업을 사용할 수 없음", "d4f0043ab9348e2c": "이 스레드를 아직 불러오지 않았습니다.", + "f49381c9fa02295f": "스레드를 이동하지 못했습니다", "de2cfd4a757c656a": "제공자가 활성 상태인 동안에는 보관할 수 없습니다.", "8523f86d3c21edf3": "이 환경의 서버는 아직 정리를 지원하지 않습니다. 정리를 사용하려면 서버를 업데이트하세요.", "876b987471f908d4": "이 환경의 서버는 아직 다시 알림을 지원하지 않습니다. 다시 알림을 사용하려면 서버를 업데이트하세요.", @@ -4269,6 +4272,8 @@ "56567586cbe00c86": "이 채팅에서 컨텍스트 전달 열기", "405e76cdd602bbcf": "서브에이전트 열기", "520c15dbd507b804": "이 채팅에서 상위 에이전트 열기", + "d9dd3778e54f2e9c": "이동됨", + "b39e8916098428d1": "이전 상위 스레드", "309b160785f6c473": "이 채팅에서 포크 열기", "6676cd4b8299663f": "이 채팅에서 상위 스레드 열기", "63e8c7a0ef0513b5": "관련 스레드", @@ -4282,12 +4287,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/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index d17ff0e321ccf..9f6dc86d6a042 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2769,6 +2769,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", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Gerando novamente…", "de30fdae5b3fea98": "Gerar título novamente", "dffd2e20f7ff5aa1": "Marcar como não lida", + "c440ceeaf0452d52": "Mover para o nível superior", "3364346f40934e88": "Mostrar todos os projetos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Transformar em projeto", @@ -2910,6 +2912,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.", @@ -4281,6 +4284,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", @@ -4294,12 +4299,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 88e2323bac363..c3cf07de99f65 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2769,6 +2769,7 @@ "f50619195a6d0ad2": "Дайте {appName} доступ к {owner}", "9b771434a1d169dd": "Оно там не установлено, поэтому запросы к GitHub для {repository} идут от вашего логина с более низким лимитом.", "5d973795984549fc": "Установить", + "934fc71948012d25": "Дождитесь завершения или сначала остановите", "d2ba9ab14fd2e81c": "Копировать", "a9abbabbd3106847": "Путь", "bd86c9f5e546d3d9": "Ветку", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Генерация…", "de30fdae5b3fea98": "Сгенерировать название заново", "dffd2e20f7ff5aa1": "Отметить непрочитанным", + "c440ceeaf0452d52": "Переместить на верхний уровень", "3364346f40934e88": "Показать все проекты", "666f3ac177c116b6": "Фильтр: {project}", "1385e2d8bd696370": "Превратить в проект", @@ -2910,6 +2912,7 @@ "32e2dbf6abe8c748": "Запуск разбора проблемы…", "ce5c66ae967fd7c8": "Действия с тредом недоступны", "d4f0043ab9348e2c": "Этот тред ещё не загрузился.", + "f49381c9fa02295f": "Не удалось переместить ветку", "de2cfd4a757c656a": "Нельзя архивировать, пока провайдер активен.", "8523f86d3c21edf3": "Сервер этого окружения пока не поддерживает разбор тредов. Обновите сервер, чтобы использовать «Разобрать».", "876b987471f908d4": "Сервер этого окружения пока не поддерживает откладывание. Обновите сервер, чтобы использовать «Отложить».", @@ -4281,6 +4284,8 @@ "56567586cbe00c86": "Открыть передачу контекста в этом чате", "405e76cdd602bbcf": "Открыть субагента", "520c15dbd507b804": "Открыть родительского агента в этом чате", + "d9dd3778e54f2e9c": "Перемещена", + "b39e8916098428d1": "Бывшая родительская ветка", "309b160785f6c473": "Открыть ответвление в этом чате", "6676cd4b8299663f": "Открыть родительский тред в этом чате", "63e8c7a0ef0513b5": "Связанные треды", @@ -4294,12 +4299,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 055af1f3a6783..a6b65391a5344 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2769,6 +2769,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", @@ -2785,6 +2786,7 @@ "6dd1f458bcd6a2ea": "Genererar om…", "de30fdae5b3fea98": "Generera om titel", "dffd2e20f7ff5aa1": "Markera som oläst", + "c440ceeaf0452d52": "Flytta till översta nivån", "3364346f40934e88": "Visa alla projekt", "666f3ac177c116b6": "Filtrera efter {project}", "1385e2d8bd696370": "Gör om till projekt", @@ -2910,6 +2912,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.", @@ -4282,6 +4285,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", @@ -4295,12 +4300,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 998020844cf79..bd887d4dd7963 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2773,6 +2773,7 @@ "f50619195a6d0ad2": "授予 {appName} 访问 {owner} 的权限", "9b771434a1d169dd": "该处尚未安装此应用,因此对 {repository} 的 GitHub 请求会使用你自己的登录身份,受较低的速率限制。", "5d973795984549fc": "安装", + "934fc71948012d25": "请等待完成,或先停止", "d2ba9ab14fd2e81c": "复制", "a9abbabbd3106847": "路径", "bd86c9f5e546d3d9": "分支", @@ -2789,6 +2790,7 @@ "6dd1f458bcd6a2ea": "正在重新生成…", "de30fdae5b3fea98": "重新生成标题", "dffd2e20f7ff5aa1": "标为未读", + "c440ceeaf0452d52": "移至顶层", "3364346f40934e88": "显示所有项目", "666f3ac177c116b6": "按 {project} 筛选", "1385e2d8bd696370": "转换为项目", @@ -2914,6 +2916,7 @@ "32e2dbf6abe8c748": "正在开始问题排查…", "ce5c66ae967fd7c8": "会话操作不可用", "d4f0043ab9348e2c": "此会话尚未加载。", + "f49381c9fa02295f": "移出会话失败", "de2cfd4a757c656a": "提供方仍在运行时无法归档。", "8523f86d3c21edf3": "此环境的服务器尚不支持收尾。请更新服务器后再使用“收尾”。", "876b987471f908d4": "此环境的服务器尚不支持暂缓。请更新服务器后再使用“暂缓”。", @@ -4288,6 +4291,8 @@ "56567586cbe00c86": "在此对话中打开上下文转移", "405e76cdd602bbcf": "打开子智能体", "520c15dbd507b804": "在此对话中打开父智能体", + "d9dd3778e54f2e9c": "已移出", + "b39e8916098428d1": "原父会话", "309b160785f6c473": "在此对话中打开分叉", "6676cd4b8299663f": "在此对话中打开父会话", "63e8c7a0ef0513b5": "相关会话", @@ -4301,12 +4306,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 9bbf3194a9d59..ea44d5a8fa994 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -282,6 +282,13 @@ fill the screen; close the full-screen view to return to the parent and inspecto Stop on a thread also stops the subagents it delegated to. Before archiving the parent, wait for its delegated tasks to finish or cancel them. +To keep working in a delegated thread on its own, choose **Pop out to top level** +from its thread menu or its row in the parent's **Lineage**; in the mobile app it's +in the thread's header, under the overflow menu on Android. It keeps its history, +model, and folder, gets its own sidebar row, and no longer reports to the parent or +stops with it. It is available once the delegated task has finished and its result +reached the parent; stop it first if you can't wait. + Subagent threads started by the agent can't take messages; message the parent thread instead. When such a subagent needs an approval or an answer, the parent thread asks for it. diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 0ea95420460a7..692a87a096b61 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -713,6 +713,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 d936fa7726df2..e80e88bdf9a87 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -307,6 +307,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 98d88407b85b4..5a88192d3fd3c 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -34,6 +34,7 @@ import { forkSideChat, forkThreadFromRun, markThreadUnread, + popOutThread, mergeThreadBack, promoteQueuedRun, resumeThreadQueue, @@ -295,6 +296,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, @@ -486,6 +493,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 6eec84b4dc253..80d9a822920bd 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -177,6 +177,8 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({ relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), rootThreadId: ThreadId, sideChat: 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; @@ -599,6 +601,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"; interface CompactionMessageFields { @@ -2160,6 +2194,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([ "thread.unsettled", "thread.snoozed", "thread.unsnoozed", + "thread.detached", "thread.pinned", "thread.auto-settle-set", "thread.unpinned", @@ -3117,6 +3152,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ "thread.unsettled", "thread.snoozed", "thread.unsnoozed", + "thread.detached", "thread.pinned", "thread.auto-settle-set", "thread.unpinned", @@ -3270,6 +3306,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"), @@ -3385,6 +3422,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,