Skip to content

Commit 1550c23

Browse files
committed
Merge remote-tracking branch 'github/main' into maria/takeover-pr-26807-original
2 parents 3c78947 + fa4e467 commit 1550c23

71 files changed

Lines changed: 3073 additions & 362 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import type {
4646
ScopedThreadRef,
4747
ServerConfig as T3ServerConfig,
4848
UsageLimitsReport,
49+
RunId,
4950
} from "@t3tools/contracts";
5051
import {
5152
appendCodexArtifactTemplateUsePrompt,
@@ -156,8 +157,10 @@ import {
156157
import { appAtomRegistry } from "../../state/atom-registry";
157158
import { threadStreamHaptics } from "./threadStreamHaptics";
158159
import { useAtomCommand } from "../../state/use-atom-command";
160+
import { orchestrationEnvironment } from "../../state/orchestration";
159161
import { useDelayedStatus } from "../../lib/useDelayedStatus";
160162
import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
163+
import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";
161164
import type {
162165
PendingApproval,
163166
PendingUserInput,
@@ -339,6 +342,9 @@ const threadVisitTracker = createThreadVisitTracker({
339342

340343
// Past the composer's 180 ms height animation.
341344
const COMPOSER_HEIGHT_SETTLE_MS = 220;
345+
const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(
346+
Atom.withLabel("mobile-thread-run-stop:empty"),
347+
);
342348

343349
// Anchors, the submitted message, follow state and pending scrolls belong to
344350
// one thread, so the body remounts when the thread changes.
@@ -528,6 +534,50 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
528534
const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
529535
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
530536
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
537+
const anyRunStop = useAtomValue(
538+
props.selectedThreadDetailRef === null
539+
? NO_RUN_STOP_ATOM
540+
: environmentThreadDetails.runStopAtom(props.selectedThreadDetailRef),
541+
);
542+
// A background Stop matters only while that work is still pending.
543+
const runStop =
544+
anyRunStop?.background && props.selectedThread.pendingBackgroundTasks.length === 0
545+
? null
546+
: anyRunStop;
547+
const forceStopThread = useAtomCommand(orchestrationEnvironment.forceStopThread, {
548+
reportFailure: false,
549+
});
550+
const canForceStop =
551+
useAtomValue(orchestrationEnvironment.forceStopThread.permissionAtom(props.environmentId)) &&
552+
props.serverConfig?.environment.capabilities.threadForceStop === true;
553+
const [forceStoppingKey, setForceStoppingKey] = useState<string | null>(null);
554+
// The run that ignored Stop, so a confirmation left open cannot hit a newer run.
555+
const forceStop = async (runId: RunId | undefined) => {
556+
const threadKey = selectedThreadKey;
557+
setForceStoppingKey(threadKey);
558+
const result = await forceStopThread({
559+
environmentId: props.environmentId,
560+
input:
561+
runId === undefined
562+
? { threadId: props.selectedThread.id }
563+
: { threadId: props.selectedThread.id, runId },
564+
});
565+
setForceStoppingKey((current) => (current === threadKey ? null : current));
566+
if (result._tag === "Failure") {
567+
if (!isAtomCommandInterrupted(result)) Dialog.alert("Could not force stop the agent");
568+
return;
569+
}
570+
const others = result.value.sharedWithThreadIds.length;
571+
if (result.value.outcome === "releasing") {
572+
Dialog.alert("Turn stopped; the agent is still shutting down");
573+
}
574+
if (result.value.outcome === "shared") {
575+
Dialog.alert(
576+
"Turn stopped; the agent process kept running",
577+
`It is shared with ${others === 0 ? "other" : others} working ${others === 1 ? "thread" : "threads"}. Stop those to free it.`,
578+
);
579+
}
580+
};
531581
const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null);
532582
const statusPending = statusRequest?.threadKey === selectedThreadKey;
533583
const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());
@@ -619,6 +669,32 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
619669
if (connectionStatus !== null && !props.draftMode) {
620670
return connectionStatus;
621671
}
672+
// Before the request check: an agent stuck on an approval may also ignore Stop.
673+
if (runStop !== null && contentPresentationKind === "ready") {
674+
const unresponsive = runStop.state === "unresponsive";
675+
return {
676+
kind: "stop",
677+
unresponsive,
678+
label: unresponsive ? "Not responding to Stop" : "Stopping…",
679+
action:
680+
unresponsive && canForceStop
681+
? {
682+
label: forceStoppingKey === selectedThreadKey ? "Force stopping..." : "Force stop",
683+
accessibilityLabel: "Force stop the agent",
684+
disabled: forceStoppingKey === selectedThreadKey,
685+
onPress: () =>
686+
Dialog.confirm({
687+
title: "Force stop the agent?",
688+
message:
689+
"It has not answered Stop. Force stop ends the turn and kills the agent's processes, unless other working threads share them.",
690+
confirmText: "Force stop",
691+
destructive: true,
692+
onConfirm: () => void forceStop(runStop.runId),
693+
}),
694+
}
695+
: null,
696+
};
697+
}
622698
if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
623699
return null;
624700
}

‎apps/mobile/src/features/threads/floating-working-control.tsx‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ export function FloatingWorkingControl(props: {
8383
const [queueWidth, setQueueWidth] = useState(0);
8484
const [actionWidth, setActionWidth] = useState(0);
8585
const action =
86-
props.status?.kind === "background" || props.status?.kind === "lifecycle"
86+
props.status?.kind === "background" ||
87+
props.status?.kind === "lifecycle" ||
88+
props.status?.kind === "stop"
8789
? props.status.action
8890
: null;
8991
const [agentsWidth, setAgentsWidth] = useState(0);
@@ -471,6 +473,30 @@ function FloatingStatusLabel(props: {
471473
</StatusLabelRow>
472474
);
473475
}
476+
if (props.status.kind === "stop") {
477+
return (
478+
<StatusLabelRow
479+
key="stop"
480+
accessibilityLabel={props.status.label}
481+
className="gap-2"
482+
onLayout={props.onLayout}
483+
>
484+
{props.status.unresponsive ? (
485+
<SymbolView
486+
name="exclamationmark.triangle"
487+
size={13}
488+
tintColorClassName="accent-warning-foreground"
489+
type="monochrome"
490+
/>
491+
) : (
492+
<AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
493+
)}
494+
<Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
495+
{props.status.label}
496+
</Text>
497+
</StatusLabelRow>
498+
);
499+
}
474500
if (props.status.kind === "goal") {
475501
return (
476502
<StatusLabelRow

‎apps/mobile/src/features/threads/floating-working-status.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ export type FloatingWorkingStatus =
3131
readonly label: string;
3232
readonly action: FloatingStatusAction;
3333
}
34+
| {
35+
readonly kind: "stop";
36+
readonly label: string;
37+
readonly unresponsive: boolean;
38+
readonly action: FloatingStatusAction | null;
39+
}
3440
| { readonly kind: "goal"; readonly label: string; readonly accessibilityLabel: string }
3541
| { readonly kind: "preparing"; readonly label: string }
3642
| {

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export const RPC_REQUIRED_SCOPES = {
4242
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
4343
[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
4444
[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
45+
[ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,
4546
[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
4647
[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
4748
[ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ export const make = Effect.gen(function* () {
240240
projectSettingsOverrides: true,
241241
projectProviderInstanceOverrides: true,
242242
threadSnooze: true,
243+
threadForceStop: true,
243244
environmentThemes: true,
244245
usageLimitSources: true,
245246
providerWorkspaceSnapshotsOnDemand: true,

‎apps/server/src/guest/GuestShareService.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
GuestShareId,
88
type GuestStreamEvent,
99
MessageId,
10+
type OrchestrationV2ThreadHistoryPage,
1011
type OrchestrationV2TurnItem,
1112
ProjectId,
1213
ProviderDriverKind,
@@ -529,6 +530,90 @@ it.effect("gives the guest a command's detail and output, but no file diffs", ()
529530
}).pipe(Effect.provide(layerTest)),
530531
);
531532

533+
it.effect("pages the guest back through turns older than the stream's snapshot", () =>
534+
Effect.gen(function* () {
535+
const { guestShares, credential } = yield* shareThread;
536+
const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
537+
const runId = yield* ownerRun;
538+
const fileSystem = yield* FileSystem.FileSystem;
539+
const directory = yield* fileSystem.makeTempDirectoryScoped();
540+
const shot = `${directory}/old.png`;
541+
yield* fileSystem.writeFile(shot, PNG);
542+
const eventSink = yield* EventSink.EventSinkV2;
543+
const now = yield* DateTime.now;
544+
const base = { threadId, runId, nodeId: null, providerThreadId: null, providerTurnId: null };
545+
const turnItem = (id: string, ordinal: number, payload: object) => ({
546+
id: EventId.make(`event:${id}`),
547+
type: "turn-item.updated" as const,
548+
threadId,
549+
driver: ProviderDriverKind.make("codex"),
550+
providerInstanceId: instanceId,
551+
occurredAt: now,
552+
payload: {
553+
...base,
554+
id: TurnItemId.make(id),
555+
nativeItemRef: null,
556+
parentItemId: null,
557+
ordinal,
558+
title: null,
559+
status: "completed" as const,
560+
startedAt: now,
561+
completedAt: now,
562+
updatedAt: now,
563+
messageId: MessageId.make(id),
564+
...payload,
565+
} as OrchestrationV2TurnItem,
566+
});
567+
yield* eventSink.write({
568+
events: [
569+
turnItem("item:old-image", 1, {
570+
type: "assistant_message",
571+
text: `![Old](${shot})`,
572+
streaming: false,
573+
}),
574+
...Array.from({ length: 30 }, (_, index) =>
575+
turnItem(`item:ask-${index}`, index + 2, {
576+
type: "user_message",
577+
text: `Ask ${index}`,
578+
createdBy: "user",
579+
creationSource: "web",
580+
inputIntent: "turn_start",
581+
attachments: [],
582+
}),
583+
),
584+
],
585+
});
586+
587+
const [, opening] = Array.from(
588+
yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)),
589+
);
590+
if (opening?.type !== "thread" || opening.item.kind !== "snapshot") {
591+
return assert.fail("Expected the thread snapshot second.");
592+
}
593+
const ids = (rows: ReadonlyArray<{ readonly sourceItemId: string }>) =>
594+
rows.map((row) => row.sourceItemId);
595+
assert.notInclude(ids(opening.item.projection.visibleTurnItems), "item:old-image");
596+
let cursor = opening.item.historyCursor ?? null;
597+
assert.isNotNull(cursor);
598+
// The page has not shown the old reply yet, so its image does not load.
599+
assert.equal((yield* Effect.flip(guestShares.media(session, shot))).reason, "unavailable");
600+
// Only a session pages.
601+
assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.history(credential, cursor!))));
602+
603+
const older: Array<string> = [];
604+
while (cursor !== null) {
605+
const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor);
606+
older.push(...ids(page.items));
607+
cursor = page.hasMoreHistory ? page.nextCursor : null;
608+
}
609+
assert.include(older, "item:old-image");
610+
assert.deepStrictEqual(yield* guestShares.media(session, shot), {
611+
path: shot,
612+
mimeType: "image/png",
613+
});
614+
}).pipe(Effect.scoped, Effect.provide(layerTest)),
615+
);
616+
532617
it.effect("ends a running command's output once the owner stops sharing", () =>
533618
Effect.gen(function* () {
534619
const { orchestrator, guestShares, credential } = yield* shareThread;

‎apps/server/src/guest/GuestShareService.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type OrchestrationV2CommandOutputFrame,
1616
type OrchestrationV2DomainEvent,
1717
type OrchestrationV2GetTurnItemResult,
18+
type OrchestrationV2ThreadHistoryPage,
1819
type OrchestrationV2TurnItem,
1920
ThreadId,
2021
TurnItemId,
@@ -185,6 +186,11 @@ export class GuestShareService extends Context.Service<
185186
session: string,
186187
itemId: string,
187188
) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;
189+
/** Older turns of the shared thread, as the owner's client pages them. */
190+
readonly history: (
191+
session: string,
192+
cursor: string,
193+
) => Effect.Effect<OrchestrationV2ThreadHistoryPage, GuestShareAccessError>;
188194
/** A command's output frames, as the owner's expanded row gets them, until the link ends. */
189195
readonly commandOutput: (
190196
session: string,
@@ -665,6 +671,21 @@ const make = Effect.gen(function* () {
665671
};
666672
});
667673

674+
const history = Effect.fn("GuestShareService.history")(function* (
675+
session: string,
676+
cursor: string,
677+
) {
678+
const { thread, share } = yield* authorize(session, "session");
679+
const page = yield* orchestrator
680+
.getThreadHistoryPage(thread.id, cursor)
681+
.pipe(Effect.mapError(() => unavailable));
682+
rememberSent(
683+
share.id,
684+
page.items.map((row) => row.item),
685+
);
686+
return page;
687+
});
688+
668689
const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
669690
session: string,
670691
itemId: string,
@@ -739,6 +760,7 @@ const make = Effect.gen(function* () {
739760
stream,
740761
render,
741762
item,
763+
history,
742764
commandOutput,
743765
attachment,
744766
media,

‎apps/server/src/guest/http.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
GUEST_ATTACHMENT_ROUTE,
33
GUEST_COMMAND_OUTPUT_ROUTE,
4+
GUEST_HISTORY_ROUTE,
45
GUEST_ITEM_ROUTE,
56
GUEST_MEDIA_ROUTE,
67
GUEST_RENDER_ROUTE,
@@ -16,6 +17,7 @@ import {
1617
isProviderSendTurnSupportedImageMimeType,
1718
OrchestrationV2CommandOutputFrame,
1819
OrchestrationV2GetTurnItemResult,
20+
OrchestrationV2ThreadHistoryPage,
1921
} from "@t3tools/contracts";
2022
import * as ByteSize from "effect/ByteSize";
2123
import * as Duration from "effect/Duration";
@@ -52,6 +54,7 @@ const encodeOutputFrame = Schema.encodeEffect(
5254
Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
5355
);
5456
const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
57+
const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
5558

5659
const errorResponse = (error: GuestShareAccessError) =>
5760
HttpServerResponse.json(
@@ -292,6 +295,26 @@ const itemRoute = HttpRouter.add(
292295
}),
293296
);
294297

298+
const historyRoute = HttpRouter.add(
299+
"GET",
300+
GUEST_HISTORY_ROUTE,
301+
Effect.gen(function* () {
302+
const request = yield* HttpServerRequest.HttpServerRequest;
303+
const cursor = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("cursor");
304+
if (!cursor) return yield* badRequest;
305+
const guestShares = yield* GuestShareService;
306+
return yield* guestShares.history(yield* sessionToken, cursor).pipe(
307+
Effect.flatMap((page) =>
308+
encodeHistoryPage(page).pipe(
309+
Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),
310+
),
311+
),
312+
Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),
313+
Effect.catchTags({ GuestShareAccessError: errorResponse }),
314+
);
315+
}),
316+
);
317+
295318
// Ends when the command settles; the page closes its EventSource on that last frame, so the
296319
// browser does not reconnect.
297320
const commandOutputRoute = HttpRouter.add(
@@ -365,6 +388,7 @@ export const layer = Layer.mergeAll(
365388
streamRoute,
366389
renderRoute,
367390
itemRoute,
391+
historyRoute,
368392
commandOutputRoute,
369393
attachmentRoute,
370394
mediaRoute,

0 commit comments

Comments
 (0)