diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.ts index 28c6cda29a4d3..a41581b08c2d5 100644 --- a/apps/mobile/src/connection/environment-owned-data-cleanup.ts +++ b/apps/mobile/src/connection/environment-owned-data-cleanup.ts @@ -8,6 +8,7 @@ import * as Schema from "effect/Schema"; import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error"; import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal"; import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts"; +import { mobileThreadTriageOutboxStore } from "../state/thread-triage-outbox-storage"; class EnvironmentOwnedDataClearError extends Schema.TaggedError()( "EnvironmentOwnedDataClearError", @@ -40,6 +41,7 @@ export const layer = Layer.succeed( settle("outbox", clearThreadOutboxEnvironment), settle("drafts", clearComposerDraftsEnvironment), Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)), + Effect.ignore(mobileThreadTriageOutboxStore.clearEnvironment(environmentId)), ], { concurrency: "unbounded", discard: true }, ); diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts index 91a6ac71919da..b412fadede0d9 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -7,6 +7,7 @@ import { removeCatalogValue, replaceCatalogValue, Persistence, + ThreadTriageOutboxStore, } from "@t3tools/client-runtime/platform"; import { TokenStore } from "@t3tools/client-runtime/authorization"; import { @@ -21,6 +22,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import { mobileThreadTriageOutboxStore } from "../state/thread-triage-outbox-storage"; import * as CatalogStore from "./catalog-store"; function targetPersistenceError( @@ -164,6 +166,7 @@ export const layer = Layer.effectContext( Context.add(ProfileStore.ConnectionProfileStore, profileStore), Context.add(CredentialStore.ConnectionCredentialStore, credentialStore), Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore), + Context.add(ThreadTriageOutboxStore, mobileThreadTriageOutboxStore), ); }), ); diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 135cf4e1d85a7..0157c38ba3f6c 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -23,6 +23,8 @@ const state = vi.hoisted(() => ({ archivedRefreshes: [] as string[], onArchivedRefresh: undefined as (() => void) | undefined, scopes: new Map>(), + sessionNotLoaded: new Set(), + successValues: new Map(), shells: [] as EnvironmentThreadShell[], requests: [] as { action: string; @@ -66,6 +68,9 @@ vi.mock("../archive/useArchivedThreadSnapshots", () => ({ vi.mock("../../state/session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => state.scopes.get(environmentId)?.has(scope) === true, + readThreadTriageScope: (environmentId: string) => + state.scopes.get(environmentId)?.has(AuthOrchestrationOperateScope) === true || + state.sessionNotLoaded.has(environmentId), })); vi.mock("../../state/presentation", () => ({ connectedEnvironmentIdsAtom: "connected-environments", @@ -168,13 +173,19 @@ vi.mock("../../state/threads", () => ({ }) => { state.requests.push({ action, ...request }); await state.heldActions.get(action); - if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) { + // Without a loaded session the command itself queues settle and snooze. + if ( + !state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope) && + !state.sessionNotLoaded.has(request.environmentId) + ) { return AsyncResult.failure(Cause.fail(new Error("Thread operation denied"))); } if (action === state.failedAction) return AsyncResult.failure(Cause.fail(new Error("Server rejected action"))); state.afterRequest?.(); - return AsyncResult.success(action === "regenerateTitle" ? state.titleOutcome : undefined); + return AsyncResult.success( + action === "regenerateTitle" ? state.titleOutcome : state.successValues.get(action), + ); }, ]), ), @@ -218,6 +229,8 @@ beforeEach(() => { state.onArchivedRefresh = undefined; state.pendingOrder = null; state.dropBusy = false; + state.sessionNotLoaded = new Set(); + state.successValues = new Map(); state.holdingRows = false; state.scopes = new Map([ [primaryEnvironmentId, new Set([AuthOrchestrationOperateScope])], @@ -269,6 +282,19 @@ describe("thread list operation permissions", () => { expect(state.requests).toEqual([]); }); + it.each(mutationCases)( + "%s runs before the session loads only for settle, snooze and their undo", + async (handler, action) => { + state.scopes.get(primaryEnvironmentId)!.clear(); + state.sessionNotLoaded.add(primaryEnvironmentId); + + await useThreadListActions()[handler](makeThread(), "2099-01-01T00:00:00.000Z"); + + const triage = ["settle", "unsettle", "snooze", "unsnooze"].includes(action); + expect(state.requests.map((request) => request.action)).toEqual(triage ? [action] : []); + }, + ); + it("rechecks permission after a retained delete confirmation, then clears the draft", async () => { const draft = { text: "unsent", attachments: [] }; appAtomRegistry.set(composerDraftsAtom, { "primary:thread": draft, "primary:other": draft }); @@ -504,6 +530,22 @@ describe("thread action undo", () => { expect(readThreadUndoNotice()).toBeNull(); }); + // Whether the queued settle reached the server is known only when Undo runs. + it.each([ + ["cancels it before it syncs", { sequence: 0, cancelledPendingSync: true }, ["snooze"]], + ["finds it delivered", { sequence: 3 }, ["pin", "snooze"]], + ])("restores a queued settle only as far as needed when Undo %s", async (_, undone, restored) => { + state.successValues.set("unsettle", undone); + const thread = makeThread({ + pinnedAt: "2026-09-02T00:00:00.000Z", + pinOrderKey: "m", + snoozedUntil: "2099-01-01T09:00:00.000Z", + }); + expect(await useThreadListActions().settleThread(thread)).toBe(true); + await readThreadUndoNotice()!.undo(); + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "unsettle", ...restored]); + }); + // regression: #21401 restore archive and thread action undo it("wakes a snoozed thread through the undo action", async () => { const thread = makeThread(); diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 8a70854e5b2c3..8056a0fefa0f8 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -19,7 +19,7 @@ import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentServerConfigsAtom } from "../../state/server"; import { connectedEnvironmentIdsAtom } from "../../state/presentation"; -import { readEnvironmentScope } from "../../state/session"; +import { readEnvironmentScope, readThreadTriageScope } from "../../state/session"; import { clearComposerDraft } from "../../state/use-composer-drafts"; import { environmentThreadShells, @@ -86,8 +86,18 @@ function actionFailureTitle(action: ThreadListAction): string { return m(msg("Could not delete thread")); } -function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: string): boolean { - if (readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return true; +/** Settle, snooze and their undo may queue before the environment's session loads. */ +function checkThreadOperationPermission( + thread: EnvironmentThreadShell, + title: string, + triage = false, +): boolean { + if ( + triage + ? readThreadTriageScope(thread.environmentId) + : readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope) + ) + return true; Dialog.alert(title, m(msg("This connection cannot change threads."))); return false; } @@ -119,9 +129,11 @@ function useThreadActionExecutor( action: ThreadListAction, thread: EnvironmentThreadShell, onStarted?: () => void, + onSucceeded?: (value: unknown) => void, restoreUnsettledAt?: string | null, ) => { - if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false; + const triage = action === "settle" || action === "unsettle"; + if (!checkThreadOperationPermission(thread, actionFailureTitle(action), triage)) return false; const key = scopedThreadKey(thread.environmentId, thread.id); // Drop only a repeat of the latest pending action; Settle → Un-settle → Settle must all send. if (latestPendingActions.current.get(key)?.action === action) { @@ -193,6 +205,7 @@ function useThreadActionExecutor( if (action === "archive" || action === "unarchive" || action === "delete") { refreshArchivedThreadsForEnvironment(thread.environmentId); } + onSucceeded?.(result.value); if (action === "delete") clearComposerDraft(key); onCompleted?.(action, thread); return true; @@ -275,18 +288,23 @@ export function useThreadListActions(): { action, claim, undo: async () => { + // A local cancellation keeps pin placement, but may have replaced a queued snooze. + let cancelledQueued = false; try { await ThreadUndo.executeThreadUndo( plan, async (step) => { switch (step.action) { case "unsettle": - return unsettleThread(thread, step.restoreUnsettledAt); + return unsettleThread(thread, step.restoreUnsettledAt, (value) => { + cancelledQueued = ThreadUndo.cancelledPendingSync(value); + }); case "unsnooze": return unsnoozeThread(thread); case "pin": - return pinThread(thread, step.orderKey); + return cancelledQueued || pinThread(thread, step.orderKey); case "reorderActive": { + if (cancelledQueued) return true; const result = await reorderActiveMutation({ environmentId: thread.environmentId, input: { threadId: thread.id, orderKey: step.orderKey }, @@ -299,7 +317,7 @@ export function useThreadListActions(): { action === "Unpinned" ? m(msg("Could not undo unpin")) : m(msg("Could not undo settle")); - if (!checkThreadOperationPermission(thread, failureTitle)) return false; + if (!checkThreadOperationPermission(thread, failureTitle, true)) return false; const result = await snoozeMutation({ environmentId: thread.environmentId, input: { threadId: thread.id, snoozedUntil: step.snoozedUntil }, @@ -346,7 +364,9 @@ export function useThreadListActions(): { return succeeded; }; const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => { - if (!checkThreadOperationPermission(thread, m(msg("Could not snooze thread")))) return false; + if (!checkThreadOperationPermission(thread, m(msg("Could not snooze thread")), true)) { + return false; + } const key = scopedThreadKey(thread.environmentId, thread.id); if (snoozeInFlightThreadKeys.current.has(key)) { return false; @@ -410,7 +430,9 @@ export function useThreadListActions(): { return succeeded; }; const unsnoozeThread = async (thread: EnvironmentThreadShell) => { - if (!checkThreadOperationPermission(thread, m(msg("Could not wake thread")))) return false; + if (!checkThreadOperationPermission(thread, m(msg("Could not wake thread")), true)) { + return false; + } const key = scopedThreadKey(thread.environmentId, thread.id); if (snoozeInFlightThreadKeys.current.has(key)) { return false; @@ -458,7 +480,9 @@ export function useThreadListActions(): { const unsettleThread = async ( thread: EnvironmentThreadShell, restoreUnsettledAt?: string | null, - ) => (await executeAction("unsettle", thread, undefined, restoreUnsettledAt)) === true; + onSucceeded?: (value: unknown) => void, + ) => + (await executeAction("unsettle", thread, undefined, onSucceeded, restoreUnsettledAt)) === true; const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => { if (!checkThreadOperationPermission(thread, m(msg("Could not pin thread")))) return false; if (!environmentConfigLoaded(thread.environmentId)) { diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index cf8adb7ac3581..9370b7c7c2ef7 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -172,6 +172,7 @@ import { appAtomRegistry } from "../../state/atom-registry"; import { threadStreamHaptics } from "./threadStreamHaptics"; import { useAtomCommand } from "../../state/use-atom-command"; import { orchestrationEnvironment } from "../../state/orchestration"; +import { useThreadTriageScope } from "../../state/session"; import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; import type { @@ -555,6 +556,7 @@ function ThreadDetailBody( }); const unsnoozeThread = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false }); const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false }); + const canTriageThread = useThreadTriageScope(props.environmentId); const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false }); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); const anyRunStop = useAtomValue( @@ -654,7 +656,9 @@ function ThreadDetailBody( latestRunCompletedAt: props.selectedThread.latestRun?.completedAt ?? null, }); const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => { - if (statusPending || !props.canOperateThread) return; + const permitted = + action === "wake" || action === "unsettle" ? canTriageThread : props.canOperateThread; + if (statusPending || !permitted) return; const request: BackgroundWorkStopRequest = { threadKey: selectedThreadKey, taskIds: @@ -783,7 +787,9 @@ function ThreadDetailBody( : gt("Dismissing...") : actionLabel, accessibilityLabel: actionLabel, - disabled: !props.canOperateThread || statusPending, + disabled: + !(lifecycleSnoozed || settled ? canTriageThread : props.canOperateThread) || + statusPending, onPress: () => void runStatusAction(lifecycleSnoozed ? "wake" : settled ? "unsettle" : "dismiss"), }, diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 7a18e1429934e..4852ec6d1e8d4 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -1,3 +1,4 @@ +import { useAtomValue } from "@effect/atom-react"; import * as Dialog from "../../components/ui/Dialog"; import type { ThreadRowProviderInstance } from "./thread-provider-instance"; import { @@ -57,7 +58,7 @@ import { cn } from "../../lib/cn"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { copyThreadReference } from "../../lib/copyThreadReference"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; -import { useEnvironmentScope } from "../../state/session"; +import { useEnvironmentScope, useThreadTriageScope } from "../../state/session"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { pendingDraftBranchNeedsRefs, @@ -324,6 +325,8 @@ type ThreadListV2ShelfHeaderProps = { readonly pane?: "screen" | "sidebar"; }; +const TRIAGE_MENU_ACTION_IDS = new Set(["settle", "snooze", "unsettle", "unsnooze"]); + const SHELF_COPY = { working: { label: msg("Working", { $context: "thread list section" }), @@ -884,31 +887,37 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { label: statusEntry.label === null ? null : m(statusEntry.label), }; const recede = shouldRecedeThreadRow({ status, selected }); + const pendingSync = useAtomValue(threadEnvironment.pendingSyncAtom(thread.environmentId)).has( + thread.id, + ); const isRegeneratingTitle = thread.titleRegeneration != null; // List items keep marked text so they stay the same objects across a language switch. - const timeLabel = props.timeLabel && m(props.timeLabel); + const listTimeLabel = props.timeLabel && m(props.timeLabel); + const timeLabel = pendingSync ? gt("Waiting to sync") : listTimeLabel; const snoozeWakeLabelText = props.snoozeWakeLabelText === undefined ? undefined : m(props.snoozeWakeLabelText); - const rowAccessibilityLabel = threadListV2RowAccessibilityLabel( - { - title: thread.title, - variant, - woke: showsWoke, - // Working and waiting rows show only an icon and a duration, so name them for speech. - statusLabel: - statusLabel && - (statusLabel.label ?? - (status === "waiting" - ? gt("Waiting", { $context: "thread status" }) - : gt("Working", { $context: "thread status" }))), - timeLabel, - snoozeWakeLabel: snoozedRow ? snoozeWakeLabelText : undefined, - providerNameLabel, - hasQueuedMessages: props.hasQueuedMessages === true, - regeneratingTitle: isRegeneratingTitle, - }, - m, - ); + // The helper names the row's meta line; a row waiting to sync is named as such after it. + const rowAccessibilityLabel = + threadListV2RowAccessibilityLabel( + { + title: thread.title, + variant, + woke: showsWoke, + // Working and waiting rows show only an icon and a duration, so name them for speech. + statusLabel: + statusLabel && + (statusLabel.label ?? + (status === "waiting" + ? gt("Waiting", { $context: "thread status" }) + : gt("Working", { $context: "thread status" }))), + timeLabel: listTimeLabel, + snoozeWakeLabel: snoozedRow ? snoozeWakeLabelText : undefined, + providerNameLabel, + hasQueuedMessages: props.hasQueuedMessages === true, + regeneratingTitle: isRegeneratingTitle, + }, + m, + ) + (pendingSync ? `, ${gt("waiting to sync")}` : ""); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false }); @@ -931,6 +940,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]); const handleRename = useCallback(() => onRenameThread(thread), [onRenameThread, thread]); const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope); + // Before the session loads, only settle, snooze and their undo are offered: they can queue. + const triageOnly = useThreadTriageScope(thread.environmentId) && !canOperateThread; + const triageAllows = (action: string) => TRIAGE_MENU_ACTION_IDS.has(action); const canShareWithGuest = useCanShareWithGuest(thread.environmentId); const navigation = useNavigation(); const handleRegenerateTitle = useCallback( @@ -1357,11 +1369,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { : null, [gt, handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title], ); - const swipeAccessibilityHint = !canOperateThread - ? gt("Opens the thread") - : secondaryAction === null - ? primaryAction.swipeHint - : primaryAction.swipeSnoozeHint; + const swipeAccessibilityHint = + !canOperateThread && !(triageOnly && triageAllows(swipeActions.primary)) + ? gt("Opens the thread") + : secondaryAction === null + ? primaryAction.swipeHint + : primaryAction.swipeSnoozeHint; const titleTextInset = props.project ? projectIconSize + 8 : 0; const cardContent = ( @@ -1747,15 +1760,16 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { )} style={{ fontFamily: MONO_FONT }} > - {snoozedRow && snoozeWakeLabelText !== undefined ? snoozeWakeLabelText : timeLabel} + {!pendingSync && snoozedRow && snoozeWakeLabelText !== undefined + ? snoozeWakeLabelText + : timeLabel} ); - if (!canOperateThread) + if (!canOperateThread && !(triageOnly && triageAllows(swipeActions.primary))) return {rowContent(() => {})}; - return ( {customSnoozeOpen && ( @@ -1783,7 +1797,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { {(close) => ( triageAllows(action.id ?? "")) + : menuActions + } onPressAction={handleMenuAction} shouldOpenOnLongPress > diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f5a0b37879c52..f1b01e35116ff 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4686,8 +4686,10 @@ "306a6f95ad9d52f7": "Nicht gesendet", "11276ab6c58b7a25": "Öffnet den Entwurf im Eingabefeld für neue Aufgaben. Nach links wischen zum Verwerfen.", "99950f3a28d425fa": "Wird gesendet, sobald die Umgebung wieder verbunden ist. Öffnet die Aufgabe zum Bearbeiten. Nach links wischen zum Löschen.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Wartet", "ad78fae7d373cf21": "Arbeitet", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Aufgeweckt-Hinweis schließen", "54ccc22be28a985d": "Benutzerdefiniert…", "bdd8716a3d6f1a53": "Threads anordnen…", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 43344b92f04ec..0dc0cf35b887e 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4687,8 +4687,10 @@ "306a6f95ad9d52f7": "Unsent", "11276ab6c58b7a25": "Opens the draft in the new task composer. Swipe left to discard.", "99950f3a28d425fa": "Sends when the environment reconnects. Opens the task for editing. Swipe left to delete.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Waiting", "ad78fae7d373cf21": "Working", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Dismiss Woke notification", "54ccc22be28a985d": "Custom…", "bdd8716a3d6f1a53": "Arrange threads…", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index ffa0249acb7c5..78abb27f8494d 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4679,8 +4679,10 @@ "306a6f95ad9d52f7": "Sin enviar", "11276ab6c58b7a25": "Abre el borrador en el cuadro de mensaje de la tarea nueva. Desliza a la izquierda para descartarlo.", "99950f3a28d425fa": "Se envía cuando el entorno se vuelve a conectar. Abre la tarea para editarla. Desliza a la izquierda para eliminarla.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Esperando", "ad78fae7d373cf21": "Trabajando", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Descartar notificación de reactivación", "54ccc22be28a985d": "Personalizado…", "bdd8716a3d6f1a53": "Organizar hilos…", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 76b6c1fee0d68..5fd79947746d8 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4680,8 +4680,10 @@ "306a6f95ad9d52f7": "Non envoyées", "11276ab6c58b7a25": "Ouvre le brouillon dans la zone de saisie de nouvelle tâche. Balayez vers la gauche pour le supprimer.", "99950f3a28d425fa": "Envoyée dès que l’environnement se reconnecte. Ouvre la tâche pour la modifier. Balayez vers la gauche pour la supprimer.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "En attente", "ad78fae7d373cf21": "En cours", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Ignorer la notification Réveillé", "54ccc22be28a985d": "Personnalisé…", "bdd8716a3d6f1a53": "Organiser les fils…", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 274edf167b42e..06373cd212c19 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4661,8 +4661,10 @@ "306a6f95ad9d52f7": "未送信", "11276ab6c58b7a25": "新しいタスクの入力欄で下書きを開きます。左にスワイプすると破棄します。", "99950f3a28d425fa": "環境に再接続すると送信します。タスクを開いて編集します。左にスワイプすると削除します。", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "待機中", "ad78fae7d373cf21": "作業中", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "再開の通知を閉じる", "54ccc22be28a985d": "カスタム…", "bdd8716a3d6f1a53": "スレッドを並べ替え…", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index d0d37ca80f4e9..aa831a61e9099 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4666,8 +4666,10 @@ "306a6f95ad9d52f7": "보내지 않음", "11276ab6c58b7a25": "새 작업 입력창에서 초안을 엽니다. 삭제하려면 왼쪽으로 스와이프하세요.", "99950f3a28d425fa": "환경이 다시 연결되면 보냅니다. 작업을 열어 편집합니다. 삭제하려면 왼쪽으로 스와이프하세요.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "대기 중", "ad78fae7d373cf21": "작업 중", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "깨어남 알림 닫기", "54ccc22be28a985d": "사용자 지정…", "bdd8716a3d6f1a53": "스레드 정렬…", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index ec401f9fa194a..545cb4db6d7fa 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4680,8 +4680,10 @@ "306a6f95ad9d52f7": "Não enviadas", "11276ab6c58b7a25": "Abre o rascunho no editor de nova tarefa. Deslize para a esquerda para descartar.", "99950f3a28d425fa": "Envia quando o ambiente se reconectar. Abre a tarefa para edição. Deslize para a esquerda para excluir.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Aguardando", "ad78fae7d373cf21": "Trabalhando", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Dispensar notificação de despertar", "54ccc22be28a985d": "Personalizado…", "bdd8716a3d6f1a53": "Organizar threads…", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 44db80a8f6808..c10f2c47806d5 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4758,8 +4758,10 @@ "306a6f95ad9d52f7": "Неотправленные", "11276ab6c58b7a25": "Открывает черновик в поле ввода новой задачи. Смахните влево, чтобы удалить.", "99950f3a28d425fa": "Отправится при переподключении окружения. Открывает задачу для редактирования. Смахните влево, чтобы удалить.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Ожидает", "ad78fae7d373cf21": "Работает", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Скрыть уведомление о пробуждении", "54ccc22be28a985d": "Другое…", "bdd8716a3d6f1a53": "Упорядочить треды…", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index e62b0c05509d9..ee016457c8db2 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4686,8 +4686,10 @@ "306a6f95ad9d52f7": "Ej skickade", "11276ab6c58b7a25": "Öppnar utkastet i inmatningsfältet för ny uppgift. Svep åt vänster för att kasta.", "99950f3a28d425fa": "Skickas när miljön återansluter. Öppnar uppgiften för redigering. Svep åt vänster för att ta bort.", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "Väntar", "ad78fae7d373cf21": "Arbetar", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "Stäng aviseringen Väckt", "54ccc22be28a985d": "Anpassat…", "bdd8716a3d6f1a53": "Ordna trådar…", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f70973a639e22..7aa6dda0fb894 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4669,8 +4669,10 @@ "306a6f95ad9d52f7": "未发送", "11276ab6c58b7a25": "在新任务输入框中打开草稿。向左滑动可丢弃。", "99950f3a28d425fa": "环境重新连接后发送。打开任务进行编辑。向左滑动可删除。", + "d71048f4fb9cf44a": "Waiting to sync", "0a260c7744afd0be": "等待中", "ad78fae7d373cf21": "运行中", + "0f3f713d5b06f223": "waiting to sync", "be451f475c514b37": "忽略已唤醒通知", "54ccc22be28a985d": "自定义…", "bdd8716a3d6f1a53": "整理会话…", diff --git a/apps/mobile/src/state/session.test.ts b/apps/mobile/src/state/session.test.ts index b47054e258663..5579da2bcc9ac 100644 --- a/apps/mobile/src/state/session.test.ts +++ b/apps/mobile/src/state/session.test.ts @@ -5,6 +5,7 @@ import { type AuthSessionState, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; @@ -33,6 +34,7 @@ import { appAtomRegistry } from "./atom-registry"; import { environmentSession, readEnvironmentScope, + readThreadTriageScope, useEnvironmentScope, useEnvironmentsWithScope, } from "./session"; @@ -100,6 +102,22 @@ it("reacts to grant revocation, failure, and regrant without a connection list c expect(changes).not.toHaveLength(0); }); +it("lets settle and snooze queue until a loaded session denies them, also after a failed refresh", () => { + const failedAfter = (canOperate: boolean) => + AsyncResult.failure(Cause.fail(new Error("Session lookup failed")), { + previousSuccess: Option.some(AsyncResult.success(session(canOperate))), + }); + expect(readThreadTriageScope(secondary)).toBe(true); + appAtomRegistry.set(source(secondary), AsyncResult.failure(Cause.fail(new Error("offline")))); + expect(readThreadTriageScope(secondary)).toBe(true); + appAtomRegistry.set(source(secondary), AsyncResult.success(session(false))); + expect(readThreadTriageScope(secondary)).toBe(false); + appAtomRegistry.set(source(secondary), failedAfter(false)); + expect(readThreadTriageScope(secondary)).toBe(false); + appAtomRegistry.set(source(secondary), failedAfter(true)); + expect(readThreadTriageScope(secondary)).toBe(true); +}); + it("uses exact new-server permissions and keeps old-server grants usable", () => { appAtomRegistry.set(source(primary), AsyncResult.success({ ...session(true), permissions: [] })); expect(useEnvironmentScope(primary, AuthOrchestrationOperateScope)).toBe(false); diff --git a/apps/mobile/src/state/session.ts b/apps/mobile/src/state/session.ts index 74876954b2716..faabba97d1913 100644 --- a/apps/mobile/src/state/session.ts +++ b/apps/mobile/src/state/session.ts @@ -4,6 +4,7 @@ import { sessionDeniesScope, } from "@t3tools/client-runtime/state/session"; import { + AuthOrchestrationOperateScope, type AuthEnvironmentScope, type AuthSessionState, type EnvironmentId, @@ -83,6 +84,33 @@ export function readEnvironmentScope( return sessionHasScope(result, scope); } +/** + * Settle and snooze can queue for an environment whose session has not loaded yet, such as one + * that was offline at launch. The server checks the grant when the change is sent. + */ +function sessionAllowsThreadTriage( + result: AsyncResult.AsyncResult, +): boolean { + // A failed refresh still carries the last loaded session, whose answer stands. + const session = AsyncResult.getOrElse(result, () => null); + return session === null || sessionGrantsScope(session, AuthOrchestrationOperateScope); +} + +export function useThreadTriageScope(environmentId: EnvironmentId | null): boolean { + return useAtomValue( + environmentId === null + ? EMPTY_SESSION_STATE_ATOM + : environmentSession.sessionStateAtom(environmentId), + sessionAllowsThreadTriage, + ); +} + +export function readThreadTriageScope(environmentId: EnvironmentId): boolean { + return sessionAllowsThreadTriage( + appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)), + ); +} + const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe( Atom.withLabel("mobile-prepared-connection:empty"), ); diff --git a/apps/mobile/src/state/thread-triage-outbox-storage.ts b/apps/mobile/src/state/thread-triage-outbox-storage.ts new file mode 100644 index 0000000000000..26b531518a9d2 --- /dev/null +++ b/apps/mobile/src/state/thread-triage-outbox-storage.ts @@ -0,0 +1,20 @@ +import { + makeThreadTriageOutboxStore, + ThreadTriageOutboxStorageError, +} from "@t3tools/client-runtime/platform"; +import * as Effect from "effect/Effect"; + +import { writeFileAtomically } from "../lib/atomic-file"; + +/** A file outside the client cache, so clearing cached data keeps unsynced settles and snoozes. */ +export const mobileThreadTriageOutboxStore = makeThreadTriageOutboxStore((next) => + Effect.tryPromise({ + try: async () => { + const { File, Paths } = await import("expo-file-system"); + const file = new File(Paths.document, "thread-triage-outbox.json"); + const value = next(file.exists ? await file.text() : null); + if (value !== null) await writeFileAtomically(file, value); + }, + catch: (cause) => new ThreadTriageOutboxStorageError({ cause }), + }), +); diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index bf2013aef5398..a0acea9187249 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -37,6 +37,7 @@ export const olderSettledThreads = createOlderSettledThreadAtoms( export const threadEnvironment = createThreadEnvironmentAtoms( connectionAtomRuntime, threadFamilies.snapshotAtom, + environmentShell.statusAtom, ); export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime); export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 86a2d04c53eef..368f9c4cd0803 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -161,7 +161,7 @@ import { threadEnvironment } from "../state/threads"; import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf"; import { useThreadSearch } from "../state/queries"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; -import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; +import { readEnvironmentScope, readThreadTriageScope, useEnvironmentScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; import { openGuestShareDialog } from "./chat/guestShareDialogState"; @@ -178,6 +178,7 @@ import { ProjectRowActions } from "./ProjectComboboxRow"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, + isThreadTriageAction, threadActionRequiresOperate, } from "./threadActionMenu.logic"; import { @@ -866,18 +867,23 @@ function ProjectScopeRowIcon(props: { isSelected: boolean; children: ReactNode } ); } +/** Settle, snooze and their undo can queue before the environment's session loads. */ function canOperateThreads( threads: ReadonlyArray>, + triage = false, ): boolean { return threads.every((thread) => - readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope), + triage + ? readThreadTriageScope(thread.environmentId) + : readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope), ); } function checkThreadOperations( threads: ReadonlyArray>, + triage = false, ): boolean { - if (canOperateThreads(threads)) return true; + if (canOperateThreads(threads, triage)) return true; toastManager.add({ type: "error", title: m(msg("Thread action unavailable")), @@ -2353,26 +2359,26 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve { id: "settle", label: gt("Settle ({count})", { count }), - disabled: settlingThreads.length === 0 || !canOperateThreads(settlingThreads), + disabled: settlingThreads.length === 0 || !canOperateThreads(settlingThreads, true), }, ...(canSnoozeSelection ? [ { id: "snooze", label: gt("Snooze ({count})", { count }), - disabled: !canOperateThreads(selectedThreads), + disabled: !canOperateThreads(selectedThreads, true), children: [ ...snoozePresets.map((preset) => ({ id: `snooze:${preset.id}`, label: preset.label, detail: preset.whenLabel, - disabled: !canOperateThreads(selectedThreads), + disabled: !canOperateThreads(selectedThreads, true), })), { id: "snooze:custom", label: gt("Custom…"), separatorBefore: snoozePresets.length > 0, - disabled: !canOperateThreads(selectedThreads), + disabled: !canOperateThreads(selectedThreads, true), }, ], }, @@ -2415,7 +2421,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) : selectedThreads; if (clicked.value === "settle" && actionTargets.length === 0) return; - if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return; + if ( + clicked.value !== "mark-unread" && + !checkThreadOperations(actionTargets, isThreadTriageAction(clicked.value)) + ) + return; if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" @@ -2664,6 +2674,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threadRef.environmentId, AuthOrchestrationOperateScope, ), + canTriage: readThreadTriageScope(threadRef.environmentId), branch: thread.branch ?? null, // An archived project is not a filter choice. projectFilter: @@ -2699,7 +2710,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ); if (clicked._tag === "Failure" || clicked.value === null) return; - if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return; + if ( + threadActionRequiresOperate(clicked.value) && + !checkThreadOperations([thread], isThreadTriageAction(clicked.value)) + ) + return; if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index 54989e73c4bc6..35d36882e37be 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -56,7 +56,7 @@ import { titleRegenerationToast } from "../threadTitleRegenerationToast"; import { newMessageId } from "~/lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore"; -import { useEnvironmentScope } from "~/state/session"; +import { useEnvironmentScope, useThreadTriageScope } from "~/state/session"; import { threadEnvironment } from "../../state/threads"; import { vcsEnvironment } from "../../state/vcs"; import { useChildThreadInputs, readThreadShell, waitForThreadShell } from "../../state/entities"; @@ -65,7 +65,7 @@ import { environmentShell } from "../../state/shell"; import { ThreadStatusLine } from "./ThreadStatusLine"; import { formatRelativeTimeLabel } from "../../timestampFormat"; import { appAtomRegistry } from "../../rpc/atomRegistry"; -import { readEnvironmentScope } from "../../state/session"; +import { readEnvironmentScope, readThreadTriageScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { useOrchestrationCommand } from "../../state/use-orchestration-command"; import { @@ -192,6 +192,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { const router = useRouter(); const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions(); const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); + const canTriageThread = useThreadTriageScope(environmentId); const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { reportFailure: false, @@ -242,17 +243,15 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { }); const activeThreadSettled = serverConfigLoaded && activeThreadShell?.settledOverride === "settled"; - const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, { - reportFailure: false, - }); + const unsettleThreadMutation = useOrchestrationCommand( + threadEnvironment.unsettle, + { reportFailure: false }, + readThreadTriageScope, + ); const [unsettlingThreadKey, setUnsettlingThreadKey] = useState(null); const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey; const handleUnsettleActiveThread = async () => { - if ( - !activeThreadRef || - !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) - ) - return; + if (!activeThreadRef || !readThreadTriageScope(activeThreadRef.environmentId)) return; const threadKey = scopedThreadKey(activeThreadRef); setUnsettlingThreadKey(threadKey); // Commands settle into a result, so this always runs. @@ -273,17 +272,15 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { setUnsettlingThreadKey((current) => (current === threadKey ? null : current)); }; const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread); - const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, { - reportFailure: false, - }); + const unsnoozeThreadMutation = useOrchestrationCommand( + threadEnvironment.unsnooze, + { reportFailure: false }, + readThreadTriageScope, + ); const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState(null); const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey; const handleUnsnoozeActiveThread = async () => { - if ( - !activeThreadRef || - !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) - ) - return; + if (!activeThreadRef || !readThreadTriageScope(activeThreadRef.environmentId)) return; const threadKey = scopedThreadKey(activeThreadRef); setUnsnoozingThreadKey(threadKey); // Commands settle into a result, so this always runs. @@ -651,7 +648,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { } clockMinute={nowMinute} actionLabel={isUnsnoozing ? gt("Waking...") : gt("Wake now")} - actionDisabled={!canOperateThread || isUnsnoozing} + actionDisabled={!canTriageThread || isUnsnoozing} onAction={() => void handleUnsnoozeActiveThreadStable()} /> ) @@ -665,7 +662,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { } clockMinute={nowMinute} actionLabel={isUnsettling ? gt("Un-settling...") : gt("Un-settle")} - actionDisabled={!canOperateThread || isUnsettling} + actionDisabled={!canTriageThread || isUnsettling} onAction={() => void handleUnsettleActiveThreadStable()} /> ) : activeThreadWokeVisible ? ( @@ -690,7 +687,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { }; const shortcuts = { "thread.settle": () => { - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; + if (!readThreadTriageScope(environmentId)) return false; if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; if (activeThreadSettled) { void handleUnsettleActiveThread(); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 3e1695e63f0a7..5991a364cf05d 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1,4 +1,4 @@ -import { useAtomMount } from "@effect/atom-react"; +import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; @@ -80,7 +80,12 @@ import { useNowSecond } from "../../hooks/useNowSecond"; import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs"; import { useLinkedIssueDetail } from "../../state/issues"; import { useEnvironmentQuery } from "../../state/query"; -import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; +import { threadEnvironment } from "../../state/threads"; +import { + readEnvironmentScope, + useEnvironmentScope, + useThreadTriageScope, +} from "../../state/session"; import { formatRelativeTime, parseTimestampDate } from "../../timestampFormat"; import type { SidebarThreadSummary } from "../../types"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; @@ -153,6 +158,19 @@ function compactSidebarTimeLabel(timestamp: string, nowMs: number, resolve: Mess return parts.suffix === null ? resolve(msg("now", { $context: "relative time" })) : parts.value; } +function PendingSyncLabel() { + return ( + + }> + Pending + + + Waiting to sync with its environment + + + ); +} + // Subscribes to the minute tick itself, so only the label re-renders each // minute. The minute is passed as the clock so it is the formatter's input. function RelativeTimeLabel(props: { timestamp: string | null }) { @@ -704,6 +722,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const threadRef = scopeThreadRef(thread.environmentId, thread.id); const threadKey = scopedThreadKey(threadRef); const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope); + const canTriageThread = useThreadTriageScope(thread.environmentId); + const pendingSync = useAtomValue(threadEnvironment.pendingSyncAtom(thread.environmentId)).has( + thread.id, + ); const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive); const { revealRef } = props; const rowRef = (row: HTMLElement | null) => { @@ -992,7 +1014,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP setSnoozeGateClock({ thread, now: new Date(snoozeGateOpensAt).toISOString() }); } const showSnoozeButton = - canOperateThread && props.snoozeSupported && canSnooze(thread, { now: snoozeGateNow }); + canTriageThread && props.snoozeSupported && canSnooze(thread, { now: snoozeGateNow }); // Closing here, not just masking, keeps the menu from reopening when the button returns. if (snoozeMenuOpenRaw && !showSnoozeButton) setSnoozeMenuOpen(false); const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; @@ -1063,7 +1085,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const accessibility = resolveSidebarRowAccessibility({ title: thread.title, - statusLabel: topStatus?.label ?? null, + statusLabel: pendingSync ? gt("Pending") : (topStatus?.label ?? null), projectDisplayName: props.projectDisplayName, isActive: props.isActive, }); @@ -1408,7 +1430,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP !isWoke && "group-any-hover/sidebar-row:opacity-0", )} > - {variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( + {pendingSync ? ( + + + + ) : variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( {/* The clock tells a wake time from an age at a glance. */} @@ -1607,7 +1633,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0", )} > - {topStatus ? ( + {pendingSync ? ( + + ) : topStatus ? ( isWokeStatus ? ( { }, ); + it.each([false, true])( + "keeps settle, snooze and their undo before the session loads (reversed: %s)", + (reversed) => { + const items = buildThreadActionMenuItems({ + ...baseState, + canOperate: false, + canTriage: true, + isPinned: reversed, + isSettled: reversed, + isSnoozed: reversed, + }); + expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual([ + reversed ? "unpin" : "pin", + "rename", + "regenerate-title", + "auto-settle", + "archive", + "delete", + ]); + expect( + items.find((item) => item.id === "snooze")?.children?.some((child) => child.disabled) ?? + false, + ).toBe(false); + }, + ); + it("disables archive and turning into a project while the thread is running", () => { const items = buildThreadActionMenuItems({ ...baseState, diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index dc2d7687a2be6..96d874bd3c2c0 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -95,6 +95,8 @@ export function buildDraftActionMenuItems( export interface ThreadActionMenuState { readonly canOperate: boolean; + /** Settle, snooze and their undo can queue before the environment's session loads. */ + readonly canTriage?: boolean; readonly canFind?: boolean; /** False where no inline title editor is rendered, such as sidebar search results. */ readonly canRename?: boolean; @@ -141,6 +143,16 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean ].includes(action); } +export function isThreadTriageAction(action: string): boolean { + return ( + action === "settle" || + action === "unsettle" || + action === "snooze" || + action === "unsnooze" || + action.startsWith("snooze:") + ); +} + export function buildThreadActionMenuItems( state: ThreadActionMenuState, resolve: MessageResolver = m, @@ -311,7 +323,8 @@ export function buildThreadActionMenuItems( return state.canOperate ? items : items.map((item) => - threadActionRequiresOperate(item.id) + threadActionRequiresOperate(item.id) && + !(state.canTriage === true && isThreadTriageAction(item.id)) ? { ...item, disabled: true, diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index ee28ca37202f9..7fa47da4bb14f 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -62,6 +62,7 @@ import { type DesktopSecondaryBootstrapsRead, } from "./desktopLocal"; import * as ConnectionStorage from "./storage"; +import { browserThreadTriageOutboxStore } from "./threadTriageOutboxStore"; import { clientPresentationMetadata } from "./clientMetadata"; import { m } from "../i18n/messages"; @@ -841,7 +842,11 @@ const layerEnvironmentOwnedDataCleanup = Layer.succeed( clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) { return Effect.sync(() => { clearComposerDraftsEnvironment(environmentId); - }); + }).pipe( + Effect.andThen( + Effect.ignore(browserThreadTriageOutboxStore.clearEnvironment(environmentId)), + ), + ); }), }), ); diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts index b56ec9a18db32..d0bc8f5b66ecf 100644 --- a/apps/web/src/connection/storage.ts +++ b/apps/web/src/connection/storage.ts @@ -14,6 +14,7 @@ import { setRoutesInCatalog, replaceCatalogValue, Persistence, + ThreadTriageOutboxStore, makeStoredShellSnapshotEncoder, makeStoredThreadSnapshotEncoder, makeThreadCacheWriteOrder, @@ -44,6 +45,7 @@ import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import { m } from "../i18n/messages"; import { projectFaviconCache } from "../assets/projectFaviconCache"; +import { browserThreadTriageOutboxStore } from "./threadTriageOutboxStore"; const DATABASE_NAME = "t3code:connection-runtime"; const DATABASE_VERSION = 5; @@ -1143,6 +1145,7 @@ export const layer = Layer.effectContext( Context.add(CredentialStore.ConnectionCredentialStore, credentialStore), Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore), Context.add(Persistence.EnvironmentCacheStore, cacheStore), + Context.add(ThreadTriageOutboxStore, browserThreadTriageOutboxStore), Context.add(EnvironmentQueryStore, queryStore), ); }), diff --git a/apps/web/src/connection/threadTriageOutboxStore.ts b/apps/web/src/connection/threadTriageOutboxStore.ts new file mode 100644 index 0000000000000..2177ab3d441bf --- /dev/null +++ b/apps/web/src/connection/threadTriageOutboxStore.ts @@ -0,0 +1,18 @@ +import { + makeThreadTriageOutboxStore, + ThreadTriageOutboxStorageError, +} from "@t3tools/client-runtime/platform"; +import * as Effect from "effect/Effect"; + +const KEY = "t3code:thread-triage-outbox"; + +/** In localStorage, so tabs share it and clearing the environment cache keeps unsynced changes. */ +export const browserThreadTriageOutboxStore = makeThreadTriageOutboxStore((next) => + Effect.try({ + try: () => { + const value = next(window.localStorage.getItem(KEY)); + if (value !== null) window.localStorage.setItem(KEY, value); + }, + catch: (cause) => new ThreadTriageOutboxStorageError({ cause }), + }), +); diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 3c8255b04c088..564764d1f6b04 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -45,6 +45,7 @@ vi.mock("@tanstack/react-router", () => ({ vi.mock("../state/session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => scope === AuthOrchestrationOperateScope && state.granted.has(environmentId), + readThreadTriageScope: (environmentId: string) => state.granted.has(environmentId), })); vi.mock("../state/entities", () => ({ readEnvironmentServerConfigLoaded: () => true, diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 4e5914d078c57..f887e9deaefb4 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -20,6 +20,7 @@ import { msg } from "gt-react"; import { pickSnoozePreset, resolveSnoozePresets } from "../components/Sidebar.snooze"; import { buildThreadActionMenuItems, + isThreadTriageAction, threadActionRequiresOperate, type ThreadActionMenuId, } from "../components/threadActionMenu.logic"; @@ -30,7 +31,7 @@ import { m } from "../i18n/messages"; import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; import { threadEnvironment } from "../state/threads"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; -import { readEnvironmentScope } from "../state/session"; +import { readEnvironmentScope, readThreadTriageScope } from "../state/session"; import { readEnvironmentServerConfigLoaded, readEnvironmentSupportsAutoSettleOptOut, @@ -140,6 +141,7 @@ export function useThreadActionMenu(input: { const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), + canTriage: readThreadTriageScope(threadRef.environmentId), canFind: onFind !== undefined, branch: thread.branch ?? null, projectFilter: null, @@ -160,7 +162,9 @@ export function useThreadActionMenu(input: { const action: ThreadActionMenuId = clicked.value; if ( threadActionRequiresOperate(action) && - !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) + !(isThreadTriageAction(action) + ? readThreadTriageScope(threadRef.environmentId) + : readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) ) { failureToast( m(msg("Thread action unavailable")), diff --git a/apps/web/src/hooks/useThreadActions.permissions.test.ts b/apps/web/src/hooks/useThreadActions.permissions.test.ts index c15dc90bb11f3..a56f3805827ac 100644 --- a/apps/web/src/hooks/useThreadActions.permissions.test.ts +++ b/apps/web/src/hooks/useThreadActions.permissions.test.ts @@ -27,6 +27,7 @@ const state = vi.hoisted(() => ({ serverConfig: { shellThreadFamilies: false }, familyLookupFails: false, scopes: new Map>(), + sessionNotLoaded: new Set(), threads: [] as { environmentId: EnvironmentId; id: ThreadId; @@ -70,6 +71,9 @@ vi.mock("../state/session", () => ({ environmentSession: { sessionStateAtom: "session" }, readEnvironmentScope: (environmentId: string, scope: string) => state.scopes.get(environmentId)?.has(scope) === true, + readThreadTriageScope: (environmentId: string) => + state.scopes.get(environmentId)?.has(AuthOrchestrationOperateScope) === true || + state.sessionNotLoaded.has(environmentId), })); vi.mock("../state/use-atom-command", () => ({ useAtomCommand: @@ -78,7 +82,11 @@ vi.mock("../state/use-atom-command", () => ({ state.requests.push({ action, ...request }); const scope = action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope; - if (!state.scopes.get(request.environmentId)?.has(scope)) { + // Without a loaded session the command itself queues settle and snooze. + if ( + !state.scopes.get(request.environmentId)?.has(scope) && + !state.sessionNotLoaded.has(request.environmentId) + ) { return AsyncResult.failure(Cause.fail(new Error("Server denied the request"))); } state.afterRequest?.(action); @@ -280,6 +288,7 @@ beforeEach(() => { latestTurn: null, }, ]; + state.sessionNotLoaded = new Set(); state.requests = []; state.localEffects = []; state.confirm.mockReset().mockResolvedValue(true); @@ -320,6 +329,17 @@ describe("thread action permissions", () => { }, ); + it.each(operations)( + "$name runs before the session loads only for settle, snooze and their undo", + async ({ name, run }) => { + state.sessionNotLoaded.add(secondary); + const result = await run(useThreadActions(), target); + const triage = ["settle", "unsettle", "snooze", "unsnooze"].includes(name); + expect(result._tag).toBe(triage ? "Success" : "Failure"); + expect(state.requests.map(({ action }) => action)).toEqual(triage ? [name] : []); + }, + ); + it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)( "%s blocks a forbidden confirmation", async (action) => { diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 2a591127044d1..5ce7b0d4080b7 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -26,7 +26,7 @@ import { useRouter } from "@tanstack/react-router"; import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic"; import { useComposerDraftStore } from "../composerDraftStore"; -import { environmentSession, readEnvironmentScope } from "../state/session"; +import { environmentSession, readEnvironmentScope, readThreadTriageScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; @@ -310,12 +310,16 @@ export function useThreadActions() { const deleteThreadMutation = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false, }); - const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, { - reportFailure: false, - }); - const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, { - reportFailure: false, - }); + const settleThreadMutation = useOrchestrationCommand( + threadEnvironment.settle, + { reportFailure: false }, + readThreadTriageScope, + ); + const unsettleThreadMutation = useOrchestrationCommand( + threadEnvironment.unsettle, + { reportFailure: false }, + readThreadTriageScope, + ); const pinThreadMutation = useOrchestrationCommand(threadEnvironment.pin, { reportFailure: false, }); @@ -331,12 +335,16 @@ export function useThreadActions() { const reorderActiveThreadMutation = useOrchestrationCommand(threadEnvironment.reorderActive, { reportFailure: false, }); - const snoozeThreadMutation = useOrchestrationCommand(threadEnvironment.snooze, { - reportFailure: false, - }); - const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, { - reportFailure: false, - }); + const snoozeThreadMutation = useOrchestrationCommand( + threadEnvironment.snooze, + { reportFailure: false }, + readThreadTriageScope, + ); + const unsnoozeThreadMutation = useOrchestrationCommand( + threadEnvironment.unsnooze, + { reportFailure: false }, + readThreadTriageScope, + ); const markThreadUnread = useMarkThreadUnread(); const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, { reportFailure: false, @@ -992,18 +1000,25 @@ export function useThreadActions() { return result; }; - const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) => - ThreadUndo.executeThreadUndo( + const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) => { + let cancelledQueued = false; + return ThreadUndo.executeThreadUndo( plan, async (step) => { switch (step.action) { - case "unsettle": - return unsettleThread(target, step.restoreUnsettledAt); + case "unsettle": { + const result = await unsettleThread(target, step.restoreUnsettledAt); + cancelledQueued = + result._tag === "Success" && ThreadUndo.cancelledPendingSync(result.value); + return result; + } case "unsnooze": return unsnoozeThread(target); case "pin": + if (cancelledQueued) return AsyncResult.success(undefined); return sendPin(target, step.orderKey === undefined ? {} : { orderKey: step.orderKey }); case "reorderActive": + if (cancelledQueued) return AsyncResult.success(undefined); return reorderActiveThread(target, step.orderKey); case "snooze": return snoozeThreadMutation({ @@ -1014,6 +1029,7 @@ export function useThreadActions() { }, (result) => result._tag === "Success", ); + }; const confirmAndDeleteThread = async (target: ScopedThreadRef, knownTitle?: string) => { const permissionFailure = threadOperationFailure(target); diff --git a/apps/web/src/hooks/useThreadActions.undo.test.ts b/apps/web/src/hooks/useThreadActions.undo.test.ts index aa6bb76437c2c..d58347fa630d2 100644 --- a/apps/web/src/hooks/useThreadActions.undo.test.ts +++ b/apps/web/src/hooks/useThreadActions.undo.test.ts @@ -120,6 +120,7 @@ beforeEach(() => { for (const command of Object.values(commands)) { command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined }); } + commands.settle.mockResolvedValue({ _tag: "Success", value: { sequence: 1 } }); router.navigate.mockClear(); router.state.location.href = "/"; router.state.matches[0]!.params = {}; @@ -318,6 +319,35 @@ describe("settle and snooze Undo", () => { }); }); + // Whether the queued settle reached the server is known only when Undo runs. + it.each([ + ["cancels it before it syncs", { sequence: 0, cancelledPendingSync: true }, 0], + ["finds it delivered", { sequence: 3 }, 1], + ] as const)( + "restores a queued settle only as far as needed when Undo %s", + async (_, undone, restorations) => { + const snoozedUntil = "2030-01-01T09:00:00.000Z"; + threadShell.pinnedAt = "2026-01-01T00:00:00.000Z"; + threadShell.snoozedUntil = snoozedUntil; + commands.unsettle.mockResolvedValue({ _tag: "Success", value: undone }); + await useThreadActions().settleThread(target); + expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 }); + await currentUndo()(); + expect(commands.unsettle).toHaveBeenCalledExactlyOnceWith({ + environmentId: target.environmentId, + input: { threadId: target.threadId, reason: "user", restoreUnsettledAt: null }, + }); + expect(commands.pin).toHaveBeenCalledTimes(restorations); + expect(commands.snooze).toHaveBeenCalledOnce(); + if (restorations > 0) { + expect(commands.snooze).toHaveBeenCalledWith({ + environmentId: target.environmentId, + input: { threadId: target.threadId, snoozedUntil }, + }); + } + }, + ); + it("puts a manually ordered thread back in its active position", async () => { threadShell.activeOrderKey = "b5"; await useThreadActions().settleThread(target); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7b125c6298aa4..f861305d8ffe5 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -4084,6 +4084,7 @@ "66be4fb43249bbd2": "{used} von {max} Tokens", "ee3ae58c8b38a425": "{left} % übrig", "ebb26f93fb83a71b": "{label}: {left} % übrig", + "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.", @@ -11679,11 +11680,14 @@ "37ffec8201f153c1": "Fehlgeschlagen", "984b361806ce8d25": "Aufgeweckt", "c6e8abc00ae470d2": "Fertig", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Issue {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} verknüpftes Issue} other {{count} verknüpfte Issues}}", "8cf699ae75fd8067": "Angeheftet", "be451f475c514b37": "Aufgeweckt-Hinweis schließen", "e9ced65134f2f36c": "Thread jetzt aufwecken", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Du hast gerade einen anderen Branch ausgecheckt.", "f665b5be60d8c144": [ "Übergeben von ", @@ -11858,7 +11862,6 @@ "0bd938825ffcf992": "+{percent} % des Kontingents", "09c0e00d7fb55402": "Reset-Guthaben wird verwendet…", "4df3ff1be768a7ab": "{name}: {remaining} % übrig", - "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", "a16b48709357a5a7": "Nutzung verwalten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..3a5c2a96ccaf1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -4083,6 +4083,7 @@ "66be4fb43249bbd2": "{used} of {max} tokens", "ee3ae58c8b38a425": "{left}% left", "ebb26f93fb83a71b": "{label}: {left}% left", + "1b16346722b65812": "{timeLeft}% of the window left", "728c6cc1431e76c8": "Resets in {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.", @@ -11687,11 +11688,14 @@ "37ffec8201f153c1": "Failed", "984b361806ce8d25": "Woke", "c6e8abc00ae470d2": "Done", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Issue {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} linked issue} other {{count} linked issues}}", "8cf699ae75fd8067": "Pinned", "be451f475c514b37": "Dismiss Woke notification", "e9ced65134f2f36c": "Wake thread now", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "You're currently checked out on another branch.", "f665b5be60d8c144": [ "Handed off from ", @@ -11866,7 +11870,6 @@ "0bd938825ffcf992": "+{percent}% of pool", "09c0e00d7fb55402": "Using reset credit…", "4df3ff1be768a7ab": "{name}: {remaining}% left", - "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", "a16b48709357a5a7": "Manage usage", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2bf075b8cde09..70ac0774fbe20 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left} % restante", "ebb26f93fb83a71b": "{label}: {left} % restante", + "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "728c6cc1431e76c8": "Se restablece en {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.", @@ -11672,11 +11673,14 @@ "37ffec8201f153c1": "Falló", "984b361806ce8d25": "Reactivado", "c6e8abc00ae470d2": "Hecho", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Incidencia {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} incidencia vinculada} other {{count} incidencias vinculadas}}", "8cf699ae75fd8067": "Fijados", "be451f475c514b37": "Descartar notificación de reactivación", "e9ced65134f2f36c": "Reactivar hilo ahora", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Ahora mismo tienes otra rama en el checkout.", "f665b5be60d8c144": [ "Traspasado desde ", @@ -11851,7 +11855,6 @@ "0bd938825ffcf992": "+{percent}% del total", "09c0e00d7fb55402": "Usando el crédito de restablecimiento…", "4df3ff1be768a7ab": "{name}: queda un {remaining}%", - "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", "a16b48709357a5a7": "Gestionar uso", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 57f3b582c471c..3f1d8b1253c5c 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -4082,6 +4082,7 @@ "66be4fb43249bbd2": "{used} tokens sur {max}", "ee3ae58c8b38a425": "{left} % restant", "ebb26f93fb83a71b": "{label} : {left} % restant", + "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}", "e16b0b9b490c8bc7": "{label} : {value}", "ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.", @@ -11677,11 +11678,14 @@ "37ffec8201f153c1": "Échec", "984b361806ce8d25": "Réveillé", "c6e8abc00ae470d2": "Terminé", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Ticket {key} : {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} ticket lié} other {{count} tickets liés}}", "8cf699ae75fd8067": "Épinglés", "be451f475c514b37": "Ignorer la notification Réveillé", "e9ced65134f2f36c": "Réveiller le fil maintenant", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Vous êtes actuellement sur une autre branche.", "f665b5be60d8c144": [ "Transféré depuis ", @@ -11856,7 +11860,6 @@ "0bd938825ffcf992": "+{percent} % du quota", "09c0e00d7fb55402": "Utilisation du crédit de réinitialisation…", "4df3ff1be768a7ab": "{name} : {remaining} % restant", - "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", "a16b48709357a5a7": "Gérer l’utilisation", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 1032927325af6..f78f7e6f9ef09 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -4072,6 +4072,7 @@ "66be4fb43249bbd2": "{used} / {max} トークン", "ee3ae58c8b38a425": "残り {left}%", "ebb26f93fb83a71b": "{label}: 残り {left}%", + "1b16346722b65812": "期間の残り {timeLeft}%", "728c6cc1431e76c8": "{duration} 後にリセット · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。", @@ -11627,11 +11628,14 @@ "37ffec8201f153c1": "失敗", "984b361806ce8d25": "再開", "c6e8abc00ae470d2": "完了", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "課題 {key}: {title}、{state}", "2dd9d295c882ef65": "{count, plural, other {{count} 件のリンクされた課題}}", "8cf699ae75fd8067": "ピン留め済み", "be451f475c514b37": "再開の通知を閉じる", "e9ced65134f2f36c": "スレッドを今すぐ再開", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "現在、別のブランチをチェックアウトしています。", "f665b5be60d8c144": [ { @@ -11806,7 +11810,6 @@ "0bd938825ffcf992": "プールの +{percent}%", "09c0e00d7fb55402": "リセットクレジットを使用しています…", "4df3ff1be768a7ab": "{name}: 残り {remaining}%", - "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "使用量を管理", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index d918ed423daef..2c6ac1dbea23b 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -4069,6 +4069,7 @@ "66be4fb43249bbd2": "토큰 {max}개 중 {used}개", "ee3ae58c8b38a425": "{left}% 남음", "ebb26f93fb83a71b": "{label}: {left}% 남음", + "1b16346722b65812": "기간 {timeLeft}% 남음", "728c6cc1431e76c8": "{duration} 후 초기화 · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.", @@ -11624,11 +11625,14 @@ "37ffec8201f153c1": "실패", "984b361806ce8d25": "깨어남", "c6e8abc00ae470d2": "완료", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "이슈 {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, other {연결된 이슈 {count}개}}", "8cf699ae75fd8067": "고정됨", "be451f475c514b37": "깨어남 알림 닫기", "e9ced65134f2f36c": "지금 스레드 깨우기", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "현재 다른 브랜치를 체크아웃한 상태입니다.", "f665b5be60d8c144": [ { @@ -11803,7 +11807,6 @@ "0bd938825ffcf992": "풀의 +{percent}%", "09c0e00d7fb55402": "초기화 크레딧 사용 중…", "4df3ff1be768a7ab": "{name}: {remaining}% 남음", - "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", "a16b48709357a5a7": "사용량 관리", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f2a498937efd8..6fe51c31668f1 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left}% restante", "ebb26f93fb83a71b": "{label}: {left}% restante", + "1b16346722b65812": "{timeLeft}% da janela restante", "728c6cc1431e76c8": "Renova em {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.", @@ -11676,11 +11677,14 @@ "37ffec8201f153c1": "Falhou", "984b361806ce8d25": "Despertou", "c6e8abc00ae470d2": "Pronta", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Issue {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} issue vinculada} other {{count} issues vinculadas}}", "8cf699ae75fd8067": "Fixadas", "be451f475c514b37": "Dispensar notificação de despertar", "e9ced65134f2f36c": "Despertar thread agora", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Você está com outro branch em checkout no momento.", "f665b5be60d8c144": [ "Transferida de ", @@ -11855,7 +11859,6 @@ "0bd938825ffcf992": "+{percent}% do total", "09c0e00d7fb55402": "Usando crédito de redefinição…", "4df3ff1be768a7ab": "{name}: {remaining}% restante", - "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", "a16b48709357a5a7": "Gerenciar uso", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5823e9e268e26..bc7a4d637963e 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} из {max} токенов", "ee3ae58c8b38a425": "Осталось {left}%", "ebb26f93fb83a71b": "{label}: осталось {left}%", + "1b16346722b65812": "От окна осталось {timeLeft}%", "728c6cc1431e76c8": "Сброс через {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.", @@ -11677,11 +11678,14 @@ "37ffec8201f153c1": "Ошибка", "984b361806ce8d25": "Проснулся", "c6e8abc00ae470d2": "Готово", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Задача {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} связанная задача} few {{count} связанные задачи} many {{count} связанных задач} other {{count} связанной задачи}}", "8cf699ae75fd8067": "Закреплённые", "be451f475c514b37": "Скрыть уведомление о пробуждении", "e9ced65134f2f36c": "Разбудить тред сейчас", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Сейчас у вас выбрана другая ветка.", "f665b5be60d8c144": [ "Передано из ", @@ -11856,7 +11860,6 @@ "0bd938825ffcf992": "+{percent}% пула", "09c0e00d7fb55402": "Использование кредита на сброс…", "4df3ff1be768a7ab": "{name}: осталось {remaining}%", - "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", "a16b48709357a5a7": "Управление использованием", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c42afb6d94fbc..53f4436230384 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -4082,6 +4082,7 @@ "66be4fb43249bbd2": "{used} av {max} token", "ee3ae58c8b38a425": "{left} % kvar", "ebb26f93fb83a71b": "{label}: {left} % kvar", + "1b16346722b65812": "{timeLeft} % av fönstret kvar", "728c6cc1431e76c8": "Återställs om {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.", @@ -11685,11 +11686,14 @@ "37ffec8201f153c1": "Misslyckades", "984b361806ce8d25": "Väckt", "c6e8abc00ae470d2": "Klar", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "Ärende {key}: {title}, {state}", "2dd9d295c882ef65": "{count, plural, one {{count} länkat ärende} other {{count} länkade ärenden}}", "8cf699ae75fd8067": "Fäst", "be451f475c514b37": "Stäng aviseringen Väckt", "e9ced65134f2f36c": "Väck tråden nu", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "Du har en annan gren utcheckad just nu.", "f665b5be60d8c144": [ "Överlämnad från ", @@ -11864,7 +11868,6 @@ "0bd938825ffcf992": "+{percent} % av poolen", "09c0e00d7fb55402": "Använder återställningskredit…", "4df3ff1be768a7ab": "{name}: {remaining} % kvar", - "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", "a16b48709357a5a7": "Hantera användning", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index beea2b7210a2a..39cc16f22bbd7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -4088,6 +4088,7 @@ "66be4fb43249bbd2": "{used} / {max} token", "ee3ae58c8b38a425": "剩余 {left}%", "ebb26f93fb83a71b": "{label}:剩余 {left}%", + "1b16346722b65812": "窗口剩余 {timeLeft}%", "728c6cc1431e76c8": "{duration} 后重置 · {time}", "e16b0b9b490c8bc7": "{label}:{value}", "ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。", @@ -11701,11 +11702,14 @@ "37ffec8201f153c1": "失败", "984b361806ce8d25": "已唤醒", "c6e8abc00ae470d2": "完成", + "353b08f4363dbb2c": "Pending", "f31a95961de19433": "议题 {key}:{title},{state}", "2dd9d295c882ef65": "{count, plural, other {{count} 个关联议题}}", "8cf699ae75fd8067": "已置顶", "be451f475c514b37": "忽略已唤醒通知", "e9ced65134f2f36c": "立即唤醒会话", + "374dac09151d4578": "Pending", + "a8f30f631e2b010e": "Waiting to sync with its environment", "aca5896600bf173e": "你当前检出的是另一个分支。", "f665b5be60d8c144": [ "从 ", @@ -11881,7 +11885,6 @@ "0bd938825ffcf992": "+{percent}%(按共享池总额度计算)", "09c0e00d7fb55402": "正在使用重置额度…", "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", - "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", "a16b48709357a5a7": "管理用量", diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.ts index f53bb3dfa9684..19744b48ecfdf 100644 --- a/apps/web/src/state/session.ts +++ b/apps/web/src/state/session.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session"; import { + AuthOrchestrationOperateScope, type AuthEnvironmentScope, type AuthSessionState, AuthRelayConfigureScope, @@ -88,6 +89,33 @@ export function readEnvironmentScope( ); } +/** + * Settle and snooze can queue for an environment whose session has not loaded yet, such as one + * that was offline at launch. The server checks the grant when the change is sent. + */ +function sessionAllowsThreadTriage( + result: AsyncResult.AsyncResult, +): boolean { + // A failed refresh still carries the last loaded session, whose answer stands. + const session = AsyncResult.getOrElse(result, () => null); + return session === null || sessionGrantsScope(session, AuthOrchestrationOperateScope); +} + +export function useThreadTriageScope(environmentId: EnvironmentId | null): boolean { + return useAtomValue( + environmentId === null + ? EMPTY_SESSION_STATE_ATOM + : environmentSession.sessionStateAtom(environmentId), + sessionAllowsThreadTriage, + ); +} + +export function readThreadTriageScope(environmentId: EnvironmentId): boolean { + return sessionAllowsThreadTriage( + appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)), + ); +} + const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe( Atom.withLabel("web-prepared-connection:empty"), ); diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6d2ce2a07c90b..1cb2749055806 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -32,6 +32,7 @@ export const olderSettledThreads = createOlderSettledThreadAtoms( export const threadEnvironment = createThreadEnvironmentAtoms( connectionAtomRuntime, threadFamilies.snapshotAtom, + environmentShell.statusAtom, ); const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime); export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( diff --git a/apps/web/src/state/use-orchestration-command.test.ts b/apps/web/src/state/use-orchestration-command.test.ts index c0ddca203f081..1087670ac58b9 100644 --- a/apps/web/src/state/use-orchestration-command.test.ts +++ b/apps/web/src/state/use-orchestration-command.test.ts @@ -54,6 +54,19 @@ it("checks the command's environment instead of borrowing the primary grant", as expect(state.run).toHaveBeenCalledWith(target(first)); }); +it("checks a caller's permission instead of the live grant on every call", async () => { + const remembered = new Set([second]); + const mutate = useOrchestrationCommand(command, { reportFailure: false }, (environmentId) => + remembered.has(environmentId), + ); + expect(await mutate(target(second))).toMatchObject({ _tag: "Success", value: "receipt" }); + remembered.clear(); + const denied = await mutate(target(second)); + assert(denied._tag === "Failure"); + expect(Cause.squash(denied.cause)).toBeInstanceOf(EnvironmentAuthorizationError); + expect(state.run).toHaveBeenCalledOnce(); +}); + it("does not dispatch a later mutation after access changes while awaiting a receipt", async () => { state.allowed.add(second); let finish: (() => void) | undefined; diff --git a/apps/web/src/state/use-orchestration-command.ts b/apps/web/src/state/use-orchestration-command.ts index cc991c0720de9..6d5063682ddbf 100644 --- a/apps/web/src/state/use-orchestration-command.ts +++ b/apps/web/src/state/use-orchestration-command.ts @@ -21,13 +21,23 @@ const ORCHESTRATION_OPERATE_DENIED_MESSAGE = msg( "This connection cannot change threads or projects.", ); +// Module scope: React Compiler cannot reorder an inline arrow used as a parameter default. +function hasLiveOperateGrant(environmentId: EnvironmentId): boolean { + return readEnvironmentScope(environmentId, AuthOrchestrationOperateScope); +} + +/** + * `permitted` replaces the operate check, so settle, snooze and their undo can queue before the + * environment's session loads. It runs on every call, like the default. + */ export function useOrchestrationCommand( command: AtomCommand, options?: string | AtomCommandOptions, + permitted: (environmentId: EnvironmentId) => boolean = hasLiveOperateGrant, ): (value: W) => Promise> { const run = useAtomCommand(command, options); return async (value: W): Promise> => { - if (!readEnvironmentScope(value.environmentId, AuthOrchestrationOperateScope)) { + if (!permitted(value.environmentId)) { return AsyncResult.failure( Cause.fail( new EnvironmentAuthorizationError({ diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 38dd4684723f9..1a5852fbba14c 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -174,6 +174,12 @@ when the thread settles** enabled in Settings > Projects > Actions. You can also that action so T3 can stop its terminal and child processes. Commands started through an agent's own shell tools are managed by the provider. +You can settle or snooze a thread while its environment is offline. The thread shows +**Waiting to sync** on mobile or **Pending** on web and desktop, and the change is sent +when the environment reconnects. If the thread changed there in the meantime, that +environment's state wins and your change is dropped, as it is when this connection cannot +change threads there. A thread with a pending settle cannot be snoozed until it syncs. + To reclaim disk space from settled work, turn on **Run in the thread's worktree when the thread settles** for one of the project's actions, or set `"runOnSettle": true` on a `t3.json` script, for example `cargo clean`. It runs each time a thread in its own diff --git a/packages/client-runtime/src/platform/index.ts b/packages/client-runtime/src/platform/index.ts index fa7be91aecd3f..33619c378e3b7 100644 --- a/packages/client-runtime/src/platform/index.ts +++ b/packages/client-runtime/src/platform/index.ts @@ -7,3 +7,4 @@ export * from "./shellCacheEncoding.ts"; export * from "./threadCacheEncoding.ts"; export * as PlatformConnectionSource from "./source.ts"; export * from "./storageDocument.ts"; +export * from "./threadTriageOutboxStore.ts"; diff --git a/packages/client-runtime/src/platform/threadTriageOutboxStore.ts b/packages/client-runtime/src/platform/threadTriageOutboxStore.ts new file mode 100644 index 0000000000000..589bdc75433f5 --- /dev/null +++ b/packages/client-runtime/src/platform/threadTriageOutboxStore.ts @@ -0,0 +1,99 @@ +import { CommandId, EnvironmentId, ThreadId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +export const PendingThreadTriage = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + commandId: CommandId, + action: Schema.Union([ + Schema.Struct({ type: Schema.Literal("settle") }), + Schema.Struct({ type: Schema.Literal("snooze"), snoozedUntil: Schema.String }), + ]), + queuedAt: Schema.DateTimeUtcFromString, + /** The thread as the user saw it; if it shows otherwise on reconnect, the change is dropped. */ + seen: Schema.String, + /** Set before the first send and never cleared: the server may have it, so only it can undo. */ + attempted: Schema.optionalKey(Schema.Literal(true)), +}); +export type PendingThreadTriage = typeof PendingThreadTriage.Type; +export type PendingThreadTriages = ReadonlyArray; + +const Stored = Schema.fromJsonString(Schema.Struct({ entries: Schema.Array(PendingThreadTriage) })); +const decodeStored = Schema.decodeUnknownExit(Stored); +const encodeStored = Schema.encodeSync(Stored); + +export class ThreadTriageOutboxStorageError extends Schema.TaggedError()( + "ThreadTriageOutboxStorageError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not save the change for later sync."; + } +} + +/** + * Settle and snooze taken while an environment is offline, kept apart from the environment + * cache so clearing the cache does not drop them. Removing the environment does. + */ +export interface ThreadTriageOutboxStoreShape { + /** Stores `change(stored)` in one step and returns it. Returning `stored` itself only reads. */ + readonly update: ( + change: (stored: PendingThreadTriages) => PendingThreadTriages, + ) => Effect.Effect; + readonly clearEnvironment: ( + environmentId: EnvironmentId, + ) => Effect.Effect; +} + +/** + * `modify` replaces the stored text with `next(stored)`, or keeps it when that is null. Text that + * no longer decodes reads as empty. + */ +export function makeThreadTriageOutboxStore( + modify: ( + next: (stored: string | null) => string | null, + ) => Effect.Effect, +): ThreadTriageOutboxStoreShape { + // Platforms whose `modify` reads and writes in separate steps rely on this to not interleave. + const lock = Semaphore.makeUnsafe(1); + const update: ThreadTriageOutboxStoreShape["update"] = (change) => + lock.withPermits(1)( + Effect.suspend(() => { + let result: PendingThreadTriages = []; + return modify((raw) => { + const decoded = raw === null ? undefined : decodeStored(raw); + const stored = + decoded !== undefined && Exit.isSuccess(decoded) ? decoded.value.entries : []; + result = change(stored); + return result === stored ? null : encodeStored({ entries: result }); + }).pipe(Effect.map(() => result)); + }), + ); + return { + update, + clearEnvironment: (environmentId) => + update((stored) => + stored.some((entry) => entry.environmentId === environmentId) + ? stored.filter((entry) => entry.environmentId !== environmentId) + : stored, + ).pipe(Effect.asVoid), + }; +} + +export class ThreadTriageOutboxStore extends Context.Reference( + "@t3tools/client-runtime/state/ThreadTriageOutboxStore", + { + defaultValue: () => { + let value: string | null = null; + return makeThreadTriageOutboxStore((next) => + Effect.sync(() => { + value = next(value) ?? value; + }), + ); + }, + }, +) {} diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index 031ef68a14502..b08a9fde70cd1 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -16,6 +16,7 @@ import * as DateTime from "effect/DateTime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Cause from "effect/Cause"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -25,6 +26,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { Atom, AtomRegistry } from "effect/reactivity"; +import { RpcClientError } from "effect/rpc"; import * as EnvironmentRegistry from "../connection/registry.ts"; import { @@ -34,7 +36,14 @@ import { } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import type { RpcSession } from "../rpc/session.ts"; +import { + makeThreadTriageOutboxStore, + ThreadTriageOutboxStorageError, + ThreadTriageOutboxStore, +} from "../platform/threadTriageOutboxStore.ts"; +import type { EnvironmentShellStatus } from "./shell.ts"; import { createThreadEnvironmentAtoms } from "./threadCommands.ts"; +import * as ThreadUndo from "./threadUndo.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; const ENVIRONMENT_ID = EnvironmentId.make("remote"); @@ -92,15 +101,33 @@ const SNAPSHOT: OrchestrationV2ShellSnapshot = { ], }; +let randomCalls = 0; + const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (options?: { readonly loadEarlier?: () => Effect.Effect; readonly reconcilePendingWork?: (threadId: ThreadId) => Effect.Effect; + readonly connected?: boolean; + /** Shared between harnesses to stand in for a restart. */ + readonly storage?: { value: string | null; failWrites?: boolean; onModify?: () => void }; }) { const requests = yield* Queue.unbounded<{ command: OrchestrationV2Command; reply: Deferred.Deferred<{ sequence: number }, Error>; }>(); const reconciled = yield* Queue.unbounded(); + const liveSession = Option.some({ + client: { + [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => + Effect.gen(function* () { + const reply = yield* Deferred.make<{ sequence: number }, Error>(); + yield* Queue.offer(requests, { command, reply }); + return yield* Deferred.await(reply); + }), + }, + } as unknown as RpcSession); + const session = yield* SubscriptionRef.make( + options?.connected === false ? Option.none() : liveSession, + ); const connectionFollowed = yield* Deferred.make(); const connection = yield* SubscriptionRef.make({ ...AVAILABLE_CONNECTION_STATE, @@ -110,23 +137,25 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: new BearerConnectionTarget({ environmentId: ENVIRONMENT_ID, - label: "Test", + label: "Mac", connectionId: "test", }), state: connection, - session: yield* SubscriptionRef.make( - Option.some({ - client: { - [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => - Effect.gen(function* () { - const reply = yield* Deferred.make<{ sequence: number }, Error>(); - yield* Queue.offer(requests, { command, reply }); - return yield* Deferred.await(reply); - }), - }, - } as unknown as RpcSession), - ), + session, } as EnvironmentSupervisor.EnvironmentSupervisor["Service"]); + const storage = options?.storage ?? { value: null }; + const store = makeThreadTriageOutboxStore((next) => + Effect.suspend(() => { + storage.onModify?.(); + const value = next(storage.value); + if (value === null) return Effect.void; + if (storage.failWrites) { + return Effect.fail(new ThreadTriageOutboxStorageError({ cause: "disk full" })); + } + storage.value = value; + return Effect.void; + }), + ); const runtime = Atom.runtime( Layer.mergeAll( Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, { @@ -141,8 +170,10 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio } as EnvironmentRegistry.EnvironmentRegistry["Service"]), Layer.succeed( SecureRandom.SecureRandom, - SecureRandom.make((size) => new Uint8Array(size)), + // Distinct bytes per call, so each queued change gets its own command id. + SecureRandom.make((size) => new Uint8Array(size).fill(++randomCalls % 256)), ), + Layer.succeed(ThreadTriageOutboxStore, store), Layer.succeed( ThreadHistoryController.ThreadHistoryController, ThreadHistoryController.ThreadHistoryController.of({ @@ -158,18 +189,36 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(SNAPSHOT), ); - const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom); + const statusAtom = Atom.family((_environmentId: EnvironmentId) => + Atom.make(options?.connected === false ? "cached" : "live"), + ); + const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom, statusAtom); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); const visibleAtom = commands.snapshotAtom(ENVIRONMENT_ID); registry.mount(visibleAtom); + const pendingSyncAtom = commands.pendingSyncAtom(ENVIRONMENT_ID); + registry.mount(pendingSyncAtom); + const reconnect = (status: EnvironmentShellStatus = "live") => + SubscriptionRef.set(session, liveSession).pipe( + Effect.andThen(Effect.sync(() => registry.set(statusAtom(ENVIRONMENT_ID), status))), + ); + const disconnect = SubscriptionRef.set(session, Option.none()).pipe( + Effect.andThen(Effect.sync(() => registry.set(statusAtom(ENVIRONMENT_ID), "cached"))), + ); return { registry, commands, snapshotAtom, + statusAtom, visibleAtom, + pendingSyncAtom, requests, reconciled, + storage, + store, + reconnect, + disconnect, connection, connectionFollowed, }; @@ -665,3 +714,358 @@ describe("remote thread lifecycle commands", () => { }), ); }); + +const waitFor = ( + registry: AtomRegistry.AtomRegistry, + atom: Atom.Atom, + done: (value: A) => boolean, +) => + Effect.callback((resume) => { + if (done(registry.get(atom))) return resume(Effect.void); + const unsubscribe = registry.subscribe(atom, (value) => { + if (!done(value)) return; + unsubscribe(); + resume(Effect.void); + }); + return Effect.sync(unsubscribe); + }); + +describe("settle and snooze while the environment is offline", () => { + const settle = { environmentId: ENVIRONMENT_ID, input: { threadId: THREAD_ID } }; + const snooze = { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" }, + }; + const undo = { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, reason: "user" as const }, + }; + const stored = (storage: { value: string | null }) => + storage.value === null + ? [] + : (JSON.parse(storage.value) as { entries: Array> }).entries; + const changedThread = (change: Partial) => ({ + ...SNAPSHOT, + snapshotSequence: 5, + threads: [{ ...SNAPSHOT.threads[0]!, ...change }], + }); + /** The request may have reached the server before the socket closed. */ + const lostReply = () => + new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: "socket closed", + cause: new Error("socket closed"), + }), + }); + const queued = Effect.fn("queued")(function* ( + action: "settle" | "snooze" = "settle", + storage?: { value: string | null; onModify?: () => void }, + ) { + const h = yield* makeHarness({ connected: false, ...(storage ? { storage } : {}) }); + const result = yield* Effect.promise(() => h.commands[action].run(h.registry, snooze)); + expect(result._tag).toBe("Success"); + return h; + }); + type Harness = Effect.Success>; + const nothingPending = (h: Harness) => + waitFor(h.registry, h.pendingSyncAtom, (threads) => threads.size === 0); + /** Commands on one thread go out in order, so this one arrives first only if no other was sent. */ + const expectNothingSent = Effect.fn("expectNothingSent")(function* (h: Harness) { + const pin = h.commands.pin.run(h.registry, settle); + const request = yield* Queue.take(h.requests); + expect(request.command.type).toBe("thread.pin"); + yield* Deferred.succeed(request.reply, { sequence: 1 }); + yield* Effect.promise(() => pin); + }); + + it.effect("shows a settle at once and sends it when the environment is back", () => + Effect.gen(function* () { + const h = yield* queued(); + expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("settled"); + expect(h.registry.get(h.pendingSyncAtom).has(THREAD_ID)).toBe(true); + const [entry] = stored(h.storage); + expect(entry).toMatchObject({ threadId: THREAD_ID, action: { type: "settle" } }); + + yield* h.reconnect(); + const request = yield* Queue.take(h.requests); + expect(request.command).toMatchObject({ + type: "thread.settle", + commandId: entry!.commandId, + threadId: THREAD_ID, + }); + // Recorded before the send, so a restart or Undo from here asks the server. + expect(stored(h.storage)[0]!.attempted).toBe(true); + yield* Deferred.succeed(request.reply, { sequence: 2 }); + yield* nothingPending(h); + expect(stored(h.storage)).toEqual([]); + }), + ); + + it.effect("sends a queued snooze after a restart, under the command id it was stored with", () => + Effect.gen(function* () { + const storage = { value: null as string | null }; + yield* queued("snooze", storage); + const [entry] = stored(storage); + + const restarted = yield* makeHarness({ connected: false, storage }); + yield* waitFor( + restarted.registry, + restarted.pendingSyncAtom, + (threads) => threads.size === 1, + ); + expect(restarted.registry.get(restarted.visibleAtom)?.threads[0]?.snoozedUntil).toEqual( + FUTURE, + ); + yield* restarted.reconnect(); + const request = yield* Queue.take(restarted.requests); + expect(request.command).toMatchObject({ + type: "thread.snooze", + commandId: entry!.commandId, + snoozedUntil: "2099-01-01T00:00:00.000Z", + }); + yield* Deferred.succeed(request.reply, { sequence: 2 }); + yield* nothingPending(restarted); + yield* expectNothingSent(restarted); + }), + ); + + it.effect.each([ + ["produced new output", { itemCount: 1 }], + ["was pinned on another device", { pinnedAt: NOW }], + ["is asking for approval", { pendingRuntimeRequest: APPROVAL }], + ] as const)("keeps the server's state for a thread that %s meanwhile", ([, change]) => + Effect.gen(function* () { + const h = yield* queued(); + // Judged against the synchronized shell: sending any earlier would leave it pending here. + yield* h.reconnect("synchronizing"); + const changed = changedThread(change); + h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed); + h.registry.set(h.statusAtom(ENVIRONMENT_ID), "live"); + yield* nothingPending(h); + yield* expectNothingSent(h); + expect(stored(h.storage)).toEqual([]); + expect(h.registry.get(h.visibleAtom)).toBe(changed); + }), + ); + + it.effect.each([ + // A reconnect whose shell has not synchronized yet lands while the change is being marked. + { when: "the shell stops being synchronized while it is marked", connected: true }, + // The shell reports synchronized from a stale stream while the session is already gone. + { when: "its environment has no session", connected: false }, + ])("leaves a change unsent and cancellable when $when", ({ connected }) => + Effect.gen(function* () { + const unmarked = yield* Queue.unbounded(); + const storage: { value: string | null; onModify?: () => void } = { value: null }; + const h = yield* queued("settle", storage); + let calls = 0; + // Replay reads the queue, marks the change, and takes the mark off again. + storage.onModify = () => { + calls += 1; + if (calls === 2 && connected) { + h.registry.set(h.statusAtom(ENVIRONMENT_ID), "synchronizing"); + } + if (calls === 3) Queue.offerUnsafe(unmarked, undefined); + }; + if (connected) yield* h.reconnect(); + else h.registry.set(h.statusAtom(ENVIRONMENT_ID), "live"); + yield* Queue.take(unmarked); + const result = yield* Effect.promise(() => h.commands.unsettle.run(h.registry, undo)); + expect(result._tag === "Success" && ThreadUndo.cancelledPendingSync(result.value)).toBe(true); + expect(stored(storage)).toEqual([]); + yield* h.reconnect(); + yield* expectNothingSent(h); + }), + ); + + it.effect("keeps another tab's sent mark when this tab could not send", () => + Effect.gen(function* () { + const flipped = yield* Queue.unbounded(); + const storage: { value: string | null; onModify?: () => void } = { value: null }; + const h = yield* queued("settle", storage); + let calls = 0; + // Between this tab's read and its mark, another tab marks the change and sends it. Then + // this tab's shell stops being synchronized. + storage.onModify = () => { + if (++calls !== 2) return; + storage.value = storage.value!.replace('"seen"', '"attempted":true,"seen"'); + h.registry.set(h.statusAtom(ENVIRONMENT_ID), "synchronizing"); + Queue.offerUnsafe(flipped, undefined); + }; + yield* h.reconnect(); + yield* Queue.take(flipped); + const undone = h.commands.unsettle.run(h.registry, undo); + const request = yield* Queue.take(h.requests); + expect(request.command.type).toBe("thread.unsettle"); + yield* Deferred.succeed(request.reply, { sequence: 2 }); + expect((yield* Effect.promise(() => undone))._tag).toBe("Success"); + }), + ); + + it.effect("sends a queued change again when the first send got no answer", () => + Effect.gen(function* () { + const h = yield* queued(); + yield* h.reconnect(); + const first = yield* Queue.take(h.requests); + yield* h.disconnect; + yield* Deferred.fail(first.reply, lostReply()); + expect(h.registry.get(h.pendingSyncAtom).has(THREAD_ID)).toBe(true); + yield* h.reconnect(); + const second = yield* Queue.take(h.requests); + expect(second.command.commandId).toBe(first.command.commandId); + yield* Deferred.succeed(second.reply, { sequence: 2 }); + yield* nothingPending(h); + }), + ); + + it.effect("drops a queued change the server refuses, and shows the server's state", () => + Effect.gen(function* () { + const h = yield* queued(); + yield* h.reconnect(); + const request = yield* Queue.take(h.requests); + yield* Deferred.fail(request.reply, new Error("This session cannot change threads.")); + yield* nothingPending(h); + expect(stored(h.storage)).toEqual([]); + expect(h.registry.get(h.visibleAtom)).toBe(SNAPSHOT); + }), + ); + + it.effect.each([ + ["settle", "unsettle"], + ["snooze", "unsnooze"], + ] as const)("undoing a queued %s cancels it without contacting the server", ([action, undoing]) => + Effect.gen(function* () { + const h = yield* queued(action); + const result = yield* Effect.promise(() => h.commands[undoing].run(h.registry, undo)); + expect(result._tag === "Success" && ThreadUndo.cancelledPendingSync(result.value)).toBe(true); + expect(h.registry.get(h.pendingSyncAtom).size).toBe(0); + expect(stored(h.storage)).toEqual([]); + expect(h.registry.get(h.visibleAtom)).toBe(SNAPSHOT); + yield* h.reconnect(); + yield* expectNothingSent(h); + }), + ); + + it.effect("after a lost reply, Undo asks the server and the change is not sent twice", () => + Effect.gen(function* () { + const h = yield* queued(); + yield* h.reconnect(); + const request = yield* Queue.take(h.requests); + yield* h.disconnect; + yield* Deferred.fail(request.reply, lostReply()); + + // The server may have settled it, so cancelling on the device would lose the Undo. + const undone = yield* Effect.promise(() => h.commands.unsettle.run(h.registry, undo)); + expect(undone._tag).toBe("Failure"); + expect(h.registry.get(h.pendingSyncAtom).has(THREAD_ID)).toBe(true); + + // It had: the returning shell shows the thread settled, which answers the queued change. + h.registry.set( + h.snapshotAtom(ENVIRONMENT_ID), + changedThread({ settledOverride: "settled", settledAt: NOW }), + ); + yield* h.reconnect(); + yield* nothingPending(h); + yield* expectNothingSent(h); + }), + ); + + it.effect("a later action that reaches the server replaces the queued one", () => + Effect.gen(function* () { + const h = yield* queued(); + yield* h.reconnect("synchronizing"); + const result = h.commands.snooze.run(h.registry, snooze); + const request = yield* Queue.take(h.requests); + expect(request.command.type).toBe("thread.snooze"); + yield* Deferred.succeed(request.reply, { sequence: 2 }); + expect((yield* Effect.promise(() => result))._tag).toBe("Success"); + expect(stored(h.storage)).toEqual([]); + h.registry.set(h.statusAtom(ENVIRONMENT_ID), "live"); + yield* expectNothingSent(h); + }), + ); + + it.effect("drops a queued snooze that expired before the reconnect", () => + Effect.gen(function* () { + const storage = { value: null as string | null }; + yield* queued("snooze", storage); + storage.value = storage.value!.replace( + "2099-01-01T00:00:00.000Z", + "2000-01-01T00:00:00.000Z", + ); + const restarted = yield* makeHarness({ connected: false, storage }); + yield* waitFor( + restarted.registry, + restarted.pendingSyncAtom, + (threads) => threads.size === 1, + ); + yield* restarted.reconnect(); + yield* nothingPending(restarted); + yield* expectNothingSent(restarted); + expect(stored(storage)).toEqual([]); + }), + ); + + it.effect("sends what storage holds when another tab replaced the change", () => + Effect.gen(function* () { + const storage = { value: null as string | null }; + const first = yield* queued("settle", storage); + const second = yield* makeHarness({ connected: false, storage }); + yield* waitFor(second.registry, second.pendingSyncAtom, (threads) => threads.size === 1); + yield* Effect.promise(() => second.commands.unsettle.run(second.registry, undo)); + yield* Effect.promise(() => second.commands.snooze.run(second.registry, snooze)); + + yield* first.reconnect(); + const request = yield* Queue.take(first.requests); + expect(request.command).toMatchObject({ + type: "thread.snooze", + commandId: stored(storage)[0]!.commandId, + }); + yield* Deferred.succeed(request.reply, { sequence: 2 }); + yield* nothingPending(first); + }), + ); + + it.effect("does not queue a settle the cached thread cannot take", () => + Effect.gen(function* () { + const h = yield* makeHarness({ connected: false }); + h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changedThread({ status: "running" })); + const result = yield* Effect.promise(() => h.commands.settle.run(h.registry, settle)); + expect(result._tag).toBe("Failure"); + expect(stored(h.storage)).toEqual([]); + }), + ); + + // The other tab loaded before the settle was queued, so only storage knows about it. + it.effect( + "keeps a settle queued in another tab when a snooze of the same thread would replace it", + () => + Effect.gen(function* () { + const storage = { value: null as string | null }; + const other = yield* makeHarness({ connected: false, storage }); + // Store calls run in order, so the other tab's first read is done after this one. + yield* other.store.update((stored) => stored); + yield* queued("settle", storage); + const before = storage.value; + const result = yield* Effect.promise(() => + other.commands.snooze.run(other.registry, snooze), + ); + expect(result._tag).toBe("Failure"); + expect(storage.value).toBe(before); + }), + ); + + it.effect("keeps the not-connected failure when the change cannot be saved", () => + Effect.gen(function* () { + const h = yield* makeHarness({ + connected: false, + storage: { value: null, failWrites: true }, + }); + const result = yield* Effect.promise(() => h.commands.settle.run(h.registry, settle)); + expect(String(result._tag === "Failure" ? Cause.squash(result.cause) : "")).toContain( + "Mac is not connected.", + ); + expect(h.registry.get(h.pendingSyncAtom).size).toBe(0); + }), + ); +}); diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 41b74e9f2ac78..cd34c022fd621 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -7,9 +7,12 @@ import { WS_METHODS, type EnvironmentId, type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts"; +import type { EnvironmentShellStatus } from "./shell.ts"; +import { createThreadTriageOutbox } from "./threadTriageOutbox.ts"; import * as DateTime from "effect/DateTime"; import { @@ -76,9 +79,53 @@ export type LoadEarlierThreadHistoryInput = { readonly workAnchorId?: string; }; +function applySettle( + thread: OrchestrationV2ThreadShell, + now: DateTime.Utc, + accepted: boolean, +): OrchestrationV2ThreadShell { + return !accepted && + (thread.pendingRuntimeRequest !== null || + ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status)) + ? thread + : { + ...thread, + pendingRuntimeRequest: null, + settledOverride: "settled", + settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now, + unsettledAt: null, + activeOrderKey: null, + pinnedAt: null, + pinOrderKey: null, + snoozedAt: null, + snoozedUntil: null, + }; +} + +function applySnooze( + thread: OrchestrationV2ThreadShell, + snoozedUntil: string, + now: DateTime.Utc, + accepted: boolean, +): OrchestrationV2ThreadShell { + return (!accepted && + ((thread.pendingRuntimeRequest !== null && + thread.pendingRuntimeRequest.kind !== "user_input") || + ["preparing", "queued", "starting"].includes(thread.status))) || + !(Date.parse(snoozedUntil) > DateTime.toEpochMillis(now)) + ? thread + : { + ...thread, + snoozedUntil: DateTime.makeUnsafe(snoozedUntil), + snoozedAt: now, + }; +} + export function createThreadEnvironmentAtoms( runtime: Atom.AtomRuntime, snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom, + /** Offline settle and snooze are sent once this reports a synchronized shell. */ + shellStatusAtom: (environmentId: EnvironmentId) => Atom.Atom, ) { const scheduler = createAtomCommandScheduler(); const concurrency = { @@ -448,7 +495,29 @@ export function createThreadEnvironmentAtoms( pin: rowAction(sent.pin), unpin: rowAction(sent.unpin), }; - const optimistic = createOptimisticThreadLifecycle(snapshotAtom); + const triage = createThreadTriageOutbox({ + runtime, + sourceSnapshotAtom: snapshotAtom, + shellStatusAtom, + apply: (thread, action, queuedAt) => + action.type === "settle" + ? applySettle(thread, queuedAt, false) + : applySnooze(thread, action.snoozedUntil, queuedAt, false), + send: (registry, { environmentId, threadId, commandId, action }) => + action.type === "settle" + ? settle.run(registry, { environmentId, input: { threadId, commandId } }) + : snooze.run(registry, { + environmentId, + input: { threadId, commandId, snoozedUntil: action.snoozedUntil }, + }), + }); + const optimistic = createOptimisticThreadLifecycle(triage.snapshotAtom); + const settle = optimistic.wrap(commands.settle, (thread, _input, now, accepted) => + applySettle(thread, now, accepted), + ); + const snooze = optimistic.wrap(commands.snooze, (thread, input, now, accepted) => + applySnooze(thread, input.snoozedUntil, now, accepted), + ); const disconnectedAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => { const connection = AsyncResult.getOrElse( @@ -485,55 +554,38 @@ export function createThreadEnvironmentAtoms( rowActionsAtom, snapshotAtom: optimistic.snapshotAtom, pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom, - settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) => - !accepted && - (thread.pendingRuntimeRequest !== null || - ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status)) - ? thread - : { - ...thread, - pendingRuntimeRequest: null, - settledOverride: "settled", - settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now, - unsettledAt: null, - activeOrderKey: null, - pinnedAt: null, - pinOrderKey: null, - snoozedAt: null, - snoozedUntil: null, - }, + pendingSyncAtom: triage.pendingSyncAtom, + settle: triage.queueWhenOffline(settle, () => ({ type: "settle" as const })), + unsettle: triage.cancelQueued( + optimistic.wrap(commands.unsettle, (thread, input, now) => ({ + ...thread, + settledOverride: input.reason === "user" ? "active" : null, + settledAt: null, + unsettledAt: + thread.settledOverride === "active" + ? (thread.unsettledAt ?? null) + : input.restoreUnsettledAt === undefined + ? now + : input.restoreUnsettledAt === null + ? null + : DateTime.makeUnsafe(input.restoreUnsettledAt), + })), + "settle", + { sequence: 0, cancelledPendingSync: true as const }, ), - unsettle: optimistic.wrap(commands.unsettle, (thread, input, now) => ({ - ...thread, - settledOverride: input.reason === "user" ? "active" : null, - settledAt: null, - unsettledAt: - thread.settledOverride === "active" - ? (thread.unsettledAt ?? null) - : input.restoreUnsettledAt === undefined - ? now - : input.restoreUnsettledAt === null - ? null - : DateTime.makeUnsafe(input.restoreUnsettledAt), + snooze: triage.queueWhenOffline(snooze, (input) => ({ + type: "snooze" as const, + snoozedUntil: input.snoozedUntil, })), - snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) => - (!accepted && - ((thread.pendingRuntimeRequest !== null && - thread.pendingRuntimeRequest.kind !== "user_input") || - ["preparing", "queued", "starting"].includes(thread.status))) || - !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now)) - ? thread - : { - ...thread, - snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil), - snoozedAt: now, - }, + unsnooze: triage.cancelQueued( + optimistic.wrap(commands.unsnooze, (thread) => ({ + ...thread, + snoozedUntil: null, + snoozedAt: null, + })), + "snooze", + { sequence: 0, cancelledPendingSync: true as const }, ), - unsnooze: optimistic.wrap(commands.unsnooze, (thread) => ({ - ...thread, - snoozedUntil: null, - snoozedAt: null, - })), setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({ ...thread, autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now), diff --git a/packages/client-runtime/src/state/threadTriageOutbox.ts b/packages/client-runtime/src/state/threadTriageOutbox.ts new file mode 100644 index 0000000000000..7d035f94f560b --- /dev/null +++ b/packages/client-runtime/src/state/threadTriageOutbox.ts @@ -0,0 +1,372 @@ +import { + CommandId, + type EnvironmentId, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadShell, + type ThreadId, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Schema from "effect/Schema"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; + +import { + type PendingThreadTriage, + type PendingThreadTriages, + ThreadTriageOutboxStore, + type ThreadTriageOutboxStorageError, +} from "../platform/threadTriageOutboxStore.ts"; +import { EnvironmentRpcUnavailableError, isRpcClientError } from "../rpc/client.ts"; +import type { EnvironmentShellStatus } from "./shell.ts"; +import { type AtomCommand, type AtomCommandResult, createRuntimeCommand } from "./runtime.ts"; + +type Target = { readonly environmentId: EnvironmentId; readonly input: I }; +type Change = (stored: PendingThreadTriages, newCommandId: CommandId) => PendingThreadTriages; + +const isUnavailable = Schema.is(EnvironmentRpcUnavailableError); + +/** Failures that say nothing about whether the server would accept the change. */ +function isTransient(cause: Cause.Cause) { + return ( + Cause.hasInterruptsOnly(cause) || + cause.reasons.some( + (reason) => + !Cause.isFailReason(reason) || + isUnavailable(reason.error) || + isRpcClientError(reason.error), + ) + ); +} + +/** + * What the user acted on: the thread's work, and every triage decision with its time, so a + * settle or snooze made and undone elsewhere still counts. A thread that shows otherwise on + * reconnect keeps its server state. + */ +function seenState(thread: OrchestrationV2ThreadShell) { + return JSON.stringify([ + thread.latestRunId, + thread.status, + thread.itemCount, + thread.pendingRuntimeRequest?.id ?? null, + thread.settledOverride, + ...[ + thread.settledAt, + thread.unsettledAt, + thread.snoozedUntil, + thread.snoozedAt, + thread.pinnedAt, + ].map((time) => (time == null ? null : DateTime.toEpochMillis(time))), + ]); +} + +const without = (entries: PendingThreadTriages, commandId: CommandId) => + entries.some((entry) => entry.commandId === commandId) + ? entries.filter((entry) => entry.commandId !== commandId) + : entries; + +/** The sent mark is left out: it is only ever read from storage. */ +const sameEntries = (a: PendingThreadTriages, b: PendingThreadTriages) => + a.length === b.length && a.every((entry, index) => entry.commandId === b[index]!.commandId); + +/** Raised before a request is sent, when the environment has no session. */ +const isOffline = (cause: Cause.Cause) => + cause.reasons.some((reason) => Cause.isFailReason(reason) && isUnavailable(reason.error)); + +/** + * Settle and snooze for an environment that is not connected: the change is stored on the + * device, shown at once, and sent when the environment is back. Storage is the truth, so tabs + * sharing it agree: memory mirrors what the last read or write returned, and a change is + * confirmed there right before it is sent. + */ +export function createThreadTriageOutbox(input: { + readonly runtime: Atom.AtomRuntime; + readonly sourceSnapshotAtom: ( + environmentId: EnvironmentId, + ) => Atom.Atom; + /** Queued changes are sent once this reports a synchronized shell. */ + readonly shellStatusAtom: (environmentId: EnvironmentId) => Atom.Atom; + /** Returns the thread itself when the action cannot apply to it. */ + readonly apply: ( + thread: OrchestrationV2ThreadShell, + action: PendingThreadTriage["action"], + queuedAt: DateTime.Utc, + ) => OrchestrationV2ThreadShell; + /** Sends the action under its command id, which the server answers only once. */ + readonly send: ( + registry: AtomRegistry.AtomRegistry, + entry: PendingThreadTriage, + ) => Promise>; +}) { + const update = createRuntimeCommand(input.runtime, { + label: "environment-data:thread-triage-outbox", + execute: Effect.fn("ThreadTriageOutbox.update")(function* (change: Change) { + const store = yield* ThreadTriageOutboxStore; + const random = yield* SecureRandom.SecureRandom; + const newCommandId = CommandId.make(yield* random.uuidV4()); + return yield* store + .update((stored) => change(stored, newCommandId)) + .pipe( + Effect.tapError(() => + Effect.logWarning("Could not read or save offline thread changes.", { + reason: "storage", + }), + ), + ); + }), + }); + + const entriesAtom = Atom.make(null).pipe(Atom.keepAlive); + /** Ends with the registry, so a replay in flight stops touching it. */ + const lifetimeAtom = Atom.make((get) => { + const lifetime = { ended: false }; + get.addFinalizer(() => { + lifetime.ended = true; + }); + return lifetime; + }).pipe(Atom.keepAlive); + + const write = async ( + registry: AtomRegistry.AtomRegistry, + change: Change = (stored) => stored, + ) => { + const lifetime = registry.get(lifetimeAtom); + const result = await update.run(registry, change); + if (AsyncResult.isSuccess(result) && !lifetime.ended) { + const current = registry.get(entriesAtom); + // An unchanged queue must not wake the replay that just read it. + if (current === null || !sameEntries(current, result.value)) { + registry.set(entriesAtom, result.value); + } + } + return result; + }; + const forget = (registry: AtomRegistry.AtomRegistry, entry: PendingThreadTriage) => + write(registry, (stored) => without(stored, entry.commandId)); + + let loading: Promise | undefined; + const load = (registry: AtomRegistry.AtomRegistry) => + (loading ??= write(registry).then((result) => { + // A failed read is tried again the next time the queue is looked at. + if (!AsyncResult.isSuccess(result)) loading = undefined; + })); + const environmentEntriesAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const entries = get(entriesAtom); + if (entries === null) void load(get.registry); + return (entries ?? []).filter((entry) => entry.environmentId === environmentId); + }), + ); + const pendingFor = ( + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + threadId: ThreadId, + ) => + registry + .get(entriesAtom) + ?.find((entry) => entry.environmentId === environmentId && entry.threadId === threadId); + const sourceThread = ( + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + threadId: ThreadId, + ) => + registry + .get(input.sourceSnapshotAtom(environmentId)) + ?.threads.find((thread) => thread.id === threadId); + + const replaying = new Set(); + const replayAgain = new Set(); + const isLive = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => + registry.get(input.shellStatusAtom(environmentId)) === "live"; + const replay = async (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => { + if (replaying.has(environmentId)) { + replayAgain.add(environmentId); + return; + } + const lifetime = registry.get(lifetimeAtom); + replaying.add(environmentId); + try { + await replayEntries(registry, environmentId, lifetime); + } finally { + replaying.delete(environmentId); + } + if (!lifetime.ended && replayAgain.delete(environmentId) && isLive(registry, environmentId)) { + await replay(registry, environmentId); + } + }; + const replayEntries = async ( + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + lifetime: { readonly ended: boolean }, + ) => { + // Read again: another tab may have queued a change this one has not seen. + const stored = await write(registry); + if (!AsyncResult.isSuccess(stored)) return; + for (const entry of stored.value) { + if (entry.environmentId !== environmentId) continue; + // A change is only marked as sent while it can be sent, so Undo can still cancel the rest. + if (lifetime.ended || !isLive(registry, environmentId)) return; + // Marked before sending, so an Undo after a lost reply or a restart asks the server. + let markedHere = false; + const marked = await write(registry, (current) => { + markedHere = current.some( + (item) => item.commandId === entry.commandId && item.attempted !== true, + ); + return markedHere + ? current.map((item) => + item.commandId === entry.commandId ? { ...item, attempted: true as const } : item, + ) + : current; + }); + if (lifetime.ended || !AsyncResult.isSuccess(marked)) return; + // Storage no longer has it: cancelled, replaced, sent by another tab, or its environment + // was removed. + if (!marked.value.some((item) => item.commandId === entry.commandId)) continue; + // A change that never left the device loses the mark this pass made, so Undo can cancel + // it. A mark from an earlier pass or another tab stays: that send may have arrived. + const unmark = async () => { + if (!markedHere) return; + await write(registry, (current) => + current.map(({ attempted, ...item }) => + item.commandId === entry.commandId || attempted !== true + ? item + : { ...item, attempted }, + ), + ); + }; + // Checked after the last wait, so the shell judged is the one the send goes through. + if (!isLive(registry, environmentId)) return unmark(); + const thread = sourceThread(registry, environmentId, entry.threadId); + // The live shell is the server's state. It wins over a change made against an older one, + // which also covers a change that was sent before but whose reply was lost. + if ( + thread === undefined || + seenState(thread) !== entry.seen || + input.apply(thread, entry.action, DateTime.nowUnsafe()) === thread + ) { + await forget(registry, entry); + continue; + } + const result = await input.send(registry, entry); + if (lifetime.ended) return; + if (!AsyncResult.isSuccess(result) && isTransient(result.cause)) { + return isOffline(result.cause) ? unmark() : undefined; + } + await forget(registry, entry); + } + }; + const replayAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + // Also runs when this tab's queue changes while the shell is synchronized. + get(environmentEntriesAtom(environmentId)); + if (get(input.shellStatusAtom(environmentId)) === "live") { + void replay(get.registry, environmentId); + } + }), + ); + + const snapshotAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + get.mount(replayAtom(environmentId)); + const snapshot = get(input.sourceSnapshotAtom(environmentId)); + const entries = get(environmentEntriesAtom(environmentId)); + if (snapshot === null || entries.length === 0) return snapshot; + const byThread = new Map(entries.map((entry) => [entry.threadId, entry])); + return { + ...snapshot, + threads: snapshot.threads.map((thread) => { + const entry = byThread.get(thread.id); + return entry === undefined ? thread : input.apply(thread, entry.action, entry.queuedAt); + }), + }; + }), + ); + + const pendingSyncAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make( + (get): ReadonlySet => + new Set(get(environmentEntriesAtom(environmentId)).map((entry) => entry.threadId)), + ), + ); + + /** Queues the action on the device when its environment is not connected. */ + function queueWhenOffline( + command: AtomCommand, { readonly sequence: number }, CE>, + toAction: (input: I) => PendingThreadTriage["action"], + ): typeof command { + return { + label: command.label, + run: async (registry, target) => { + const { environmentId } = target; + const { threadId } = target.input; + // Read before sending: the change is judged against what the user saw when acting. + const snapshot = registry.get(input.sourceSnapshotAtom(environmentId)); + const thread = snapshot?.threads.find((candidate) => candidate.id === threadId); + const result = await command.run(registry, target); + if (AsyncResult.isSuccess(result)) { + // The server now has a newer action than the queued one. + const previous = pendingFor(registry, environmentId, threadId); + if (previous !== undefined) await forget(registry, previous); + return result; + } + if (!isOffline(result.cause) || snapshot == null || thread === undefined) return result; + const action = toAction(target.input); + const queuedAt = DateTime.nowUnsafe(); + if (input.apply(thread, action, queuedAt) === thread) return result; + let refused = false; + const queued = await write(registry, (stored, commandId) => { + const same = (entry: PendingThreadTriage) => + entry.environmentId === environmentId && entry.threadId === threadId; + // One change per thread. A snooze cannot replace a settle, which online it keeps. + refused = action.type === "snooze" && stored.find(same)?.action.type === "settle"; + return refused + ? stored + : [ + ...stored.filter((entry) => !same(entry)), + { environmentId, threadId, commandId, action, queuedAt, seen: seenState(thread) }, + ]; + }); + return AsyncResult.isSuccess(queued) && !refused + ? AsyncResult.success({ sequence: snapshot.snapshotSequence }) + : result; + }, + }; + } + + /** + * Undo of a change that was never sent cancels it on the device. Once it was sent, even if the + * reply was lost, only the server can undo it. + */ + function cancelQueued( + command: AtomCommand, A, CE>, + cancels: PendingThreadTriage["action"]["type"], + cancelledValue: B, + ): AtomCommand, A | B, CE | ThreadTriageOutboxStorageError | E> { + return { + label: command.label, + run: async (registry, target) => { + const pending = pendingFor(registry, target.environmentId, target.input.threadId); + if (pending === undefined || pending.action.type !== cancels) { + return command.run(registry, target); + } + // Storage decides, because a replay, a restart or another tab may have sent it. + let unsent = false; + const stored = await write(registry, (current) => { + unsent = current.some( + (entry) => entry.commandId === pending.commandId && entry.attempted !== true, + ); + return unsent ? without(current, pending.commandId) : current; + }); + if (!AsyncResult.isSuccess(stored)) return AsyncResult.failure(stored.cause); + if (unsent) return AsyncResult.success(cancelledValue); + const result = await command.run(registry, target); + if (AsyncResult.isSuccess(result)) await forget(registry, pending); + return result; + }, + }; + } + + return { snapshotAtom, pendingSyncAtom, queueWhenOffline, cancelQueued }; +} diff --git a/packages/client-runtime/src/state/threadUndo.ts b/packages/client-runtime/src/state/threadUndo.ts index 20ea56400c284..6b3249595477f 100644 --- a/packages/client-runtime/src/state/threadUndo.ts +++ b/packages/client-runtime/src/state/threadUndo.ts @@ -79,6 +79,19 @@ export function planThreadUndo( return [unsettle, ...placement, ...snooze]; } +/** + * True when an Undo step cancelled a settle or snooze still waiting to sync. The server never + * saw the change, so the rest of the plan (re-pin, re-snooze) has nothing to restore. + */ +export function cancelledPendingSync(value: unknown): boolean { + return ( + typeof value === "object" && + value !== null && + "cancelledPendingSync" in value && + value.cancelledPendingSync === true + ); +} + export async function executeThreadUndo( plan: ThreadUndoPlan, execute: (step: ThreadUndoStep) => Promise,