Skip to content

Commit e459e7e

Browse files
Merge remote-tracking branch 'origin/main' into fix/issue-30251
2 parents 63616d9 + b7ab02e commit e459e7e

17 files changed

Lines changed: 222 additions & 30 deletions

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7274,7 +7274,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
72747274
...(command.context ? { context: command.context } : {}),
72757275
attachments: command.attachments,
72767276
...(run.contextHandoffId === null
7277-
? modelSwitchSince(projection, modelSelection, sourceRun?.modelSelection)
7277+
? modelSwitchSince(
7278+
projection,
7279+
modelSelection,
7280+
// Side chats do not show the parent's runs.
7281+
sideChatFork ? undefined : sourceRun?.modelSelection,
7282+
)
72787283
: {}),
72797284
};
72807285
const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff;

‎apps/server/src/orchestration-v2/ThreadFork.execution.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -852,7 +852,11 @@ const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadI
852852
});
853853
});
854854

855-
const askSideChat = (threadId: ThreadId, commandId: string) =>
855+
const askSideChat = (
856+
threadId: ThreadId,
857+
commandId: string,
858+
modelSelection?: (typeof forkCases)[number]["modelSelection"],
859+
) =>
856860
Effect.gen(function* () {
857861
const orchestrator = yield* Orchestrator.OrchestratorV2;
858862
yield* orchestrator.dispatch({
@@ -862,6 +866,7 @@ const askSideChat = (threadId: ThreadId, commandId: string) =>
862866
messageId: MessageId.make(commandId),
863867
text: "What is the main thread doing?",
864868
attachments: [],
869+
...(modelSelection === undefined ? {} : { modelSelection }),
865870
dispatchMode: { type: "start_immediately" },
866871
createdBy: "user",
867872
creationSource: "web",
@@ -954,10 +959,17 @@ it.effect("a side chat of an idle parent still starts with the framing note", ()
954959
query.includes("FROM orchestration_v2_projection_context_transfers"),
955960
),
956961
);
957-
yield* askSideChat(sideChatId, "side-chat-idle-first-message");
962+
yield* askSideChat(sideChatId, "side-chat-idle-first-message", {
963+
...forkCases[0]!.modelSelection,
964+
model: "side-chat-model",
965+
});
958966

959967
const started = yield* orchestrator.getThreadProjection(sideChatId);
960968
assert.isNotNull(started.providerThreads[0]?.forkedFrom);
969+
// The side chat does not show the parent's run, so it is no baseline.
970+
assert.isFalse(
971+
started.turnItems.some((item) => item.type === "user_message" && item.modelSwitch),
972+
);
961973
assert.lengthOf(started.contextHandoffs, 1);
962974
const [handoff] = started.contextHandoffs;
963975
assert.isTrue(

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3367,6 +3367,7 @@ export default function ChatView(props: ChatViewProps) {
33673367
<ThreadFind onClose={focusComposerStable} />
33683368
{isWorkspaceFileDragActive ? <WorkspaceFileDropOverlay /> : null}
33693369
<ChatBannerLane
3370+
environmentId={activeThread.environmentId}
33703371
providerStatus={visibleProviderStatus}
33713372
providerStatusBannerKey={providerStatusBannerKey}
33723373
setDismissedProviderStatusBannerKey={setDismissedProviderStatusBannerKey}

‎apps/web/src/components/chat/ChatBannerLane.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {
2+
EnvironmentId,
23
OrchestrationV2ProviderFailureClass,
34
ProviderInstanceId,
45
ServerProvider,
@@ -13,6 +14,7 @@ import { dismissThreadErrorBannerForSession, ThreadErrorBanner } from "./ThreadE
1314
* values, so a ChatView render that changes neither banner leaves both cached.
1415
*/
1516
export function ChatBannerLane(props: {
17+
environmentId: EnvironmentId;
1618
providerStatus: ServerProvider | null;
1719
providerStatusBannerKey: string | null;
1820
setDismissedProviderStatusBannerKey: Dispatch<SetStateAction<string | null>>;
@@ -41,6 +43,7 @@ export function ChatBannerLane(props: {
4143
return (
4244
<div className="chat-banner-lane pointer-events-none absolute top-0 z-30 flex flex-col">
4345
<ProviderStatusBanner
46+
environmentId={props.environmentId}
4447
status={providerStatus}
4548
onDismiss={() => setDismissedProviderStatusBannerKey(providerStatusBannerKey)}
4649
onOpenProviderSetup={onOpenProviderSetup}

‎apps/web/src/components/chat/ProviderStatusBanner.tsx‎

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1-
import { type ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
2-
import { memo } from "react";
1+
import {
2+
type EnvironmentId,
3+
type ProviderInstanceId,
4+
type ServerProvider,
5+
} from "@t3tools/contracts";
6+
import { useAtomValue } from "@effect/atom-react";
7+
import { memo, useRef, useState } from "react";
38
import { InfoIcon, XIcon } from "lucide-react";
49
import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
510
import { Button, InlineButton } from "../ui/button";
611
import { formatProviderDriverKindLabel } from "../../providerModels";
712
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
13+
import { serverEnvironment } from "../../state/server";
14+
import { useAtomCommand } from "../../state/use-atom-command";
15+
import { RefreshIcon } from "../ui/refresh-icon";
816

917
function getIncompatibleVersion(status: ServerProvider) {
1018
const compatibility = status.compatibilityAdvisory;
@@ -86,14 +94,35 @@ export function getProviderStatusMessage(status: ServerProvider): string {
8694
}
8795

8896
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
97+
environmentId,
8998
onDismiss,
9099
onOpenProviderSetup,
91100
status,
92101
}: {
102+
environmentId: EnvironmentId;
93103
onDismiss: () => void;
94104
onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
95105
status: ServerProvider | null;
96106
}) {
107+
const canRefresh = useAtomValue(serverEnvironment.refreshProviders.permissionAtom(environmentId));
108+
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
109+
label: "Refresh provider status",
110+
});
111+
const refreshingRef = useRef(false);
112+
const [isRefreshing, setIsRefreshing] = useState(false);
113+
114+
const refresh = async () => {
115+
if (!status || !canRefresh || refreshingRef.current) return;
116+
refreshingRef.current = true;
117+
setIsRefreshing(true);
118+
await refreshProviders({
119+
environmentId,
120+
input: { instanceId: status.instanceId, refreshModels: true },
121+
});
122+
refreshingRef.current = false;
123+
setIsRefreshing(false);
124+
};
125+
97126
if (!status || getProviderStatusBannerKey(status) === null) {
98127
return null;
99128
}
@@ -121,17 +150,31 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
121150
<InfoIcon />
122151
<AlertTitle>{title}</AlertTitle>
123152
<AlertDescription>
124-
<Tooltip>
125-
<TooltipTrigger render={<div className="line-clamp-3" />}>{message}</TooltipTrigger>
126-
<TooltipPopup side="top" className="whitespace-pre-wrap">
127-
{message}
128-
</TooltipPopup>
129-
</Tooltip>
130-
{onOpenProviderSetup && hasProviderSetup(status) ? (
131-
<InlineButton onClick={() => onOpenProviderSetup(status.instanceId)}>
132-
Open provider setup
133-
</InlineButton>
134-
) : null}
153+
<div className="flex flex-col gap-2">
154+
<Tooltip>
155+
<TooltipTrigger render={<div className="line-clamp-3" />}>{message}</TooltipTrigger>
156+
<TooltipPopup side="top" className="whitespace-pre-wrap">
157+
{message}
158+
</TooltipPopup>
159+
</Tooltip>
160+
<div className="flex flex-wrap items-center justify-end gap-3">
161+
{onOpenProviderSetup && hasProviderSetup(status) ? (
162+
<InlineButton onClick={() => onOpenProviderSetup(status.instanceId)}>
163+
Open provider setup
164+
</InlineButton>
165+
) : null}
166+
<Button
167+
aria-label={`Refresh ${providerName} provider status`}
168+
disabled={!canRefresh || isRefreshing}
169+
onClick={() => void refresh()}
170+
size="xs"
171+
variant="outline"
172+
>
173+
<RefreshIcon />
174+
{isRefreshing ? "Refreshing..." : "Refresh"}
175+
</Button>
176+
</div>
177+
</div>
135178
</AlertDescription>
136179
<AlertAction>
137180
<Button

‎apps/web/src/markdown-clipboard.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,32 @@ describe("serializeRenderedMarkdownFragment", () => {
206206
expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
207207
});
208208

209+
it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
210+
const code = ["import os", "", "", "def main():"];
211+
const list = new FakeElement("OL").append(
212+
new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
213+
);
214+
const quote = new FakeElement("BLOCKQUOTE").append(
215+
new FakeElement("P").append(new FakeText("Note:")),
216+
renderedCodeBlock(code),
217+
);
218+
const nestedFence = new FakeElement("DIV").append(
219+
new FakeElement("P").append(new FakeText("Example:")),
220+
renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
221+
);
222+
223+
expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
224+
"Example:\n\n````\n```js\na()\n\n\nb() \n```\n````",
225+
);
226+
227+
expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
228+
"1. Create it:\n ```\n import os\n\n\n def main():\n ```",
229+
);
230+
expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
231+
"> Note:\n>\n> ```\n> import os\n>\n>\n> def main():\n> ```",
232+
);
233+
});
234+
209235
it("omits fences when a selection past the last line drags in the whole code block", () => {
210236
const container = new FakeElement("DIV").append(
211237
renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),

‎apps/web/src/markdown-clipboard.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,14 @@ function codeFenceFor(code: string): string {
5757
return "`".repeat(Math.max(3, longestRun + 1));
5858
}
5959

60+
function outsideCodeFences(markdown: string, tidy: (prose: string) => string): string {
61+
// A fence closes only at its own opening run, so split yields [prose, fence, run] triples.
62+
return markdown
63+
.split(/((`{3,})[\s\S]*?(?:\2|$))/)
64+
.map((part, index) => (index % 3 === 0 ? tidy(part) : index % 3 === 1 ? part : ""))
65+
.join("");
66+
}
67+
6068
function resolveCodeBlockLanguage(pre: Element): string | null {
6169
const declared =
6270
pre.closest("[data-language]")?.getAttribute("data-language") ??
@@ -120,11 +128,11 @@ function serializeListItem(
120128
const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
121129
const bullet = ordered ? `${index}. ` : "- ";
122130
const marker = `${bullet}${task}`;
123-
let content = serializeChildren(item, inTableCell)
124-
.replace(/\n{3,}/g, "\n\n")
125-
.trim();
131+
let content = outsideCodeFences(serializeChildren(item, inTableCell), (prose) =>
132+
prose.replace(/\n{3,}/g, "\n\n"),
133+
).trim();
126134
if (!item.querySelector(":scope > p")) {
127-
content = content.replace(/\n{2,}/g, "\n");
135+
content = outsideCodeFences(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
128136
}
129137
// Continuations align after the bullet; task boxes belong to the item text.
130138
const continuationIndent = " ".repeat(bullet.length);
@@ -143,9 +151,9 @@ function serializeList(list: Element, ordered: boolean, inTableCell: boolean): s
143151
}
144152

145153
function serializeBlockquote(quote: Element, inTableCell: boolean): string {
146-
const content = serializeChildren(quote, inTableCell)
147-
.replace(/\n{3,}/g, "\n\n")
148-
.trim();
154+
const content = outsideCodeFences(serializeChildren(quote, inTableCell), (prose) =>
155+
prose.replace(/\n{3,}/g, "\n\n"),
156+
).trim();
149157
if (!content) return "";
150158
const quoted = content
151159
.split("\n")
@@ -316,13 +324,9 @@ function soleCodeBlock(container: Node): Element | null {
316324
}
317325

318326
function tidyMarkdown(markdown: string): string {
319-
return markdown
320-
.split(/(```[\s\S]*?(?:```|$))/)
321-
.map((part, index) =>
322-
index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
323-
)
324-
.join("")
325-
.trim();
327+
return outsideCodeFences(markdown, (prose) =>
328+
prose.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
329+
).trim();
326330
}
327331

328332
export function serializeRenderedMarkdownFragment(container: Node): string {

‎packages/client-runtime/src/state/commandPermissions.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,40 @@ const setup = Effect.gen(function* () {
6767
});
6868

6969
describe("command permissions", () => {
70+
it.effect("requires the destination read grant to refresh providers", () =>
71+
Effect.scoped(
72+
Effect.gen(function* () {
73+
const registry = yield* setup;
74+
const refresh = createCommandPermissions(runtime, WS_METHODS.serverRefreshProviders);
75+
registry.set(sessions(env), AsyncResult.success(grant(true)));
76+
expect(registry.get(refresh.permissionAtom(env))).toBe(false);
77+
expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
78+
"EnvironmentAuthorizationError",
79+
);
80+
registry.set(
81+
sessions(env),
82+
AsyncResult.success({
83+
...grant(false),
84+
scopes: [AuthOrchestrationReadScope],
85+
permissions: [AuthOrchestrationReadScope],
86+
}),
87+
);
88+
expect(registry.get(refresh.permissionAtom(env))).toBe(true);
89+
yield* refresh.authorize(registry, env);
90+
registry.set(sessions(other), AsyncResult.success(grant(false)));
91+
expect(registry.get(refresh.permissionAtom(other))).toBe(false);
92+
expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
93+
"EnvironmentAuthorizationError",
94+
);
95+
registry.set(sessions(env), AsyncResult.success(grant(false)));
96+
expect(registry.get(refresh.permissionAtom(env))).toBe(false);
97+
expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
98+
"EnvironmentAuthorizationError",
99+
);
100+
}),
101+
),
102+
);
103+
70104
it.effect("requires the destination preview grant to close a browser tab", () =>
71105
Effect.scoped(
72106
Effect.gen(function* () {

‎packages/contracts/src/clientRpcPermissions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
2020
[WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
2121
[WS_METHODS.serverRunStorageCleanup]: AuthSettingsWriteScope,
2222
[WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope,
23+
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
2324
[WS_METHODS.pullRequestsRunAction]: AuthSourceControlWriteScope,
2425
[WS_METHODS.pullRequestsUpdate]: AuthSourceControlWriteScope,
2526
[WS_METHODS.pullRequestsComment]: AuthSourceControlWriteScope,

‎packages/provider-pi/src/server/adapter.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1591,6 +1591,9 @@ describe("PiAdapterV2", () => {
15911591
arg === "--extension" ? [spawn.args[index + 1]] : [],
15921592
);
15931593
assert.isFalse(spawn.args.includes("--no-extensions"));
1594+
// A thread's long-lived process keeps Pi's startup model refresh unless the user opts out.
1595+
assert.notInclude(spawn.args, "--offline");
1596+
assert.isUndefined(spawn.env.PI_OFFLINE);
15941597
assert.isTrue(extensions.some((path) => path?.endsWith("pi-t3-mcp-extension.ts")));
15951598
assert.equal(spawn.env.T3_MCP_URL, "http://127.0.0.1:43123/mcp");
15961599
assert.equal(spawn.env.T3_MCP_BEARER_TOKEN, "secret-pi-token");
@@ -1891,6 +1894,7 @@ describe("PiAdapterV2", () => {
18911894
assert.equal(args[args.indexOf("--fork") + 1], FAKE_SESSION_FILE);
18921895
assert.include(args, "--no-extensions");
18931896
assert.include(args, "--no-tools");
1897+
assert.include(args, "--offline");
18941898
assert.notInclude(args, "--no-session");
18951899
assert.deepEqual(
18961900
forkFake

0 commit comments

Comments
 (0)