@devries-cameron20 / t3code Mirror · read-only / commits / b24959d579
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

feat: Labs option to suggest your next prompt after Claude and Codex turns (#28047)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 8, 2026 at 16:58 UTC b24959d579b7ec2b527eeeccf043c74a95ab705a
27 files changed +783 -7
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -61,6 +61,7 @@ export const RPC_REQUIRED_SCOPES = {
61 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
62 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
63 [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope,
64 + [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: AuthOrchestrationReadScope,
65 [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
66 [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
67 [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -33,6 +33,7 @@ const RPC_AGGREGATES = {
33 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2",
34 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2",
35 [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2",
36 + [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: "orchestrationV2",
37 [WS_METHODS.projectsMutate]: "orchestration",
38 [WS_METHODS.serverProbe]: "server",
39 [WS_METHODS.serverGetConfig]: "server",
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+140
@@ -3159,6 +3159,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3159 readonly freshQueueOnReopen?: boolean;
3160 readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"];
3161 readonly allocateSessionId?: Effect.Effect<string>;
3162 + readonly promptSuggestions?: boolean;
3163 }) =>
3164 Effect.gen(function* () {
3165 const fileSystem = yield* FileSystem.FileSystem;
@@ -3329,6 +3330,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3330 providerSessionId: ProviderSessionId.make("provider-session-claude-wake"),
3331 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3332 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3333 + promptSuggestions: Effect.succeed(options?.promptSuggestions === true),
3334 });
3335 const providerThread = yield* runtime.ensureThread({
3336 threadId,
@@ -7864,6 +7866,101 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7866 ),
7867 );
7868
7869 + it.effect.each(["root", "mcp", "subagent", "remote"] as const)(
7870 + "asks Claude for suggestions only on threads a person drives (%s)",
7871 + (lineage) =>
7872 + Effect.gen(function* () {
7873 + const harness = yield* makeWakeHarnessWithOptions({ promptSuggestions: true });
7874 + const base = makeClaudeTestTurnInput({
7875 + threadId: harness.threadId,
7876 + providerThread: harness.providerThread,
7877 + now: yield* DateTime.now,
7878 + attemptId: RunAttemptId.make("attempt-prompt-suggestion"),
7879 + text: "Add a subtract function.",
7880 + attachments: [],
7881 + });
7882 + const parentThreadId = ThreadId.make("thread-claude-suggestion-parent");
7883 + // MCP-launched root threads carry `delegatedFrom: null` at runtime.
7884 + const offered = lineage === "root" || lineage === "mcp";
7885 + const input =
7886 + lineage === "root"
7887 + ? base
7888 + : lineage === "mcp"
7889 + ? {
7890 + ...base,
7891 + appThread: {
7892 + ...base.appThread,
7893 + delegatedFrom: null as unknown as undefined,
7894 + },
7895 + }
7896 + : lineage === "subagent"
7897 + ? {
7898 + ...base,
7899 + appThread: {
7900 + ...base.appThread,
7901 + lineage: {
7902 + parentThreadId,
7903 + relationshipToParent: "subagent" as const,
7904 + rootThreadId: parentThreadId,
7905 + },
7906 + },
7907 + }
7908 + : {
7909 + ...base,
7910 + appThread: {
7911 + ...base.appThread,
7912 + delegatedFrom: {
7913 + environmentId: EnvironmentId.make("environment-claude-suggestion-parent"),
7914 + threadId: parentThreadId,
7915 + title: "Parent",
7916 + },
7917 + },
7918 + };
7919 + yield* harness.runtime.startTurn(input);
7920 + yield* Queue.offer(
7921 + harness.sdkMessages,
7922 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000690", result: "Done." }),
7923 + );
7924 + yield* Queue.take(harness.terminalReceipts);
7925 + // Delegated threads have no one typing, so the SDK is never asked for suggestions.
7926 + assert.equal(harness.getOpenedOptions()?.promptSuggestions, offered);
7927 + if (!offered) return;
7928 + yield* Queue.offer(
7929 + harness.sdkMessages,
7930 + claudeSdkFrame({
7931 + type: "prompt_suggestion",
7932 + suggestion: " add tests for subtract\n",
7933 + uuid: "00000000-0000-4000-8000-000000000691",
7934 + session_id: WAKE_NATIVE_SESSION,
7935 + }),
7936 + );
7937 + yield* harness.until(() =>
7938 + harness.events.some((event) => event.type === "prompt_suggestion.updated"),
7939 + );
7940 + assert.deepEqual(
7941 + harness.events.filter((event) => event.type === "prompt_suggestion.updated"),
7942 + [
7943 + {
7944 + type: "prompt_suggestion.updated",
7945 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
7946 + threadId: harness.threadId,
7947 + runId: input.runId,
7948 + text: "add tests for subtract",
7949 + },
7950 + ],
7951 + );
7952 + }).pipe(
7953 + Effect.provide(
7954 + Layer.mergeAll(
7955 + IdAllocator.layer,
7956 + McpProviderSessions.layer,
7957 + NodeServices.layer,
7958 + NodeCrypto.layer,
7959 + ),
7960 + ),
7961 + ),
7962 + );
7963 +
7964 it.effect("merges cumulative stream usage into the message_start counts", () =>
7965 Effect.gen(function* () {
7966 const harness = yield* makeWakeHarnessWithOptions({
@@ -12452,6 +12549,49 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12549 ),
12550 );
12551 assert.isFalse(yield* harness.hasPendingBackgroundWork);
12552 +
12553 + // The continuation settled with no result of its own, so a late suggestion belongs to B.
12554 + yield* harness.offerAndWait(
12555 + claudeSdkFrame({
12556 + type: "prompt_suggestion",
12557 + suggestion: "Check the build logs",
12558 + uuid: "00000000-0000-4000-8000-000000000692",
12559 + session_id: WAKE_NATIVE_SESSION,
12560 + }),
12561 + );
12562 + const userTurn = makeClaudeTestTurnInput({
12563 + threadId: harness.threadId,
12564 + providerThread: harness.providerThread,
12565 + now,
12566 + attemptId: RunAttemptId.make("attempt-claude-wake-4d"),
12567 + text: "Ship it.",
12568 + attachments: [],
12569 + providerTurnOrdinal: 4,
12570 + });
12571 + yield* harness.runtime.startTurn(userTurn);
12572 + yield* Queue.offer(
12573 + harness.sdkMessages,
12574 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000693", result: "Shipped." }),
12575 + );
12576 + yield* harness.awaitTerminal(4);
12577 + yield* Queue.offer(
12578 + harness.sdkMessages,
12579 + claudeSdkFrame({
12580 + type: "prompt_suggestion",
12581 + suggestion: "Open the release notes",
12582 + uuid: "00000000-0000-4000-8000-000000000694",
12583 + session_id: WAKE_NATIVE_SESSION,
12584 + }),
12585 + );
12586 + yield* harness.until(() =>
12587 + harness.events.some((event) => event.type === "prompt_suggestion.updated"),
12588 + );
12589 + assert.deepEqual(
12590 + harness.events.flatMap((event) =>
12591 + event.type === "prompt_suggestion.updated" ? [[event.runId, event.text]] : [],
12592 + ),
12593 + [[userTurn.runId, "Open the release notes"]],
12594 + );
12595 }).pipe(
12596 Effect.provide(
12597 Layer.mergeAll(
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+28
@@ -128,6 +128,7 @@ import {
128 type RunId,
129 type ThreadId,
130 resolveIdleCompaction,
131 + isDelegatedAppThread,
132 } from "@t3tools/contracts";
133
134 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
@@ -1758,6 +1759,7 @@ export function makeClaudeQueryOptions(input: {
1759 readonly cwd: string | null;
1760 readonly attachmentsDir?: string;
1761 readonly settings?: ClaudeSettings;
1762 + readonly promptSuggestions?: boolean;
1763 readonly sdkSettings?: string | ClaudeSdkSettings;
1764 readonly environment?: NodeJS.ProcessEnv;
1765 readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
@@ -1842,6 +1844,7 @@ export function makeClaudeQueryOptions(input: {
1844 ? "bypassPermissions"
1845 : (input.permissionMode ?? "default")),
1846 includePartialMessages: true,
1847 + promptSuggestions: input.promptSuggestions === true,
1848 ...(compiledSelection.effort === undefined
1849 ? {}
1850 : {
@@ -5102,6 +5105,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5105 }),
5106 openSession: Effect.fn("ClaudeAdapterV2.openSession")(
5107 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
5108 + const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false);
5109 const sessionScope = yield* Effect.scope;
5110 const now = yield* DateTime.now;
5111 const session = providerSession({
@@ -8821,6 +8825,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8825 }
8826
8827 const message = input.message;
8828 + if (message.type === "prompt_suggestion") {
8829 + // Arrives after `result`; offer it only while the completed turn is still the latest.
8830 + // A continuation can settle from buffered frames first, so its suggestion may be a user turn's.
8831 + const settled = settledTurnByNativeThread.get(liveQuery.nativeThreadId);
8832 + const text = message.suggestion.trim();
8833 + if (
8834 + settled !== undefined &&
8835 + !isClaudeProviderContinuationTurn(settled.input) &&
8836 + text.length > 0 &&
8837 + (yield* Ref.get(activeTurn)) === null
8838 + ) {
8839 + yield* emitProviderEvent({
8840 + type: "prompt_suggestion.updated",
8841 + driver: CLAUDE_PROVIDER,
8842 + threadId: settled.input.threadId,
8843 + runId: settled.input.runId,
8844 + text,
8845 + });
8846 + }
8847 + return;
8848 + }
8849 // Track before routing: idle-wake Monitors report tasks before replaying their tool calls.
8850 yield* trackClaudeMonitorCalls(message);
8851 // Update before routing because the idle wake gate reads this.
@@ -10924,6 +10949,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10949 cwd: turnInput.runtimePolicy.cwd,
10950 attachmentsDir,
10951 settings: adapterOptions.settings,
10952 + // Delegated threads have no one typing, so they never ask for suggestions.
10953 + promptSuggestions:
10954 + !isDelegatedAppThread(turnInput.appThread) && (yield* promptSuggestionsEnabled),
10955 ...(launchArgSettings === undefined
10956 ? {}
10957 : { sdkSettings: claudeSdkLaunchArgSettings(launchArgSettings) }),
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+207
@@ -1238,6 +1238,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1238 readChildMetadata?: Parameters<typeof withCodexReplayChildMetadata>[2],
1239 beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"],
1240 onUsageLimits?: CodexAdapterV2.CodexAdapterV2Options["onUsageLimits"],
1241 + promptSuggestions: Effect.Effect<boolean> = Effect.succeed(false),
1242 ) =>
1243 Effect.gen(function* () {
1244 const fileSystem = yield* FileSystem.FileSystem;
@@ -1313,6 +1314,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1314 providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`),
1315 modelSelection: CODEX_TEST_MODEL_SELECTION,
1316 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1317 + promptSuggestions,
1318 });
1319 const providerThread = yield* runtime.ensureThread({
1320 threadId,
@@ -1829,6 +1831,211 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1831 ),
1832 );
1833
1834 + it.effect.each(["subagent", "remote", "toggled-off"] as const)(
1835 + "never samples a suggestion for a %s thread",
1836 + (delegation) =>
1837 + Effect.gen(function* () {
1838 + const nativeThreadId = `suggest-${delegation}-thread`;
1839 + const prompt = "Continue the task.";
1840 + const first = codexReplayPreamble({
1841 + nativeThreadId,
1842 + nativeTurnId: `${delegation}-turn-1`,
1843 + prompt,
1844 + });
1845 + const second = codexReplayPreamble({
1846 + nativeThreadId,
1847 + nativeTurnId: `${delegation}-turn-2`,
1848 + prompt,
1849 + });
1850 + const completed = (nativeTurnId: string): CodexReplay.CodexAppServerReplayEntry => ({
1851 + type: "emit_inbound",
1852 + label: `${nativeTurnId} completed`,
1853 + frame: {
1854 + method: "turn/completed",
1855 + params: {
1856 + threadId: nativeThreadId,
1857 + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1858 + },
1859 + },
1860 + });
1861 + // The second turn is a barrier: a stray sample from the first turn is sent before it ends.
1862 + const requests: Array<string> = [];
1863 + const enabled = yield* Ref.make(true);
1864 + const harness = yield* makeCodexReplayHarness(
1865 + makeCodexReplayTranscript({
1866 + scenario: `prompt-suggestion-${delegation}`,
1867 + entries: [
1868 + ...first,
1869 + completed(`${delegation}-turn-1`),
1870 + ...second.slice(5, 7).map((entry) => withReplayRequestId(entry, 4)),
1871 + completed(`${delegation}-turn-2`),
1872 + ],
1873 + }),
1874 + undefined,
1875 + (method) => Effect.sync(() => requests.push(method)),
1876 + undefined,
1877 + undefined,
1878 + undefined,
1879 + Ref.get(enabled),
1880 + );
1881 + // The flag is read per turn: turning it off after the session opened stops sampling.
1882 + if (delegation === "toggled-off") yield* Ref.set(enabled, false);
1883 + const base = makeCodexTestTurnInput({
1884 + threadId: harness.threadId,
1885 + providerThread: harness.providerThread,
1886 + now: yield* DateTime.now,
1887 + attemptId: RunAttemptId.make(`${delegation}-attempt-1`),
1888 + text: prompt,
1889 + });
1890 + const parentThreadId = ThreadId.make("thread-codex-suggestion-parent");
1891 + const turn = {
1892 + ...base,
1893 + appThread:
1894 + delegation === "toggled-off"
1895 + ? base.appThread
1896 + : delegation === "subagent"
1897 + ? {
1898 + ...base.appThread,
1899 + lineage: {
1900 + parentThreadId,
1901 + relationshipToParent: "subagent" as const,
1902 + rootThreadId: parentThreadId,
1903 + },
1904 + }
1905 + : {
1906 + ...base.appThread,
1907 + delegatedFrom: {
1908 + environmentId: EnvironmentId.make("environment-codex-suggestion-parent"),
1909 + threadId: parentThreadId,
1910 + title: "Parent",
1911 + },
1912 + },
1913 + };
1914 + yield* harness.runtime.startTurn(turn);
1915 + yield* harness.awaitTerminal(1);
1916 + yield* harness.runtime.startTurn({
1917 + ...turn,
1918 + runId: RunId.make(`${delegation}-run-2`),
1919 + attemptId: RunAttemptId.make(`${delegation}-attempt-2`),
1920 + rootNodeId: NodeId.make(`${delegation}-root-2`),
1921 + runOrdinal: 2,
1922 + providerTurnOrdinal: 2,
1923 + });
1924 + yield* harness.awaitTerminal(2);
1925 + assert.deepEqual(
1926 + harness.terminalEvents().map((event) => event.status),
1927 + ["completed", "completed"],
1928 + );
1929 + assert.notInclude(requests, "thread/sample");
1930 + }).pipe(
1931 + Effect.scoped,
1932 + Effect.provide(
1933 + Layer.mergeAll(
1934 + IdAllocator.layer,
1935 + McpProviderSessions.layer,
1936 + NodeServices.layer,
1937 + NodeCrypto.layer,
1938 + ),
1939 + ),
1940 + ),
1941 + );
1942 +
1943 + it.effect("samples a next-prompt suggestion after a completed root turn", () =>
1944 + Effect.gen(function* () {
1945 + const nativeThreadId = "suggest-thread";
1946 + const nativeTurnId = "suggest-turn";
1947 + const prompt = "Add a subtract function.";
1948 + const transcript = makeCodexReplayTranscript({
1949 + scenario: "prompt-suggestion",
1950 + entries: [
1951 + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }),
1952 + {
1953 + type: "emit_inbound",
1954 + label: "turn/completed",
1955 + frame: {
1956 + method: "turn/completed",
1957 + params: {
1958 + threadId: nativeThreadId,
1959 + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1960 + },
1961 + },
1962 + },
1963 + {
1964 + type: "expect_outbound",
1965 + label: "thread/sample",
1966 + frame: {
1967 + id: 4,
1968 + method: "thread/sample",
1969 + params: {
1970 + threadId: nativeThreadId,
1971 + expectedTurnId: nativeTurnId,
1972 + prompt: CodexAdapterV2.CODEX_PROMPT_SUGGESTION_PROMPT,
1973 + effort: "low",
1974 + },
1975 + },
1976 + },
1977 + {
1978 + type: "emit_inbound",
1979 + label: "thread/sample",
1980 + frame: {
1981 + id: 4,
1982 + result: {
1983 + sourceTurnId: nativeTurnId,
1984 + responseId: "resp-suggest",
1985 + text: " add tests for subtract\n",
1986 + inputTokens: 11448,
1987 + cachedInputTokens: 11264,
1988 + outputTokens: 16,
1989 + },
1990 + },
1991 + },
1992 + ],
1993 + });
1994 + const harness = yield* makeCodexReplayHarness(
1995 + transcript,
1996 + undefined,
1997 + undefined,
1998 + undefined,
1999 + undefined,
2000 + undefined,
2001 + Effect.succeed(true),
2002 + );
2003 + const turnInput = makeCodexTestTurnInput({
2004 + threadId: harness.threadId,
2005 + providerThread: harness.providerThread,
2006 + now: yield* DateTime.now,
2007 + attemptId: RunAttemptId.make("suggest-attempt"),
2008 + text: prompt,
2009 + });
2010 + yield* harness.runtime.startTurn(turnInput);
2011 + yield* harness.until(() =>
2012 + harness.events.some((event) => event.type === "prompt_suggestion.updated"),
2013 + );
2014 + assert.deepEqual(
2015 + harness.events.filter((event) => event.type === "prompt_suggestion.updated"),
2016 + [
2017 + {
2018 + type: "prompt_suggestion.updated",
2019 + driver: CodexAdapterV2.CODEX_DRIVER_KIND,
2020 + threadId: harness.threadId,
2021 + runId: turnInput.runId,
2022 + text: "add tests for subtract",
2023 + },
2024 + ],
2025 + );
2026 + }).pipe(
2027 + Effect.scoped,
2028 + Effect.provide(
2029 + Layer.mergeAll(
2030 + IdAllocator.layer,
2031 + McpProviderSessions.layer,
2032 + NodeServices.layer,
2033 + NodeCrypto.layer,
2034 + ),
2035 + ),
2036 + ),
2037 + );
2038 +
2039 const assistantMessages = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
2040 events.filter(
2041 (
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+64
@@ -38,6 +38,7 @@ import {
38 ProviderDriverKind,
39 ProviderSetupError,
40 type ServerProviderCompatibilityAdvisory,
41 + isDelegatedAppThread,
42 } from "@t3tools/contracts";
43 import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
44 import { AgentScope } from "@t3tools/shared/AgentScope";
@@ -231,6 +232,10 @@ const decodeCodexBackgroundTerminalTerminateResponse = Schema.decodeUnknownEffec
232 const decodeCodexBackgroundTerminalsListResponse = Schema.decodeUnknownEffect(
233 CodexBackgroundTerminalsListResponse,
234 );
235 +const CodexThreadSampleResponse = Schema.Struct({ text: Schema.NullOr(Schema.String) });
236 +const decodeCodexThreadSampleResponse = Schema.decodeUnknownEffect(CodexThreadSampleResponse);
237 +export const CODEX_PROMPT_SUGGESTION_PROMPT =
238 + "Predict the next message the user will send in this conversation. Reply with only that message, written as the user would type it, in under 20 words. Do not use tools. If there is no clear next step, reply with nothing.";
239 const CODEX_CLIENT_CAPABILITIES = {
240 experimentalApi: true,
241 optOutNotificationMethods: ["turn/diff/updated"],
@@ -2016,6 +2021,43 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2021 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
2022 Queue.offer(events, event).pipe(Effect.asVoid);
2023
2024 + const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false);
2025 + // Best effort: older Codex lacks thread/sample, and a sample fails once the user sends again.
2026 + // Delegated threads share this session but have no one typing, so they never sample.
2027 + const samplePromptSuggestion = Effect.fn("CodexAdapterV2.samplePromptSuggestion")(
2028 + function* (
2029 + context: ActiveCodexTurnContext,
2030 + nativeThreadId: string,
2031 + nativeTurnId: string,
2032 + ) {
2033 + if (
2034 + isDelegatedAppThread(context.input.appThread) ||
2035 + !(yield* promptSuggestionsEnabled)
2036 + ) {
2037 + return;
2038 + }
2039 + const response = yield* client.raw.request("thread/sample", {
2040 + threadId: nativeThreadId,
2041 + expectedTurnId: nativeTurnId,
2042 + prompt: CODEX_PROMPT_SUGGESTION_PROMPT,
2043 + effort: "low",
2044 + });
2045 + const suggestion =
2046 + (yield* decodeCodexThreadSampleResponse(response)).text?.trim() ?? "";
2047 + if (suggestion.length === 0) return;
2048 + yield* emitProviderEvent({
2049 + type: "prompt_suggestion.updated",
2050 + driver: CODEX_PROVIDER,
2051 + threadId: context.projectionThreadId,
2052 + runId: context.input.runId,
2053 + text: suggestion,
2054 + });
2055 + },
2056 + Effect.catchCause((cause) =>
2057 + Effect.logDebug("orchestration-v2.codex-prompt-suggestion-failed", { cause }),
2058 + ),
2059 + );
2060 +
2061 const emitImageWorkState =
2062 /* Provider events include streaming deltas; avoid a span for each update. */
2063 Effect.fnUntraced(function* (context: ActiveCodexTurnContext, pending: boolean) {
@@ -6038,6 +6080,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6080 });
6081 yield* emitRootTerminal(hold.context, { ...hold.event, status });
6082 yield* Deferred.succeed(hold.next, undefined);
6083 + const nativeThreadId = hold.context.providerThread.nativeThreadRef?.nativeId;
6084 + if (status === "completed" && nativeThreadId != null) {
6085 + yield* samplePromptSuggestion(
6086 + hold.context,
6087 + nativeThreadId,
6088 + hold.context.nativeTurnId,
6089 + ).pipe(Effect.forkIn(scope));
6090 + }
6091 });
6092
6093 const releaseGoalHold = Effect.fnUntraced(function* (
@@ -6369,6 +6419,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6419 const retainSettledContext =
6420 input.status === "completed" &&
6421 (yield* turnHasRetainedBackgroundWork(input.nativeTurnId));
6422 + // A held goal predicts when settleGoalHold completes it.
6423 + if (
6424 + input.status === "completed" &&
6425 + input.context.subagent === null &&
6426 + !input.continueRun &&
6427 + !holdsForGoal &&
6428 + nativeThreadId != null
6429 + ) {
6430 + yield* samplePromptSuggestion(
6431 + input.context,
6432 + nativeThreadId,
6433 + input.nativeTurnId,
6434 + ).pipe(Effect.forkIn(scope));
6435 + }
6436 if (retainSettledContext) {
6437 yield* Ref.update(settledTurns, (current) => {
6438 const updated = new Map(current);
apps/server/src/orchestration-v2/EffectWorker.test.ts
+2
@@ -21,6 +21,7 @@ import * as Exit from "effect/Exit";
21 import * as Layer from "effect/Layer";
22 import * as Option from "effect/Option";
23 import * as Ref from "effect/Ref";
24 +import * as Stream from "effect/Stream";
25
26 import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
27 import * as CheckpointService from "./CheckpointService.ts";
@@ -113,6 +114,7 @@ function layerExecutorFor(input: {
114 detach: () => record("detach"),
115 otherWorkingThreads: () => Effect.succeed([]),
116 releaseUnlessBusy: () => Effect.succeed(true),
117 + subscribePromptSuggestion: () => Stream.empty,
118 }),
119 ),
120 Layer.succeed(
apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+2 -1
@@ -619,7 +619,8 @@ export const layer: Layer.Layer<
619 case "background_work.updated":
620 return [];
621 case "command_output.delta":
622 - // Live output is routed to the command output hub before ingestion.
622 + case "prompt_suggestion.updated":
623 + // The session manager serves these to clients before ingestion.
624 return [];
625 case "turn.terminal":
626 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+58
@@ -8,6 +8,7 @@ import {
8 type ModelSelection,
9 type OrchestrationV2AppThread,
10 type OrchestrationV2DomainEvent,
11 + type OrchestrationV2PromptSuggestion,
12 type OrchestrationV2ProviderCapabilities,
13 type OrchestrationV2ProviderSession,
14 type OrchestrationV2ProviderThread,
@@ -2744,6 +2745,63 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre
2745 }),
2746 );
2747
2748 +it.effect(
2749 + "ProviderSessionManagerV2 stops serving prompt suggestions once a thread is deleted",
2750 + () =>
2751 + Effect.gen(function* () {
2752 + const state = yield* Ref.make(emptyState);
2753 + const effect = Effect.gen(function* () {
2754 + const eventSink = yield* EventSink.EventSinkV2;
2755 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
2756 + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
2757 + const now = yield* DateTime.now;
2758 + const threadId = ThreadId.make("thread-provider-session-manager-suggestion");
2759 + const providerSessionId = yield* idAllocator.allocate.providerSession({
2760 + providerInstanceId: modelSelection.instanceId,
2761 + threadId,
2762 + });
2763 + const created = yield* makeThreadCreatedEvent({ idAllocator, threadId, now });
2764 + yield* eventSink.write({ events: [created] });
2765 + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy });
2766 + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
2767 + const runId = idAllocator.derive.run({ threadId, ordinal: 1 });
2768 + const suggest = (text: string) =>
2769 + Queue.offer(queue!, {
2770 + type: "prompt_suggestion.updated",
2771 + driver: CODEX_DRIVER,
2772 + threadId,
2773 + runId,
2774 + text,
2775 + });
2776 + const received = yield* Queue.unbounded<OrchestrationV2PromptSuggestion>();
2777 + yield* manager.subscribePromptSuggestion(threadId).pipe(
2778 + Stream.runForEach((suggestion) => Queue.offer(received, suggestion)),
2779 + Effect.forkScoped,
2780 + );
2781 + assert.isNull(yield* Queue.take(received));
2782 +
2783 + yield* suggest("add tests");
2784 + assert.deepEqual(yield* Queue.take(received), { runId, text: "add tests" });
2785 +
2786 + yield* eventSink.write({
2787 + events: [
2788 + {
2789 + ...created,
2790 + id: yield* idAllocator.allocate.event({ threadId }),
2791 + type: "thread.deleted",
2792 + payload: { ...created.payload, deletedAt: now },
2793 + },
2794 + ],
2795 + });
2796 + // A late Codex sample can land after deletion; the open subscription must drop it.
2797 + yield* suggest("ship it");
2798 + assert.isNull(yield* Queue.take(received));
2799 + });
2800 +
2801 + yield* effect.pipe(Effect.scoped, Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 })));
2802 + }),
2803 +);
2804 +
2805 const openSessionWithBackgroundCommand = (fixtureName: string) =>
2806 Effect.gen(function* () {
2807 const eventSink = yield* EventSink.EventSinkV2;
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+47
@@ -6,6 +6,7 @@ import {
6 ModelSelection,
7 OrchestrationV2DomainEvent,
8 OrchestrationV2ProviderSession,
9 + type OrchestrationV2PromptSuggestion,
10 type OrchestrationV2ProviderThread,
11 OrchestrationV2RuntimeRequest,
12 ProviderInstanceId,
@@ -32,6 +33,7 @@ import * as Schema from "effect/Schema";
33 import * as Scope from "effect/Scope";
34 import * as Semaphore from "effect/Semaphore";
35 import * as Stream from "effect/Stream";
36 +import * as SubscriptionRef from "effect/SubscriptionRef";
37
38 import { normalizeModelMetricLabel } from "../observability/Attributes.ts";
39 import {
@@ -64,6 +66,8 @@ const busyTurnPrefix = (providerThreadId: ProviderThreadId) => `${providerThread
66 const busyTurnKey = (providerThreadId: ProviderThreadId, runOrdinal: number) =>
67 `${busyTurnPrefix(providerThreadId)}${runOrdinal}`;
68 const UNLOAD_THREAD_TIMEOUT_MS = 10 * 1000;
69 +/** Suggestions outlive their sessions, so keep only the most recently updated threads. */
70 +const MAX_PROMPT_SUGGESTIONS = 256;
71 const WORKING_RUN_STATUSES: ReadonlySet<string> = new Set([
72 "preparing",
73 "starting",
@@ -208,6 +212,10 @@ export interface ProviderSessionManagerV2Shape {
212 readonly providerSessionId: ProviderSessionId;
213 readonly threadId: ThreadId;
214 }) => Effect.Effect<ReadonlyArray<ThreadId>>;
215 + /** The thread's latest predicted next prompt, then each replacement. */
216 + readonly subscribePromptSuggestion: (
217 + threadId: ThreadId,
218 + ) => Stream.Stream<OrchestrationV2PromptSuggestion>;
219 }
220
221 export class ProviderSessionManagerV2 extends Context.Service<
@@ -345,10 +353,21 @@ export const layerWithOptions = (
353 const projectService = yield* Effect.serviceOption(ProjectService.ProjectService);
354 const eventSink = yield* EventSink.EventSinkV2;
355 const commandOutput = yield* CommandOutputHub.CommandOutputHub;
356 + const promptSuggestionStore = yield* SubscriptionRef.make<
357 + ReadonlyMap<ThreadId, NonNullable<OrchestrationV2PromptSuggestion>>
358 + >(new Map());
359 const idAllocator = yield* IdAllocator.IdAllocatorV2;
360 const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
361 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
362 const agentScope = yield* AgentScope;
363 + // Labs flag, read live: Codex per turn (its shared session outlives a toggle), Claude per query.
364 + // Unreadable settings keep it off.
365 + const promptSuggestionsEnabled = Option.isNone(serverSettings)
366 + ? Effect.succeed(false)
367 + : serverSettings.value.getSettings.pipe(
368 + Effect.map((settings) => settings.promptSuggestionsEnabled),
369 + Effect.orElseSucceed(() => false),
370 + );
371 const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")(
372 function* (threadId: ThreadId) {
373 if (Option.isNone(serverSettings)) return { browser: true, device: false };
@@ -2175,6 +2194,18 @@ export const layerWithOptions = (
2194 if (event.type === "command_output.delta") {
2195 return commandOutput.append(event);
2196 }
2197 + if (event.type === "prompt_suggestion.updated") {
2198 + return SubscriptionRef.update(promptSuggestionStore, (current) => {
2199 + const next = new Map(current);
2200 + next.delete(event.threadId);
2201 + next.set(event.threadId, { runId: event.runId, text: event.text });
2202 + for (const threadId of next.keys()) {
2203 + if (next.size <= MAX_PROMPT_SUGGESTIONS) break;
2204 + next.delete(threadId);
2205 + }
2206 + return next;
2207 + });
2208 + }
2209 const releaseLiveOutput =
2210 event.type === "turn_item.updated" &&
2211 event.turnItem.type === "command_execution" &&
@@ -2418,6 +2449,7 @@ export const layerWithOptions = (
2449 providerSessionId: input.providerSessionId,
2450 modelSelection: input.modelSelection,
2451 runtimePolicy: input.runtimePolicy,
2452 + promptSuggestions: promptSuggestionsEnabled,
2453 ...(input.resumeFromSession === undefined
2454 ? {}
2455 : { resumeFromSession: input.resumeFromSession }),
@@ -2795,6 +2827,21 @@ export const layerWithOptions = (
2827 ),
2828 ),
2829 ),
2830 + // Stored suggestions can outlive a deleted thread, so check the thread before serving one.
2831 + subscribePromptSuggestion: (threadId) =>
2832 + SubscriptionRef.changes(promptSuggestionStore).pipe(
2833 + Stream.map((suggestions) => suggestions.get(threadId) ?? null),
2834 + Stream.changes,
2835 + Stream.mapEffect((suggestion) =>
2836 + suggestion === null
2837 + ? Effect.succeed(null)
2838 + : projectionStore.getThread(threadId).pipe(
2839 + Effect.map((thread) => (thread.deletedAt === null ? suggestion : null)),
2840 + Effect.orElseSucceed(() => null),
2841 + ),
2842 + ),
2843 + Stream.changes,
2844 + ),
2845 } satisfies ProviderSessionManagerV2Shape);
2846 }),
2847 );
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+1
@@ -294,6 +294,7 @@ it.effect(
294 detach: () => Effect.void,
295 otherWorkingThreads: () => Effect.succeed([]),
296 releaseUnlessBusy: () => Effect.succeed(true),
297 + subscribePromptSuggestion: () => Stream.empty,
298 }),
299 );
300 const layerControl = ProviderTurnControlService.layer.pipe(
apps/server/src/orchestration-v2/RunExecutionService.ts
+2 -1
@@ -512,7 +512,8 @@ export function routeProviderEvent(
512 case "background_work.updated":
513 return [state.ownedProviderTurns.has(event.providerTurnId), state];
514 case "command_output.delta":
515 - // The session manager hands live output to the command output hub; runs never see it.
515 + case "prompt_suggestion.updated":
516 + // The session manager serves these to clients directly; runs never see them.
517 return [false, state];
518 case "turn.terminal":
519 return event.providerTurnId === state.rootProviderTurnId
apps/server/src/ws.ts
+2
@@ -2346,6 +2346,8 @@ export const layerWsRpc = (
2346 Effect.as(commandOutputHub.subscribe(input)),
2347 ),
2348 ),
2349 + [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) =>
2350 + providerSessionManager.subscribePromptSuggestion(input.threadId),
2351 [WS_METHODS.scheduledTasksSubscribe]: (_input) =>
2352 scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)),
2353 [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input),
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+5
@@ -46,6 +46,7 @@ import {
46 useRef,
47 useState,
48 type KeyboardEvent as ReactKeyboardEvent,
49 + type ReactNode,
50 type RefObject,
51 } from "react";
52 import { EditorContent, useEditor } from "@tiptap/react";
@@ -161,6 +162,8 @@ export interface ComposerPromptEditorProps {
162 skills: ReadonlyArray<ServerProviderSkill>;
163 disabled: boolean;
164 placeholder: string;
165 + /** Rendered after the placeholder text, such as a key hint. */
166 + placeholderSuffix?: ReactNode;
167 ariaLabel?: string | undefined;
168 suggestionListId?: string | undefined;
169 activeSuggestionId?: string | undefined;
@@ -876,6 +879,7 @@ function ComposerPromptEditorTiptapInner(
879 containerClassName,
880 className,
881 placeholderClassName,
882 + placeholderSuffix,
883 onChange,
884 onVisibleSelectionChange,
885 onCommandKeyDown,
@@ -1786,6 +1790,7 @@ function ComposerPromptEditorTiptapInner(
1790 )}
1791 >
1792 {placeholder}
1793 + {placeholderSuffix}
1794 </div>
1795 ) : null}
1796 </div>
apps/web/src/components/chat/ChatComposer.tsx
+35 -1
@@ -48,6 +48,7 @@ import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/
48 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
49 import * as Schema from "effect/Schema";
50 import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
51 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
52 import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
53 import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop";
54 import { splitTransferredFiles } from "./workspaceFileDrop";
@@ -244,6 +245,7 @@ import {
245 resolveProviderSlashCommandsForCwd,
246 } from "@t3tools/client-runtime/providerSkills";
247 import { useMediaQuery } from "../../hooks/useMediaQuery";
248 +import { Kbd } from "../ui/kbd";
249 import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen";
250 import { useStableCallback } from "../../hooks/useStableCallback";
251 import { usePanelAnimationSettings } from "../../panelAnimations";
@@ -264,6 +266,8 @@ import {
266 } from "./preparingComposerImages";
267 import { ComposerControlsBar } from "./ComposerControlsBar";
268 import { composerCommandKeyHandler } from "./composerCommandKey";
269 +import { usePromptSuggestion } from "./usePromptSuggestion";
270 +import { useFreshSessionArmed } from "./freshSessionArms";
271
272 function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
273 const armed = Date.now() <= deadline.current;
@@ -2226,6 +2230,27 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2230 };
2231 const expandMobileComposerStable = useStableCallback(expandMobileComposer);
2232
2233 + // Escape dismisses the suggestion so Tab moves focus again.
2234 + const { suggestion: promptSuggestion, dismiss: dismissPromptSuggestion } = usePromptSuggestion(
2235 + environmentId,
2236 + activeThread,
2237 + );
2238 + // After /clear the next message starts a fresh session that cannot see what the suggestion refers to.
2239 + const freshSessionArmed = useFreshSessionArmed(scopedThreadKey(routeThreadRef));
2240 + // Offered only where the default placeholder would show, so it never hides a pending question.
2241 + const offeredPromptSuggestion =
2242 + phase !== "running" &&
2243 + !isSendBusy &&
2244 + !freshSessionArmed &&
2245 + !speechInput.freezesEditor &&
2246 + composerContextRecords.size === 0 &&
2247 + !isComposerApprovalState &&
2248 + !activePendingProgress &&
2249 + !projectSelectionRequired &&
2250 + !showProviderUnavailable
2251 + ? promptSuggestion
2252 + : null;
2253 +
2254 const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) =>
2255 composerCommandKeyHandler({
2256 keybindings,
@@ -2261,6 +2286,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2286 readComposerSnapshot,
2287 applyPromptReplacement,
2288 submitComposer,
2289 + promptSuggestion: offeredPromptSuggestion,
2290 + dismissPromptSuggestion,
2291 })(key, event, isTaskItem);
2292
2293 const {
@@ -3429,7 +3456,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3456 ? "Choose a project above to start a thread"
3457 : showProviderUnavailable
3458 ? "Enable a provider in Settings to send a message"
3432 - : DEFAULT_COMPOSER_PLACEHOLDER
3459 + : (offeredPromptSuggestion ?? DEFAULT_COMPOSER_PLACEHOLDER)
3460 + }
3461 + placeholderSuffix={
3462 + offeredPromptSuggestion !== null ? (
3463 + <span className="ml-2 inline-flex align-[1px]">
3464 + <Kbd variant="outline">⇥ Tab</Kbd>
3465 + </span>
3466 + ) : undefined
3467 }
3468 disabled={
3469 projectSelectionRequired ||
apps/web/src/components/chat/composerCommandKey.ts
+27 -2
@@ -30,7 +30,7 @@ import type { Dispatch, RefObject, SetStateAction } from "react";
30
31 /**
32 * The composer's key handling inside the editor: send shortcuts, the slash/mention menu,
33 - * prompt history on ArrowUp/ArrowDown, plan-mode toggle, and list continuation.
33 + * prompt history on ArrowUp/ArrowDown, plan-mode toggle, prompt suggestions on Tab, and list continuation.
34 * Returns the editor's key handler; it reads the inputs captured by the render that built it.
35 */
36 export function composerCommandKeyHandler(input: {
@@ -82,6 +82,9 @@ export function composerCommandKeyHandler(input: {
82 dispatchMode: ComposerDispatchMode,
83 submissionIntent: ComposerSubmissionIntent,
84 ) => void;
85 + /** Predicted next prompt that Tab fills into an empty composer; Escape dismisses it. */
86 + readonly promptSuggestion: string | null;
87 + readonly dismissPromptSuggestion: () => void;
88 }) {
89 const {
90 keybindings,
@@ -117,6 +120,8 @@ export function composerCommandKeyHandler(input: {
120 readComposerSnapshot,
121 applyPromptReplacement,
122 submitComposer,
123 + promptSuggestion,
124 + dismissPromptSuggestion,
125 } = input;
126
127 // The composer persists across threads. A recall from thread A must not
@@ -211,7 +216,12 @@ export function composerCommandKeyHandler(input: {
216 const menuIsActive =
217 !isLiteralPendingAnswer && (composerMenuOpenRef.current || trigger !== null);
218 if (key === "Escape") {
214 - if (!menuIsActive || event.isComposing || event.keyCode === 229) return false;
219 + if (event.isComposing || event.keyCode === 229) return false;
220 + if (!menuIsActive && promptSuggestion !== null && promptRef.current.length === 0) {
221 + dismissPromptSuggestion();
222 + return true;
223 + }
224 + if (!menuIsActive) return false;
225 dismissComposerTrigger(trigger);
226 composerMenuOpenRef.current = false;
227 return true;
@@ -232,6 +242,21 @@ export function composerCommandKeyHandler(input: {
242 return true;
243 }
244 }
245 + if (
246 + key === "Tab" &&
247 + promptSuggestion !== null &&
248 + promptRef.current.length === 0 &&
249 + !menuIsActive &&
250 + !event.shiftKey &&
251 + !event.altKey &&
252 + !event.metaKey &&
253 + !event.ctrlKey &&
254 + !event.isComposing &&
255 + event.keyCode !== 229
256 + ) {
257 + // The typing guard must see this draft, so an approval that lands next is not answered with it.
258 + return applyPromptReplacement(0, 0, promptSuggestion);
259 + }
260 if ((key === "ArrowUp" || key === "ArrowDown") && submissionIntent === null) {
261 return navigatePromptHistory(key === "ArrowUp" ? "backward" : "forward", event);
262 }
apps/web/src/components/chat/usePromptSuggestion.ts new
+55
@@ -0,0 +1,55 @@
1 +import type { EnvironmentId, RunId } from "@t3tools/contracts";
2 +import { useSyncExternalStore } from "react";
3 +
4 +import type { Thread } from "../../types";
5 +import { useMediaQuery } from "../../hooks/useMediaQuery";
6 +import { useServerConfigs } from "../../state/entities";
7 +import { orchestrationEnvironment } from "../../state/orchestration";
8 +import { useEnvironmentQuery } from "../../state/query";
9 +
10 +// Dismissed suggestions, keyed by environment and run, shared by every mounted composer and kept
11 +// across remounts. Run ids derive from thread ids, which can repeat across environments.
12 +let dismissedKeys: ReadonlySet<string> = new Set();
13 +const listeners = new Set<() => void>();
14 +const subscribeDismissed = (listener: () => void) => {
15 + listeners.add(listener);
16 + return () => listeners.delete(listener);
17 +};
18 +const readDismissed = () => dismissedKeys;
19 +const dismissKey = (environmentId: EnvironmentId, runId: RunId) => `${environmentId}\u0000${runId}`;
20 +
21 +/**
22 + * The provider's predicted next prompt, while the run that produced it is the thread's latest
23 + * completed run and Escape has not dismissed it.
24 + */
25 +export function usePromptSuggestion(
26 + environmentId: EnvironmentId,
27 + thread: Thread | undefined,
28 +): { readonly suggestion: string | null; readonly dismiss: () => void } {
29 + // Older servers decode the missing setting as false, so true also proves the method exists.
30 + const enabled = useServerConfigs().get(environmentId)?.settings.promptSuggestionsEnabled === true;
31 + // Tab is the only way to accept one, so skip devices with no mouse or trackpad at all.
32 + const hasFinePointer = useMediaQuery("(any-pointer: fine)");
33 + const { data } = useEnvironmentQuery(
34 + // A local draft has no run, and so no suggestion, until its first send.
35 + enabled && hasFinePointer && thread?.latestRun
36 + ? orchestrationEnvironment.v2.promptSuggestion({
37 + environmentId,
38 + input: { threadId: thread.id },
39 + })
40 + : null,
41 + );
42 + const dismissed = useSyncExternalStore(subscribeDismissed, readDismissed);
43 + const latestRun = thread?.latestRun;
44 + const offered =
45 + data && latestRun?.runId === data.runId && latestRun.status === "completed" ? data : null;
46 + return {
47 + suggestion:
48 + offered && !dismissed.has(dismissKey(environmentId, offered.runId)) ? offered.text : null,
49 + dismiss: () => {
50 + if (offered === null) return;
51 + dismissedKeys = new Set(dismissedKeys).add(dismissKey(environmentId, offered.runId));
52 + for (const listener of listeners) listener();
53 + },
54 + };
55 +}
apps/web/src/components/settings/LabsSettingsPanel.tsx
+24
@@ -22,6 +22,7 @@ export function LabsSettingsPanel() {
22 {/* Clerk is only mounted when this build has T3 Connect. */}
23 {hasCloudPublicConfig() ? <GuestLinksRowWithSignIn /> : <GuestLinksRow />}
24 <LinkedEnvironmentsRow />
25 + <PromptSuggestionsRow />
26 <SimlockHostsRow />
27 <FastWorktreeCheckoutRow />
28 </SettingsSection>
@@ -166,6 +167,29 @@ function LinkedEnvironmentsRow() {
167 );
168 }
169
170 +function PromptSuggestionsRow() {
171 + const settings = useScopedSettings();
172 + const updateSettings = useUpdateScopedSettings();
173 + return (
174 + <SettingsRow
175 + serverScoped
176 + {...searchableSetting("prompt-suggestions-beta")}
177 + settingKeys={["promptSuggestionsEnabled"]}
178 + description="Show a predicted next message in the empty composer after a Claude or Codex turn. Tab uses it. Each is an extra cached request on your plan. Needs Codex 0.165+. Claude threads update on restart."
179 + control={
180 + <ScopedSwitch
181 + settingKeys={["promptSuggestionsEnabled"]}
182 + checked={settings.promptSuggestionsEnabled}
183 + onCheckedChange={(checked) =>
184 + updateSettings({ promptSuggestionsEnabled: Boolean(checked) })
185 + }
186 + aria-label="Suggest next prompt"
187 + />
188 + }
189 + />
190 + );
191 +}
192 +
193 function SimlockHostsRow() {
194 const settings = useScopedSettings();
195 const updateSettings = useUpdateScopedSettings();
apps/web/src/components/settings/settingsSearch.ts
+7
@@ -492,6 +492,13 @@ export const SETTINGS_SEARCH_ITEMS = [
492 scope: "environment",
493 searchTerms: ["beta link another machine vps peer agents work there delegate"],
494 },
495 + {
496 + id: "prompt-suggestions-beta",
497 + title: "Suggest next prompt",
498 + to: "/settings/labs",
499 + scope: "environment",
500 + searchTerms: ["beta tab autocomplete predict next message claude codex ghost text"],
501 + },
502 {
503 id: "simlock-hosts",
504 title: "Simlock device hosts (alpha)",
apps/web/src/components/ui/kbd.tsx
+12 -2
@@ -2,11 +2,21 @@ import type * as React from "react";
2
3 import { cn } from "~/lib/utils";
4
5 -function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
5 +function Kbd({
6 + className,
7 + variant = "default",
8 + ...props
9 +}: React.ComponentProps<"kbd"> & {
10 + /** `outline` draws a physical key, so the hint stays distinct inside surrounding text. */
11 + variant?: "default" | "outline";
12 +}) {
13 return (
14 <kbd
15 className={cn(
9 - "pointer-events-none inline-flex h-5 min-w-5 select-none items-center justify-center gap-1 rounded bg-foreground/[0.07] px-1 font-medium font-sans text-muted-foreground text-xs [&_svg:not([class*='size-'])]:size-3",
16 + "pointer-events-none inline-flex h-5 min-w-5 select-none items-center justify-center gap-1 rounded px-1 font-medium font-sans text-muted-foreground text-xs [&_svg:not([class*='size-'])]:size-3",
17 + variant === "outline"
18 + ? "border border-b-2 border-foreground/15 px-1.5"
19 + : "bg-foreground/[0.07]",
20 className,
21 )}
22 data-slot="kbd"
docs/user/composer.md
+10
@@ -156,6 +156,16 @@ the text is an unedited recalled prompt, with the caret on the first visual line
156 the last visual line for `ArrowDown`, counting wrapped lines. Editing a recalled prompt turns it
157 into a normal draft.
158
159 +## Suggested next prompt
160 +
161 +Turn on **Suggest next prompt** in Settings > Labs. After a Claude or Codex turn completes, the
162 +empty composer shows a predicted next message. Press `Tab` to fill it in, then edit or send it, or
163 +press `Escape` to dismiss it. Each suggestion is one extra request that reuses the turn's prompt
164 +cache, so it uses a little of your plan's usage. Claude skips suggestions on the first turn of a
165 +thread and near usage limits. Codex needs version 0.165 or later; if T3 Code manages
166 +Codex, update it in Settings > Providers. Codex follows a change to the setting at once; open Claude
167 +threads follow it after they restart. Suggestions show on web and desktop.
168 +
169 ## Edit an earlier prompt
170
171 On web and desktop, choose **Edit from here** beneath a sent message to rewind
packages/client-runtime/src/rpc/client.ts
+1
@@ -54,6 +54,7 @@ export type EnvironmentSubscriptionRpcTag =
54 | typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell
55 | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread
56 | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput
57 + | typeof ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion
58 | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream
59 | typeof WS_METHODS.subscribeAuthAccess
60 | typeof WS_METHODS.subscribeServerConfig
packages/client-runtime/src/state/orchestration.ts
+6
@@ -152,6 +152,12 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
152 Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),
153 ),
154 }),
155 + // The open thread's predicted next prompt, while its composer is mounted.
156 + promptSuggestion: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
157 + label: "environment-data:orchestration-v2:prompt-suggestion",
158 + tag: ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion,
159 + idleTtlMs: 0,
160 + }),
161 },
162 turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
163 label: "environment-data:orchestration:turn-diff",
packages/contracts/src/orchestrationV2.ts
+22
@@ -517,6 +517,13 @@ export const OrchestrationV2AppThread = Schema.Struct({
517 });
518 export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type;
519
520 +/** A thread another agent drives: a local subagent or a task delegated from a linked environment. */
521 +export const isDelegatedAppThread = (
522 + thread: Pick<OrchestrationV2AppThread, "lineage" | "delegatedFrom">,
523 +): boolean =>
524 + // MCP-launched threads store `delegatedFrom: null` at runtime, so check both absent shapes.
525 + thread.lineage.relationshipToParent === "subagent" || thread.delegatedFrom != null;
526 +
527 /** Provider-native children cannot receive messages; T3 delegate_task children can. */
528 export function isProviderNativeSubagentThread(
529 thread: Pick<OrchestrationV2AppThread, "lineage" | "creationSource">,
@@ -3617,6 +3624,7 @@ export const ORCHESTRATION_V2_WS_METHODS = {
3624 subscribeShell: "orchestration.subscribeShell",
3625 subscribeThread: "orchestration.subscribeThread",
3626 subscribeCommandOutput: "orchestration.subscribeCommandOutput",
3627 + subscribePromptSuggestion: "orchestration.subscribePromptSuggestion",
3628 } as const;
3629
3630 export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({
@@ -3646,6 +3654,16 @@ export class OrchestrationV2CommandOutputError extends Schema.TaggedError<Orches
3654 },
3655 ) {}
3656
3657 +export const OrchestrationV2SubscribePromptSuggestionInput = Schema.Struct({
3658 + threadId: ThreadId,
3659 +});
3660 +
3661 +/** Unpersisted predicted next prompt for the run that produced it; null when there is none. */
3662 +export const OrchestrationV2PromptSuggestion = Schema.NullOr(
3663 + Schema.Struct({ runId: RunId, text: Schema.String }),
3664 +);
3665 +export type OrchestrationV2PromptSuggestion = typeof OrchestrationV2PromptSuggestion.Type;
3666 +
3667 export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({
3668 schemaVersion: PositiveInt,
3669 snapshotSequence: NonNegativeInt,
@@ -4325,6 +4343,10 @@ export const OrchestrationV2RpcSchemas = {
4343 input: OrchestrationV2SubscribeCommandOutputInput,
4344 output: OrchestrationV2CommandOutputFrame,
4345 },
4346 + subscribePromptSuggestion: {
4347 + input: OrchestrationV2SubscribePromptSuggestionInput,
4348 + output: OrchestrationV2PromptSuggestion,
4349 + },
4350 } as const;
4351
4352 export const ProviderReplayEntry = Schema.Union([
packages/contracts/src/rpc.ts
+11
@@ -1920,6 +1920,16 @@ const WsOrchestrationV2SubscribeCommandOutputRpc = Rpc.make(
1920 },
1921 );
1922
1923 +const WsOrchestrationV2SubscribePromptSuggestionRpc = Rpc.make(
1924 + ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion,
1925 + {
1926 + payload: OrchestrationV2RpcSchemas.subscribePromptSuggestion.input,
1927 + success: OrchestrationV2RpcSchemas.subscribePromptSuggestion.output,
1928 + error: EnvironmentAuthorizationError,
1929 + stream: true,
1930 + },
1931 +);
1932 +
1933 const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, {
1934 payload: Schema.Struct({}),
1935 success: TerminalMetadataStreamEvent,
@@ -2256,4 +2266,5 @@ export const WsRpcGroup = RpcGroup.make(
2266 WsOrchestrationV2SubscribeShellRpc,
2267 WsOrchestrationV2SubscribeThreadRpc,
2268 WsOrchestrationV2SubscribeCommandOutputRpc,
2269 + WsOrchestrationV2SubscribePromptSuggestionRpc,
2270 ).middleware(RpcScopeAuthorization);
packages/contracts/src/settings.ts
+3
@@ -1374,6 +1374,8 @@ export const ServerSettings = Schema.Struct({
1374 * and tasks on another machine; tasks already running there finish.
1375 */
1376 linkedEnvironmentsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1377 + /** Beta: Claude and Codex predict the next prompt after completed turns. Codex follows a change at once; open Claude threads after they restart. */
1378 + promptSuggestionsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1379 sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
1380 Schema.withDecodingDefault(Effect.succeed(false)),
1381 ),
@@ -1767,6 +1769,7 @@ export const ServerSettingsPatch = Schema.Struct({
1769 hideTaggedThreads: Schema.optionalKey(Schema.Boolean),
1770 guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
1771 linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean),
1772 + promptSuggestionsEnabled: Schema.optionalKey(Schema.Boolean),
1773 backgroundActivity: Schema.optionalKey(
1774 Schema.Struct({
1775 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
packages/provider-core/src/server/ProviderAdapter.ts
+10
@@ -142,6 +142,14 @@ export const ProviderAdapterV2Event = Schema.Union([
142 itemId: TurnItemId,
143 chunk: Schema.String,
144 }),
145 + /** Unpersisted predicted next prompt; arrives after the run's root terminal. */
146 + Schema.Struct({
147 + type: Schema.Literal("prompt_suggestion.updated"),
148 + driver: ProviderDriverKind,
149 + threadId: ThreadId,
150 + runId: RunId,
151 + text: Schema.String,
152 + }),
153 Schema.Struct({
154 type: Schema.Literal("runtime_request.updated"),
155 driver: ProviderDriverKind,
@@ -460,6 +468,8 @@ export interface ProviderAdapterV2OpenSessionInput {
468 readonly providerSessionId: ProviderSessionId;
469 readonly modelSelection: ModelSelection;
470 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
471 + /** Labs flag, read live: emit `prompt_suggestion.updated` after completed turns, where the provider can. */
472 + readonly promptSuggestions?: Effect.Effect<boolean>;
473 readonly resumeFromSession?: OrchestrationV2ProviderSession;
474 readonly initialNativeThreadId?: string;
475 readonly initialProviderItemIdentityVersion?: 2;