Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"use client";
import { CodeIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Spinner } from "@/components/ui/spinner";
import { SandboxFiles } from "./sandbox-files-view";
import { isSandboxFileList, type SandboxFile } from "./sandbox-files";
import {
preferSanitizedFullToolOutput,
toolResultText,
useChatRuntimeStore,
useChatPreferencesStore,
useToolAwaitingApproval,
useToolOutputFor,
useToolPaneScope,
} from "@/features/chat";
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
import { useToolArgsStatus } from "@assistant-ui/react";
import { memo } from "react";
import { pythonToolImagePath } from "./python-tool-image-path";
import { useSandboxImage } from "./use-sandbox-image";
import { CopyBtn, ToolCodeCell } from "./tool-code-cell";
import { isToolCallRunning, toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
import { ToolLiveOutput } from "./tool-live-output";
import { ToolResultOutput } from "./tool-result-output";
interface StructuredResult {
text: string;
images: string[];
sessionId: string;
files?: SandboxFile[];
}
function CodeGlyph(props: { className?: string }) {
return <HugeiconsIcon icon={CodeIcon} {...props} />;
}
function isStructuredResult(val: unknown): val is StructuredResult {
if (typeof val !== "object" || val === null) return false;
const v = val as { files?: unknown };
return (
"text" in val &&
"images" in val &&
"sessionId" in val &&
// Persisted content can carry anything, and the card reads name off each entry.
isSandboxFileList(v.files)
);
}
function PythonToolImage({
sessionId,
filename,
}: {
sessionId: string;
filename: string;
}) {
// Shared hook: authed fetch, object URL lifetime, keyed by url so stale responses cannot land.
const { ref, state } = useSandboxImage(pythonToolImagePath(sessionId, filename));
return (
<img
ref={ref}
src={state.status === "loaded" ? state.url : undefined}
alt={filename}
loading="lazy"
className="max-w-full rounded-lg border border-border"
/>
);
}
const PythonToolUIImpl: ToolCallMessagePartComponent = ({
toolCallId,
args,
result,
status,
}) => {
const code = toolArgText((args as { code?: unknown })?.code);
const firstLine = code.split("\n")[0]?.slice(0, 60) ?? "";
const isRunning = isToolCallRunning(status);
// Args still streaming = the model is WRITING the code, not running it yet.
const { propStatus } = useToolArgsStatus();
const isWritingCode = isRunning && propStatus.code === "streaming";
let output: string;
let images: string[] = [];
let files: SandboxFile[] = [];
let sessionId = "";
if (isStructuredResult(result)) {
output = result.text;
images = result.images;
files = result.files ?? [];
sessionId = result.sessionId;
} else if (result != null) {
output = toolResultText(result);
} else {
output = "";
}
// Prefer the fuller live stream over a truncated result; after a reload only the result remains.
const paneScope = useToolPaneScope();
const fullOutput = useToolOutputFor(
useChatRuntimeStore((s) => s.toolFullOutput),
paneScope,
toolCallId,
);
const displayOutput = preferSanitizedFullToolOutput(fullOutput, output);
// The gate opens only once the call parsed, so pending approval means the script is written.
const awaitingApproval = useToolAwaitingApproval(toolCallId);
const isWriting = isWritingCode && !awaitingApproval;
const collapseByDefault = useChatPreferencesStore(
(state) => state.toolVisibility === "collapsed",
);
const scriptCell = code ? (
<div className="mt-1 pl-5">
<ToolCodeCell
label="script"
code={code}
language="python"
downloadName="script.py"
streaming={isWriting}
/>
</div>
) : null;
return (
// The script renders outside ToolFallbackContent so it stays visible on reopen, except with
// tool calls set to collapsed; awaiting approval always shows it. Created files stay outside.
<ToolFallbackRoot
defaultOpen={isRunning}
awaitingApproval={awaitingApproval}
>
<ToolFallbackTrigger
toolName={firstLine ? `Python: ${firstLine}` : "Python"}
status={status}
icon={CodeGlyph}
/>
{!collapseByDefault && scriptCell}
<ToolFallbackContent>
{collapseByDefault && scriptCell}
<div className="border-l-2 border-muted-foreground/20 pl-2">
{isRunning ? (
<>
<div className="mt-2 flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-3.5" />
<span>
{awaitingApproval
? "Waiting for approval…"
: isWriting
? "Writing code…"
: "Running…"}
</span>
</div>
{/* Live stdout streamed via tool_output SSE events. */}
<ToolLiveOutput toolCallId={toolCallId} />
</>
) : displayOutput ? (
<div className="mt-2 border-t border-dashed pt-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">
output
</span>
<CopyBtn text={displayOutput} />
</div>
<ToolResultOutput text={displayOutput} />
</div>
) : null}
{images.length > 0 && sessionId && (
<div className="mt-2 flex flex-col gap-2">
{images.map((filename) => (
<PythonToolImage
key={filename}
sessionId={sessionId}
filename={filename}
/>
))}
</div>
)}
</div>
</ToolFallbackContent>
<SandboxFiles className="ml-5" sessionId={sessionId} files={files} />
</ToolFallbackRoot>
);
};
export const PythonToolUI = memo(
PythonToolUIImpl,
) as unknown as ToolCallMessagePartComponent;
PythonToolUI.displayName = "PythonToolUI";