refactor: 下线浏览器内练习场运行时(WebContainer/Vivari 均移除),练习场进入 ESM + MCP 重规划——两条路线评估结论:前者闭源且运行时资产绑定外部域,后者单人维护且 yarn4 等工程管理在 wasm32 VM 内结构性受限;practice 页降级为占位(保留任务卡阅读与跳转,注明重建方向),删除 runtime/webcontainer 适配层、agent 工具链、终端/文件树/预览面板与 @webcontainer/api、@xterm/* 依赖;learn 环境对照左卡与首页 CTA 文案改重建口径、导航条目 react-starter→重建中;Dockerfile 修 design-lab 残留 COPY(原样会构建失败);历史实现归档 exp/vivari-playground,调研报告归档 vivari-lab
This commit is contained in:
1 parent
d1c8704b72
commit
f452495f2a
21 files changed
+35
-1144
No files matched your search
@@ -4,7 +4,6 @@
|
||||
**/dist
|
||||
**/test-results
|
||||
**/playwright-report
|
||||
apps/design-lab/e2e
|
||||
.zcode*
|
||||
.env
|
||||
.pnp.*
|
||||
|
||||
@@ -32,3 +32,6 @@ yarn-error.log*
|
||||
# ZCode local config
|
||||
.zcodeignore
|
||||
design-refs/mockup/single*/
|
||||
|
||||
# playwright 本地产物(误在仓库根运行时产生)
|
||||
/test-results
|
||||
@@ -11,7 +11,6 @@ WORKDIR /workspace
|
||||
COPY .yarnrc.yml package.json yarn.lock ./
|
||||
COPY .yarn/releases/yarn-4.9.2.cjs .yarn/releases/
|
||||
COPY apps/tutorial/package.json apps/tutorial/
|
||||
COPY apps/design-lab/package.json apps/design-lab/
|
||||
COPY packages/design-system/package.json packages/design-system/
|
||||
COPY packages/stack-idealjs/package.json packages/stack-idealjs/
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ test.describe('教程首页', () => {
|
||||
await expect(header.getByRole('link', { name: /20\d{2}-\d{2}/ }).first()).toBeVisible()
|
||||
await expect(header.getByRole('link', { name: '颜色', exact: true })).toBeVisible()
|
||||
await expect(header.getByRole('link', { name: '组件', exact: true })).toBeVisible()
|
||||
await expect(header.getByRole('link', { name: 'react-starter', exact: true })).toBeVisible()
|
||||
await expect(header.getByRole('link', { name: '重建中', exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test('技术用途直接可读,键盘能展开详情并使用实际学习入口', async ({ page }) => {
|
||||
|
||||
@@ -12,9 +12,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@stack/design-system": "workspace:*",
|
||||
"@webcontainer/api": "^1.6.4",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
|
||||
@@ -51,7 +51,7 @@ const NAV_ROWS: NavRowGroup[] = [
|
||||
label: '在线练习',
|
||||
href: '/practice.html',
|
||||
// v1 单任务直入练习场;任务库落地后由任务表生成(/practice.html?task=<id>)
|
||||
items: [{ key: 'practice-starter', label: 'react-starter', href: '/practice.html', mono: true }],
|
||||
items: [{ key: 'practice-starter', label: '重建中', href: '/practice.html', mono: true }],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** idealjs stack 首页:教程、博客与浏览器练习场入口。 */
|
||||
/** idealjs stack 首页:教程、博客与练习场(重建中)入口。 */
|
||||
import { Page } from '../../lib/ui'
|
||||
import { Button } from '@stack/design-system'
|
||||
import { MONTHS } from '../../content/blogs'
|
||||
@@ -22,7 +22,7 @@ export function App() {
|
||||
)}
|
||||
</div>
|
||||
<p className="mb-0 mt-7 text-content">
|
||||
在浏览器练习场中,通过浏览器内的 Node 运行时跑起工程,与 Agent 一起编写、运行和改进代码。
|
||||
在线练习场正在以 ESM + MCP 的形式重建;在那之前,从教程开始、在本地环境跟练。
|
||||
</p>
|
||||
<div className="mt-2.5">
|
||||
<Button tone="clash2b" href="/practice.html">打开在线练习场</Button>
|
||||
|
||||
@@ -141,15 +141,13 @@ export function App() {
|
||||
<ComparisonBoard
|
||||
connector="or"
|
||||
left={{
|
||||
label: '浏览器练习 · 推荐起步',
|
||||
label: '浏览器练习 · 重建中',
|
||||
content: (
|
||||
<>
|
||||
<dl className="learn-environment-list">
|
||||
<div><dt>运行项目</dt><dd>本站的浏览器内 Node 运行时(Vivari)直接跑起工程,无需本地安装开发工具。</dd></div>
|
||||
<div><dt>协助实现</dt><dd>Agent Playground 根据你的要求修改代码、执行命令,你通过预览检查结果。</dd></div>
|
||||
<div><dt>运行项目</dt><dd>练习场正在重建:计划以 ESM 模块承载练习工程,页面即工程、无需安装。</dd></div>
|
||||
<div><dt>协助实现</dt><dd>Agent 经 MCP 工具协议协助你写代码、跑命令——方案上线前,先走右侧本地路线。</dd></div>
|
||||
</dl>
|
||||
<p className="learn-environment-note">使用 Agent 前配置模型 API Key;项目环境会自动启动。</p>
|
||||
<Button tone="clash1b" href="/practice.html">打开浏览器练习场</Button>
|
||||
</>
|
||||
),
|
||||
}}
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
/** 在线练习——浏览器里的 WebContainer 练习场 + 陪练 agent。
|
||||
* SSG 只渲染静态壳(任务卡 + 占位面板);沙盒与 agent 都在浏览器端拉起。 */
|
||||
/** 在线练习——占位页。浏览器内运行时两条路线(WebContainer / Vivari)经评估后均已移除:
|
||||
* 前者闭源且运行时资产绑定外部域,后者单人维护、工程管理(yarn4 等)在 wasm32 VM 内结构性受限。
|
||||
* 练习场将基于 ESM + MCP 的形式重新规划;历史实现归档于 exp/vivari-playground 分支,
|
||||
* 调研报告(外部域实测 / Prisma generate 与 migrate 移植可行性)在 vivari-lab 分支的 lab/ 目录。 */
|
||||
import { Page } from '../../lib/ui'
|
||||
import { PracticeWorkspace } from './components/PracticeWorkspace'
|
||||
import { Button } from '@stack/design-system'
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<Page
|
||||
active="practice"
|
||||
title="在线练习"
|
||||
desc="浏览器里的 Node.js 练习场:一个真实的 vite + react 工程跑在 WebContainer 中。你指挥陪练 agent 改代码,预览实时更新——你负责提要求和验收,agent 负责过程。"
|
||||
desc="练习场正在重新规划:我们将以 ESM + MCP 的形式重建「在浏览器里动手写、有 Agent 陪练」的体验。在它回来之前,教程与本地跟练路线不受影响。"
|
||||
>
|
||||
<PracticeWorkspace />
|
||||
<section className="grid gap-4 lg:grid-cols-2">
|
||||
<div className="rounded-xl border-2 border-ink bg-paper p-5 shadow-hard">
|
||||
<h2 className="m-0 text-t3 font-extrabold text-ink">现在就能开始</h2>
|
||||
<p className="mt-2 mb-3 text-[13.5px] leading-6 text-body">
|
||||
教程不依赖练习场:从第一个网页写起,本地环境的跟练路线照常可用。
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2.5">
|
||||
<Button tone="clash1b" href="/learn.html">去看教程概览</Button>
|
||||
<Button href="/ch1.html">从第一个网页开始</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-xl border-2 border-dashed border-ink/40 bg-paper-deep p-5">
|
||||
<h2 className="m-0 text-t3 font-extrabold text-ink">重建中的练习场</h2>
|
||||
<p className="mt-2 mb-0 text-[13.5px] leading-6 text-body">
|
||||
计划采用 ESM + MCP 的形式:页面直接以 ESM 模块承载练习工程,Agent 经 MCP 工具协议协助你写代码、跑命令。
|
||||
方案规划完成后会在这里上线。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</Page>
|
||||
)
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
/** 聊天面板——用户与陪练 agent 的对话视图(纯展示,会话状态在工作区) */
|
||||
import { useState } from 'react'
|
||||
import type { KeyboardEvent } from 'react'
|
||||
|
||||
export interface ChatItem {
|
||||
kind: 'user' | 'assistant' | 'tool'
|
||||
text: string
|
||||
}
|
||||
|
||||
export function ChatPanel({
|
||||
items,
|
||||
busy,
|
||||
ready,
|
||||
hasKey,
|
||||
model,
|
||||
onSend,
|
||||
onStop,
|
||||
onOpenKey,
|
||||
}: {
|
||||
items: ChatItem[]
|
||||
busy: boolean
|
||||
/** WebContainer 就绪后才允许发消息 */
|
||||
ready: boolean
|
||||
hasKey: boolean
|
||||
model: string
|
||||
onSend: (text: string) => void
|
||||
onStop: () => void
|
||||
onOpenKey: () => void
|
||||
}) {
|
||||
const [draft, setDraft] = useState('')
|
||||
|
||||
const submit = () => {
|
||||
const text = draft.trim()
|
||||
if (!text || busy || !ready) return
|
||||
setDraft('')
|
||||
onSend(text)
|
||||
}
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
submit()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col rounded-xl border-2 border-ink bg-paper shadow-hard">
|
||||
{/* 头部:模型 + key 配置入口 */}
|
||||
<div className="flex items-center gap-2 border-b border-dashed border-ink/20 px-3 py-2">
|
||||
<span className="t-small-strong">陪练 agent</span>
|
||||
<span className="t-small-mute min-w-0 flex-1 truncate font-mono">{model}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenKey}
|
||||
className={`cursor-pointer rounded-lg border-2 border-ink px-2 py-0.5 text-[12px] font-bold transition-colors ${
|
||||
hasKey ? 'bg-paper text-body hover:bg-paper-deep' : 'bg-clash2a text-ink'
|
||||
}`}
|
||||
>
|
||||
{hasKey ? '接入配置' : '填写 Key'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 消息流 */}
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-2.5 overflow-auto p-3">
|
||||
{items.map((item, i) =>
|
||||
item.kind === 'tool' ? (
|
||||
<p key={i} className="t-small-mute m-0 font-mono">
|
||||
{item.text}
|
||||
</p>
|
||||
) : (
|
||||
<div key={i} className={`flex ${item.kind === 'user' ? 'justify-end' : 'justify-start'}`}>
|
||||
<div
|
||||
className={`max-w-[92%] rounded-xl border-2 border-ink px-3 py-2 text-[13.5px] leading-6 whitespace-pre-wrap ${
|
||||
item.kind === 'user' ? 'bg-paper-deep text-ink' : 'bg-paper text-body'
|
||||
}`}
|
||||
>
|
||||
{item.text}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{busy && <p className="t-small-mute m-0 animate-pulse font-mono">agent 工作中…</p>}
|
||||
</div>
|
||||
|
||||
{/* 输入区 */}
|
||||
<div className="border-t border-dashed border-ink/20 p-2.5">
|
||||
<textarea
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
rows={2}
|
||||
placeholder={
|
||||
!ready ? '练习环境启动中…' : hasKey ? '告诉 agent 要做什么(Enter 发送,Shift+Enter 换行)' : '先填写 API Key'
|
||||
}
|
||||
className="w-full resize-none rounded-lg border-2 border-ink bg-paper px-2.5 py-1.5 text-[13.5px] leading-6 outline-none focus:bg-paper-deep"
|
||||
/>
|
||||
<div className="mt-1.5 flex justify-end gap-2">
|
||||
{busy ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
className="cursor-pointer rounded-lg border-2 border-ink bg-clash1a px-3 py-1 text-[13px] font-bold text-ink transition-colors hover:bg-clash1a/80"
|
||||
>
|
||||
停止
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={!ready}
|
||||
className="cursor-pointer rounded-lg border-2 border-ink bg-clash1b px-3 py-1 text-[13px] font-bold text-ink transition-colors hover:bg-clash1b/80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
发送
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
/** 只读文件树——agent 每次 write 后由工作区重扫刷新,用户只看不改 */
|
||||
import type { FileEntry } from '../lib/webcontainer'
|
||||
|
||||
export function FileTree({ entries }: { entries: FileEntry[] | null }) {
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<p className="t-small-mute m-0 border-b border-dashed border-ink/15 px-3 py-1.5">文件</p>
|
||||
<ul className="m-0 list-none overflow-auto p-2 font-mono text-[12px] leading-5">
|
||||
{entries === null && <li className="t-small-mute">扫描中…</li>}
|
||||
{entries?.map((e) => (
|
||||
<li key={e.path} style={{ paddingLeft: (e.depth - 1) * 12 }} className="truncate">
|
||||
<span className={e.kind === 'dir' ? 'font-bold text-ink' : 'text-body'}>
|
||||
{e.kind === 'dir' ? `${e.path.split('/').pop()}/` : e.path.split('/').pop()}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/** LLM 配置弹窗——DeepSeek 预设,baseURL/model 可换(任何 OpenAI 兼容端点)。
|
||||
* key 只存本机 localStorage,随聊天请求直连所选端点,不经过任何中间服务器。 */
|
||||
import { useState } from 'react'
|
||||
import type { LlmConfig } from '../lib/agent/llm'
|
||||
|
||||
const FIELD = 'w-full rounded-lg border-2 border-ink bg-paper px-2.5 py-1.5 font-mono text-[13px] outline-none focus:bg-paper-deep'
|
||||
|
||||
export function KeyModal({
|
||||
config,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
config: LlmConfig
|
||||
onSave: (config: LlmConfig) => void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [baseURL, setBaseURL] = useState(config.baseURL)
|
||||
const [apiKey, setApiKey] = useState(config.apiKey)
|
||||
const [model, setModel] = useState(config.model)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 grid place-items-center bg-ink/40 p-4"
|
||||
onClick={onClose}
|
||||
role="presentation"
|
||||
>
|
||||
<form
|
||||
className="w-full max-w-md rounded-2xl border-2 border-ink bg-paper p-5 shadow-hard"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
onSave({ baseURL: baseURL.trim(), apiKey: apiKey.trim(), model: model.trim() })
|
||||
}}
|
||||
>
|
||||
<h2 className="m-0 text-t3 font-extrabold text-ink">模型接入</h2>
|
||||
<p className="t-small-mute mt-1.5 mb-4">
|
||||
默认 DeepSeek;也可填任何 OpenAI 兼容端点。key 仅保存在浏览器 localStorage。
|
||||
</p>
|
||||
<label className="t-small-strong mb-1 block">API 地址(baseURL)</label>
|
||||
<input className={FIELD} value={baseURL} onChange={(e) => setBaseURL(e.target.value)} spellCheck={false} />
|
||||
<label className="t-small-strong mt-3 mb-1 block">API Key</label>
|
||||
<input
|
||||
className={FIELD}
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-…"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<label className="t-small-strong mt-3 mb-1 block">模型</label>
|
||||
<input className={FIELD} value={model} onChange={(e) => setModel(e.target.value)} spellCheck={false} />
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="cursor-pointer rounded-lg border-2 border-ink bg-paper px-3 py-1.5 text-[13px] font-bold text-body transition-colors hover:bg-paper-deep"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="cursor-pointer rounded-lg border-2 border-ink bg-clash1b px-3 py-1.5 text-[13px] font-bold text-ink transition-colors hover:bg-clash1b/80"
|
||||
>
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
/** 练习场工作区:左=预览/终端 + 只读文件树,右=陪练 agent 对话。
|
||||
* SSG 首屏=静态壳(状态条 + 占位);WebContainer boot、agent 循环全部浏览器端。
|
||||
* 本组件树在 renderToString 下必须无 window 访问——副作用都在 effect/handler 里。 */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { WebContainer } from '@webcontainer/api'
|
||||
import type { ChatMessage, LlmConfig } from '../lib/agent/llm'
|
||||
import { hasKey, loadLlmConfig, saveLlmConfig } from '../lib/agent/llm'
|
||||
import { runAgentTurn, systemPrompt } from '../lib/agent/loop'
|
||||
import { scanFiles, startPracticeEnv } from '../lib/webcontainer'
|
||||
import type { FileEntry, OutputSink } from '../lib/webcontainer'
|
||||
import { taskFromLocation } from '../lib/tasks'
|
||||
import { ChatPanel } from './ChatPanel'
|
||||
import type { ChatItem } from './ChatPanel'
|
||||
import { FileTree } from './FileTree'
|
||||
import { KeyModal } from './KeyModal'
|
||||
import { PreviewPanel } from './PreviewPanel'
|
||||
import { TerminalPanel } from './TerminalPanel'
|
||||
|
||||
type Status = { kind: 'booting' | 'ready' | 'error'; message?: string }
|
||||
|
||||
/** 流式文本追加到最后一条 assistant 消息 */
|
||||
function appendAssistant(items: ChatItem[], delta: string): ChatItem[] {
|
||||
const next = items.slice()
|
||||
const last = next[next.length - 1]
|
||||
if (last && last.kind === 'assistant') next[next.length - 1] = { ...last, text: last.text + delta }
|
||||
else next.push({ kind: 'assistant', text: delta })
|
||||
return next
|
||||
}
|
||||
|
||||
/** 最后一条工具状态行由 ⚙ 改为 ✓ */
|
||||
function markToolDone(items: ChatItem[]): ChatItem[] {
|
||||
const next = items.slice()
|
||||
for (let i = next.length - 1; i >= 0; i--) {
|
||||
if (next[i].kind === 'tool') {
|
||||
next[i] = { ...next[i], text: `✓ ${next[i].text.slice(2)}` }
|
||||
break
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
const TABS = [
|
||||
{ key: 'preview', label: '预览' },
|
||||
{ key: 'terminal', label: '终端' },
|
||||
] as const
|
||||
|
||||
export function PracticeWorkspace() {
|
||||
const task = useMemo(taskFromLocation, [])
|
||||
|
||||
const sinkRef = useRef<OutputSink | null>(null)
|
||||
/** 终端未挂载时的输出缓冲(tab 切走/挂载前不丢日志),挂载时整段回放 */
|
||||
const logRef = useRef<string[]>([])
|
||||
const wcRef = useRef<WebContainer | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const historyRef = useRef<ChatMessage[]>([])
|
||||
|
||||
const [status, setStatus] = useState<Status>({ kind: 'booting' })
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null)
|
||||
const [entries, setEntries] = useState<FileEntry[] | null>(null)
|
||||
const [tab, setTab] = useState<'preview' | 'terminal'>('terminal')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [llm, setLlm] = useState<LlmConfig>(loadLlmConfig)
|
||||
const [keyOpen, setKeyOpen] = useState(false)
|
||||
const [chat, setChat] = useState<ChatItem[]>(() => [
|
||||
{
|
||||
kind: 'assistant',
|
||||
text: `我是这个练习场的陪练 agent。当前任务「${task.title}」——把想改成什么样告诉我,我来写代码;你负责看预览、逐条对照验收清单。`,
|
||||
},
|
||||
])
|
||||
|
||||
// 拉起练习环境(含模板 mount、npm install、dev server);task 变化才重启
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const sink: OutputSink = (chunk) => {
|
||||
logRef.current.push(chunk)
|
||||
if (logRef.current.length > 4096) logRef.current.splice(0, logRef.current.length - 4096)
|
||||
sinkRef.current?.(chunk)
|
||||
}
|
||||
startPracticeEnv(task.files, sink)
|
||||
.then(async (env) => {
|
||||
if (cancelled) return
|
||||
wcRef.current = env.wc
|
||||
env.previewUrl.then((url) => {
|
||||
if (cancelled) return
|
||||
setPreviewUrl(url)
|
||||
setTab('preview') // 预览就绪,把用户视线从安装日志切到页面
|
||||
})
|
||||
setStatus({ kind: 'ready' })
|
||||
setEntries(await scanFiles(env.wc))
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setStatus({ kind: 'error', message: (e as Error).message })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [task])
|
||||
|
||||
const send = (text: string) => {
|
||||
const wc = wcRef.current
|
||||
if (!wc || busy) return
|
||||
if (!hasKey(llm)) {
|
||||
setKeyOpen(true)
|
||||
return
|
||||
}
|
||||
if (historyRef.current.length === 0) historyRef.current.push({ role: 'system', content: systemPrompt(task) })
|
||||
|
||||
setChat((c) => [...c, { kind: 'user', text }, { kind: 'assistant', text: '' }])
|
||||
setBusy(true)
|
||||
const abort = new AbortController()
|
||||
abortRef.current = abort
|
||||
|
||||
runAgentTurn({
|
||||
config: llm,
|
||||
wc,
|
||||
history: historyRef.current,
|
||||
userText: text,
|
||||
signal: abort.signal,
|
||||
hooks: {
|
||||
onAssistantDelta: (delta) => setChat((c) => appendAssistant(c, delta)),
|
||||
onToolCall: (name, args) => {
|
||||
const detail =
|
||||
typeof args.path === 'string' ? args.path : typeof args.command === 'string' ? args.command : ''
|
||||
setChat((c) => [...c, { kind: 'tool', text: `⚙ ${name} ${detail}`.trim() }])
|
||||
},
|
||||
onToolResult: (name) => {
|
||||
setChat(markToolDone)
|
||||
if (name === 'write_file') scanFiles(wc).then((es) => setEntries(es))
|
||||
},
|
||||
onCommandChunk: (chunk) => sinkRef.current?.(chunk),
|
||||
},
|
||||
})
|
||||
.catch((e) => {
|
||||
const message = abort.signal.aborted ? '(已停止。)' : `⚠ 出错了:${(e as Error).message}`
|
||||
setChat((c) => [...c, { kind: 'assistant', text: message }])
|
||||
})
|
||||
.finally(() => {
|
||||
setBusy(false)
|
||||
abortRef.current = null
|
||||
})
|
||||
}
|
||||
|
||||
const stop = () => abortRef.current?.abort()
|
||||
|
||||
const statusLabel =
|
||||
status.kind === 'booting'
|
||||
? '环境启动中(boot → 装依赖 → dev server,首次约 1-2 分钟)…'
|
||||
: status.kind === 'ready'
|
||||
? '环境就绪'
|
||||
: '启动失败'
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_360px]" suppressHydrationWarning>
|
||||
{/* 状态条:横跨两列独占一行,左右两张工作卡同行起步、顶部对齐 */}
|
||||
<div className="flex items-center gap-2 lg:col-span-2">
|
||||
<span
|
||||
className={`inline-block size-2.5 rounded-full border border-ink ${
|
||||
status.kind === 'error' ? 'bg-clash1a' : status.kind === 'ready' ? 'bg-clash1b' : 'bg-clash2a'
|
||||
}`}
|
||||
/>
|
||||
<span className={status.kind === 'error' ? 'text-[13px] font-bold text-clash1a' : 't-small-mute'}>
|
||||
{statusLabel}
|
||||
</span>
|
||||
<span className="t-small-mute font-mono">· {task.label}</span>
|
||||
{status.kind === 'error' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
className="cursor-pointer rounded-lg border-2 border-ink bg-paper px-2 py-0.5 text-[12px] font-bold transition-colors hover:bg-paper-deep"
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 左列:工作区卡(tab 面板 + 文件树) + 任务卡 */}
|
||||
<section className="min-w-0">
|
||||
{status.kind === 'error' ? (
|
||||
<div className="rounded-xl border-2 border-ink bg-paper p-4 shadow-hard">
|
||||
<p className="m-0 text-[13.5px] leading-6 text-body">{status.message}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-[540px] flex-col overflow-hidden rounded-xl border-2 border-ink bg-paper shadow-hard">
|
||||
<div className="flex gap-1.5 border-b border-dashed border-ink/20 p-2">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => setTab(t.key)}
|
||||
className={`cursor-pointer rounded-lg px-2.5 py-1 text-[12.5px] font-bold transition-colors ${
|
||||
tab === t.key
|
||||
? 'bg-paper-deep text-ink shadow-[inset_0_0_0_2px_var(--color-ink)]'
|
||||
: 'text-body hover:bg-paper-deep'
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
{tab === 'preview' ? <PreviewPanel url={previewUrl} /> : <TerminalPanel sinkRef={sinkRef} logRef={logRef} />}
|
||||
</div>
|
||||
<div className="w-44 shrink-0 border-l border-dashed border-ink/20">
|
||||
<FileTree entries={entries} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 任务卡:场景 / 预期 / 验收 */}
|
||||
<div className="mt-4 rounded-xl border-2 border-ink bg-paper p-4 shadow-hard">
|
||||
<h2 className="m-0 text-t3 font-extrabold text-ink">练习任务 · {task.title}</h2>
|
||||
<p className="mt-2 mb-0 text-[13.5px] leading-6 text-body">{task.scene}</p>
|
||||
<p className="mt-2 mb-0 text-[13.5px] leading-6 text-body">{task.expectation}</p>
|
||||
<p className="t-small-strong mt-3 mb-1">验收清单</p>
|
||||
<ul className="m-0 list-disc pl-5 text-[13.5px] leading-6 text-body">
|
||||
{task.acceptance.map((a) => (
|
||||
<li key={a}>{a}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 右列:陪练 agent */}
|
||||
<section className="min-h-[540px] lg:h-[540px]">
|
||||
<ChatPanel
|
||||
items={chat}
|
||||
busy={busy}
|
||||
ready={status.kind === 'ready'}
|
||||
hasKey={hasKey(llm)}
|
||||
model={llm.model}
|
||||
onSend={send}
|
||||
onStop={stop}
|
||||
onOpenKey={() => setKeyOpen(true)}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{keyOpen && (
|
||||
<KeyModal
|
||||
config={llm}
|
||||
onClose={() => setKeyOpen(false)}
|
||||
onSave={(config) => {
|
||||
saveLlmConfig(config)
|
||||
setLlm(config)
|
||||
setKeyOpen(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/** 预览面板——dev server 就绪后用 iframe 接入练习工程 */
|
||||
export function PreviewPanel({ url }: { url: string | null }) {
|
||||
if (!url) {
|
||||
return (
|
||||
<div className="grid h-full place-items-center bg-white p-6 text-center">
|
||||
<p className="t-small-mute m-0">dev server 就绪后,练习工程的预览会显示在这里。</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return <iframe src={url} title="练习工程预览" className="h-full w-full border-0 bg-white" />
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/** 终端面板——xterm 渲染 WebContainer 的输出流水(install / dev / agent 命令共用)。
|
||||
* 只出不进:交互都由用户对 agent 说话完成,符合「用户验收、agent 过程」的练习定位。
|
||||
* xterm 是 CJS 包,SSG 的 ssrLoadModule 吃不下具名导出——动态 import 延迟到浏览器。 */
|
||||
import { useEffect, useRef } from 'react'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
import type { OutputSink } from '../lib/webcontainer'
|
||||
|
||||
export function TerminalPanel({
|
||||
sinkRef,
|
||||
logRef,
|
||||
}: {
|
||||
sinkRef: { current: OutputSink | null }
|
||||
/** 挂载前的历史输出,整段回放后接入实时流 */
|
||||
logRef: { current: string[] }
|
||||
}) {
|
||||
const elRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false
|
||||
let dispose = () => {}
|
||||
void (async () => {
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([
|
||||
import('@xterm/xterm'),
|
||||
import('@xterm/addon-fit'),
|
||||
])
|
||||
if (disposed || !elRef.current) return
|
||||
const term = new Terminal({
|
||||
convertEol: true,
|
||||
disableStdin: true,
|
||||
fontSize: 12,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
|
||||
theme: { background: '#111111', foreground: '#fff9f0', cursor: '#4ecdc4' },
|
||||
})
|
||||
const fit = new FitAddon()
|
||||
term.loadAddon(fit)
|
||||
term.open(elRef.current)
|
||||
for (const chunk of logRef.current) term.write(chunk)
|
||||
fit.fit()
|
||||
sinkRef.current = (chunk) => term.write(chunk)
|
||||
|
||||
const ro = new ResizeObserver(() => fit.fit())
|
||||
ro.observe(elRef.current)
|
||||
dispose = () => {
|
||||
sinkRef.current = null
|
||||
ro.disconnect()
|
||||
term.dispose()
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
disposed = true
|
||||
dispose()
|
||||
}
|
||||
}, [sinkRef, logRef])
|
||||
|
||||
return <div ref={elRef} className="h-full w-full bg-ink" />
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
/** LLM seam——OpenAI 兼容 chat/completions 流式客户端。
|
||||
* 默认 DeepSeek;baseURL/key/model 可换(任何兼容端点)。key 只存 localStorage,不出浏览器。 */
|
||||
|
||||
export interface LlmConfig {
|
||||
baseURL: string
|
||||
apiKey: string
|
||||
model: string
|
||||
}
|
||||
|
||||
export const DEFAULT_LLM_CONFIG: LlmConfig = {
|
||||
baseURL: 'https://api.deepseek.com/v1',
|
||||
apiKey: '',
|
||||
model: 'deepseek-chat',
|
||||
}
|
||||
|
||||
const STORE_KEY = 'practice.llm.v1'
|
||||
|
||||
export function loadLlmConfig(): LlmConfig {
|
||||
if (typeof localStorage === 'undefined') return DEFAULT_LLM_CONFIG // SSG 安全
|
||||
try {
|
||||
return { ...DEFAULT_LLM_CONFIG, ...JSON.parse(localStorage.getItem(STORE_KEY) ?? '{}') }
|
||||
} catch {
|
||||
return DEFAULT_LLM_CONFIG
|
||||
}
|
||||
}
|
||||
|
||||
export function saveLlmConfig(config: LlmConfig) {
|
||||
localStorage.setItem(STORE_KEY, JSON.stringify(config))
|
||||
}
|
||||
|
||||
export function hasKey(config: LlmConfig): boolean {
|
||||
return config.apiKey.trim().length > 0
|
||||
}
|
||||
|
||||
export interface ToolSchema {
|
||||
type: 'function'
|
||||
function: { name: string; description: string; parameters: Record<string, unknown> }
|
||||
}
|
||||
|
||||
export interface ToolCall {
|
||||
id: string
|
||||
function: { name: string; arguments: string }
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role: 'system' | 'user' | 'assistant' | 'tool'
|
||||
content: string
|
||||
tool_calls?: ToolCall[]
|
||||
tool_call_id?: string
|
||||
}
|
||||
|
||||
/** 发起一轮流式补全:文本增量走 onDelta;返回聚合完整的 assistant 消息(含 tool_calls)。 */
|
||||
export async function streamChat(opts: {
|
||||
config: LlmConfig
|
||||
messages: ChatMessage[]
|
||||
tools?: ToolSchema[]
|
||||
signal?: AbortSignal
|
||||
onDelta?: (text: string) => void
|
||||
}): Promise<ChatMessage> {
|
||||
const url = `${opts.config.baseURL.replace(/\/+$/, '')}/chat/completions`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${opts.config.apiKey.trim()}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: opts.config.model,
|
||||
messages: opts.messages,
|
||||
tools: opts.tools,
|
||||
stream: true,
|
||||
}),
|
||||
signal: opts.signal,
|
||||
})
|
||||
if (!res.ok || !res.body) {
|
||||
const detail = (await res.text().catch(() => '')).slice(0, 300)
|
||||
throw new Error(`LLM 请求失败 HTTP ${res.status}${detail ? `:${detail}` : ''}`)
|
||||
}
|
||||
|
||||
const reader = res.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buf = ''
|
||||
let content = ''
|
||||
const toolAcc = new Map<number, ToolCall>()
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += decoder.decode(value, { stream: true })
|
||||
let idx: number
|
||||
while ((idx = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, idx).trim()
|
||||
buf = buf.slice(idx + 1)
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (payload === '[DONE]') continue
|
||||
try {
|
||||
const delta = JSON.parse(payload).choices?.[0]?.delta ?? {}
|
||||
if (typeof delta.content === 'string' && delta.content) {
|
||||
content += delta.content
|
||||
opts.onDelta?.(delta.content)
|
||||
}
|
||||
for (const tc of delta.tool_calls ?? []) {
|
||||
const acc = toolAcc.get(tc.index) ?? { id: '', function: { name: '', arguments: '' } }
|
||||
if (tc.id) acc.id = tc.id
|
||||
if (tc.function?.name) acc.function.name += tc.function.name
|
||||
if (tc.function?.arguments) acc.function.arguments += tc.function.arguments
|
||||
toolAcc.set(tc.index, acc)
|
||||
}
|
||||
} catch {
|
||||
// 残包/心跳行,忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const message: ChatMessage = { role: 'assistant', content }
|
||||
if (toolAcc.size) message.tool_calls = [...toolAcc.entries()].sort(([a], [b]) => a - b).map(([, v]) => v)
|
||||
return message
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/** Agent loop——驱动一轮「用户消息 → (工具调用)* → 回复」的会话推进。
|
||||
* 模型只与 TOOL_SCHEMAS/llm seam 打交道;对 WebContainer 的访问全部经 tools seam。 */
|
||||
import type { WebContainer } from '@webcontainer/api'
|
||||
import type { ChatMessage, LlmConfig } from './llm'
|
||||
import { streamChat } from './llm'
|
||||
import type { PracticeTask } from '../tasks'
|
||||
import { taskMarkdown } from '../tasks'
|
||||
import type { ToolHooks } from './tools'
|
||||
import { TOOL_SCHEMAS, execTool } from './tools'
|
||||
|
||||
/** 单轮对话最大「模型步」数(含工具迭代),防失控 */
|
||||
const MAX_STEPS = 25
|
||||
|
||||
export function systemPrompt(task: PracticeTask): string {
|
||||
return [
|
||||
'你是「在线练习」页面的陪练 agent,运行在浏览器 WebContainer 沙盒中。',
|
||||
'用户是编程初学者,正在完成一个练习任务:你负责写代码,用户负责提出要求、看预览并验收结果。',
|
||||
'',
|
||||
`当前任务:${task.title}`,
|
||||
'任务说明(TASK.md):',
|
||||
taskMarkdown(task),
|
||||
'',
|
||||
'工作约定:',
|
||||
'- dev server 已在运行,用户始终能看到最新预览;禁止启动常驻服务(npm run dev/serve 等)。',
|
||||
'- 改动代码用 write_file 全量写入;改完直接请用户看预览,不要自行「验证页面」。',
|
||||
'- 需要确认现状时用 read_file / run_command(如 npx tsc --noEmit 查类型错误)。',
|
||||
'- 全程简体中文,简洁、教学式;完成后引导用户逐条对照验收清单。',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export interface TurnHooks extends ToolHooks {
|
||||
/** assistant 文本增量(流式) */
|
||||
onAssistantDelta: (delta: string) => void
|
||||
onToolCall: (name: string, args: Record<string, unknown>) => void
|
||||
onToolResult: (name: string, summary: string) => void
|
||||
}
|
||||
|
||||
/** 推进一轮对话:就地追加 user/assistant/tool 消息到 history。Abort 后直接抛出。 */
|
||||
export async function runAgentTurn(opts: {
|
||||
config: LlmConfig
|
||||
wc: WebContainer
|
||||
/** 完整历史(应已含 system prompt),就地追加 */
|
||||
history: ChatMessage[]
|
||||
userText: string
|
||||
signal: AbortSignal
|
||||
hooks: TurnHooks
|
||||
}): Promise<void> {
|
||||
const { config, wc, history, userText, signal, hooks } = opts
|
||||
history.push({ role: 'user', content: userText })
|
||||
|
||||
for (let step = 0; step < MAX_STEPS; step++) {
|
||||
const assistant = await streamChat({
|
||||
config,
|
||||
messages: history,
|
||||
tools: TOOL_SCHEMAS,
|
||||
signal,
|
||||
onDelta: hooks.onAssistantDelta,
|
||||
})
|
||||
history.push(assistant)
|
||||
|
||||
const calls = assistant.tool_calls ?? []
|
||||
if (!calls.length) return // 纯文本回复,本轮结束
|
||||
|
||||
for (const call of calls) {
|
||||
let args: Record<string, unknown> = {}
|
||||
try {
|
||||
args = JSON.parse(call.function.arguments || '{}')
|
||||
} catch {
|
||||
// 参数坏包也照样走 execTool 的容错路径
|
||||
}
|
||||
hooks.onToolCall(call.function.name, args)
|
||||
let result: string
|
||||
try {
|
||||
result = await execTool(wc, call.function.name, call.function.arguments, hooks)
|
||||
} catch (e) {
|
||||
result = `工具执行失败:${(e as Error).message}`
|
||||
}
|
||||
hooks.onToolResult(call.function.name, result)
|
||||
history.push({ role: 'tool', tool_call_id: call.id, content: result })
|
||||
}
|
||||
}
|
||||
|
||||
history.push({
|
||||
role: 'assistant',
|
||||
content: '(已连续执行较多步骤,先停在这里。你可以继续给指示。)',
|
||||
})
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
/** 工具 seam——agent 对练习工程的全部动作:写文件 / 读文件 / 跑命令。
|
||||
* 一律作用在 WebContainer 内,浏览器侧只拿结果摘要喂回模型。 */
|
||||
import type { WebContainer } from '@webcontainer/api'
|
||||
import type { OutputSink } from '../webcontainer'
|
||||
import type { ToolSchema } from './llm'
|
||||
|
||||
export interface ToolHooks {
|
||||
/** 命令输出进终端流水(与 install/dev 共用一块屏) */
|
||||
onCommandChunk?: OutputSink
|
||||
}
|
||||
|
||||
/** 工具结果与命令输出的截断上限(token 友好) */
|
||||
const MAX_RESULT = 4000
|
||||
|
||||
export const TOOL_SCHEMAS: ToolSchema[] = [
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'write_file',
|
||||
description: '写入或覆盖练习工程中的一个 UTF-8 文本文件。父目录不存在会自动创建。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: '工程内相对路径,如 src/App.tsx' },
|
||||
content: { type: 'string', description: '完整文件内容(全量覆盖,非增量)' },
|
||||
},
|
||||
required: ['path', 'content'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'read_file',
|
||||
description: '读取练习工程中的一个文本文件。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { path: { type: 'string', description: '工程内相对路径' } },
|
||||
required: ['path'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'run_command',
|
||||
description:
|
||||
'在练习工程根目录执行一条 shell 命令并返回输出与退出码。dev server 已在运行,不要执行长期驻留的服务类命令。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: { command: { type: 'string', description: '如 node -v、npx tsc --noEmit' } },
|
||||
required: ['command'],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
export async function execTool(
|
||||
wc: WebContainer,
|
||||
name: string,
|
||||
argsJson: string,
|
||||
hooks: ToolHooks,
|
||||
): Promise<string> {
|
||||
let args: Record<string, unknown>
|
||||
try {
|
||||
args = argsJson ? JSON.parse(argsJson) : {}
|
||||
} catch {
|
||||
return '参数不是合法 JSON,请重试。'
|
||||
}
|
||||
|
||||
switch (name) {
|
||||
case 'write_file': {
|
||||
const path = String(args.path ?? '')
|
||||
if (!path || path.startsWith('/')) return 'path 必须是工程内相对路径'
|
||||
const dir = path.split('/').slice(0, -1).join('/')
|
||||
if (dir) await wc.fs.mkdir(dir, { recursive: true }).catch(() => {})
|
||||
await wc.fs.writeFile(path, String(args.content ?? ''), { encoding: 'utf8' })
|
||||
return `已写入 ${path}(${String(args.content ?? '').length} 字符),预览将由 vite 热更新。`
|
||||
}
|
||||
case 'read_file': {
|
||||
const path = String(args.path ?? '')
|
||||
const text = await wc.fs.readFile(path, 'utf8')
|
||||
return text.length > MAX_RESULT * 2 ? `${text.slice(0, MAX_RESULT * 2)}\n…(超长截断)` : text
|
||||
}
|
||||
case 'run_command': {
|
||||
const command = String(args.command ?? '').trim()
|
||||
if (!command) return 'command 为空'
|
||||
const proc = await wc.spawn('jsh', ['-c', command])
|
||||
let output = ''
|
||||
proc.output.pipeTo(
|
||||
new WritableStream({
|
||||
write(chunk) {
|
||||
output += chunk
|
||||
hooks.onCommandChunk?.(chunk)
|
||||
},
|
||||
}),
|
||||
)
|
||||
const exit = await proc.exit
|
||||
const clipped = output.length > MAX_RESULT ? `…(前段截断)\n${output.slice(-MAX_RESULT)}` : output
|
||||
return `exit ${exit}\n${clipped || '(无输出)'}`
|
||||
}
|
||||
default:
|
||||
return `未知工具 ${name}`
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
/** 练习任务库:每个任务 = 一份注入 WebContainer 的模板工程 + 任务卡(位置/预期/场景 + 验收清单)。
|
||||
* 任务卡同时驱动两处:SSG 首屏的静态说明、agent 的 system prompt 与 TASK.md——单一数据源。
|
||||
* v1 只有 react-starter 一个任务;后续按 ch1-ch6 扩充,导航行由本表生成。 */
|
||||
import type { FileSystemTree } from '@webcontainer/api'
|
||||
|
||||
export interface PracticeTask {
|
||||
id: string
|
||||
/** 导航/任务卡上的短名 */
|
||||
label: string
|
||||
title: string
|
||||
/** 场景:给用户的开场说明(任务卡正文) */
|
||||
scene: string
|
||||
/** 预期:给 agent 与用户共同的目标描述 */
|
||||
expectation: string
|
||||
/** 验收清单:完成后用户逐条对照 */
|
||||
acceptance: string[]
|
||||
/** 注入 WebContainer 的模板工程 */
|
||||
files: FileSystemTree
|
||||
}
|
||||
|
||||
/* 模板工程文件(内联字符串,mount 进 WebContainer) */
|
||||
const starterAppTsx = `export function App() {
|
||||
return (
|
||||
<main
|
||||
style={{
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
maxWidth: 560,
|
||||
margin: '80px auto',
|
||||
padding: '24px 28px',
|
||||
border: '2px solid #111',
|
||||
borderRadius: 16,
|
||||
boxShadow: '8px 8px 0 #111',
|
||||
}}
|
||||
>
|
||||
<h1 style={{ marginTop: 0 }}>你好,练习场</h1>
|
||||
<p>这是一个 vite + react 工程,正跑在浏览器的 WebContainer 里。</p>
|
||||
<p>打开右侧对话,让 agent 把它改成你的作品。</p>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
`
|
||||
|
||||
const starterMainTsx = `import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { App } from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
`
|
||||
|
||||
const starterFiles: FileSystemTree = {
|
||||
'package.json': {
|
||||
file: {
|
||||
contents: JSON.stringify(
|
||||
{
|
||||
name: 'practice-react-starter',
|
||||
private: true,
|
||||
version: '0.0.0',
|
||||
type: 'module',
|
||||
scripts: { dev: 'vite' },
|
||||
dependencies: { react: '^18.3.1', 'react-dom': '^18.3.1' },
|
||||
devDependencies: {
|
||||
'@types/react': '^18.3.12',
|
||||
'@types/react-dom': '^18.3.1',
|
||||
'@vitejs/plugin-react': '^4.3.4',
|
||||
typescript: '~5.6.2',
|
||||
vite: '^6.0.0',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
},
|
||||
},
|
||||
'vite.config.ts': {
|
||||
file: {
|
||||
contents: `import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
})
|
||||
`,
|
||||
},
|
||||
},
|
||||
'tsconfig.json': {
|
||||
file: {
|
||||
contents: JSON.stringify(
|
||||
{
|
||||
compilerOptions: {
|
||||
target: 'ES2020',
|
||||
lib: ['ES2020', 'DOM', 'DOM.Iterable'],
|
||||
module: 'ESNext',
|
||||
moduleResolution: 'bundler',
|
||||
jsx: 'react-jsx',
|
||||
strict: true,
|
||||
skipLibCheck: true,
|
||||
noEmit: true,
|
||||
},
|
||||
include: ['src'],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
},
|
||||
},
|
||||
'index.html': {
|
||||
file: {
|
||||
contents: `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Practice</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
},
|
||||
},
|
||||
src: {
|
||||
directory: {
|
||||
'main.tsx': { file: { contents: starterMainTsx } },
|
||||
'App.tsx': { file: { contents: starterAppTsx } },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const TASKS: PracticeTask[] = [
|
||||
{
|
||||
id: 'react-starter',
|
||||
label: 'react-starter',
|
||||
title: '我的自我介绍卡',
|
||||
scene:
|
||||
'这是一个 vite + react + ts 的最小工程,已经跑在浏览器的 WebContainer 里。这是你第一次「指挥 agent」:你负责提要求和验收,agent 负责写代码。',
|
||||
expectation:
|
||||
'把 src/App.tsx 改成一张「自我介绍卡」:大标题显示一个名字(真实或虚构均可),配 3 行介绍(来自哪里 / 正在学什么 / 想做什么项目)。只用最基础的 JSX 与内联样式,不引入新依赖。',
|
||||
acceptance: [
|
||||
'预览页大标题显示名字',
|
||||
'介绍恰好 3 行',
|
||||
'只改了 src/App.tsx(可以让 agent 展示改动内容)',
|
||||
],
|
||||
files: starterFiles,
|
||||
},
|
||||
]
|
||||
|
||||
/** 由任务卡生成 TASK.md(注入模板工程,agent 的任务说明与其 UI 展示同源) */
|
||||
export function taskMarkdown(task: PracticeTask): string {
|
||||
return [
|
||||
`# 练习任务 · ${task.title}`,
|
||||
'',
|
||||
'## 位置',
|
||||
task.scene,
|
||||
'',
|
||||
'## 预期',
|
||||
task.expectation,
|
||||
'',
|
||||
'## 验收清单',
|
||||
...task.acceptance.map((a) => `- [ ] ${a}`),
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** 从 ?task= 选任务;SSG/水合差异可接受(React 客户端渲染接管) */
|
||||
export function taskFromLocation(): PracticeTask {
|
||||
if (typeof window === 'undefined') return TASKS[0]
|
||||
const id = new URLSearchParams(window.location.search).get('task')
|
||||
return TASKS.find((t) => t.id === id) ?? TASKS[0]
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
/** WebContainer 生命周期 seam:boot → mount 模板 → npm install → dev server。
|
||||
* 全部浏览器端调用;@webcontainer/api 动态 import,SSG 渲染树不触碰 window。 */
|
||||
import type { FileSystemTree, WebContainer, WebContainerProcess } from '@webcontainer/api'
|
||||
|
||||
export type { WebContainer }
|
||||
|
||||
/** 终端流水:install / dev / agent 命令的输出都汇到同一个 sink */
|
||||
export type OutputSink = (chunk: string) => void
|
||||
|
||||
export interface PracticeEnv {
|
||||
wc: WebContainer
|
||||
/** dev server 就绪后的预览地址 */
|
||||
previewUrl: Promise<string>
|
||||
}
|
||||
|
||||
function assertIsolated() {
|
||||
if (typeof window === 'undefined' || !window.crossOriginIsolated) {
|
||||
throw new Error(
|
||||
'页面未开启跨域隔离(crossOriginIsolated=false)。WebContainer 需要 COOP/COEP 响应头:' +
|
||||
'Cross-Origin-Opener-Policy: same-origin 与 Cross-Origin-Embedder-Policy: require-corp。' +
|
||||
'若在本地 vite dev/preview 之外访问,请检查反向代理是否配置了同名头。',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 拉起练习环境:mount 模板 → 装依赖 → 起 dev server。install 输出/错误都进终端流水。 */
|
||||
export async function startPracticeEnv(files: FileSystemTree, sink: OutputSink): Promise<PracticeEnv> {
|
||||
assertIsolated()
|
||||
const { WebContainer } = await import('@webcontainer/api')
|
||||
const wc = await WebContainer.boot()
|
||||
await wc.mount(files)
|
||||
|
||||
const install = await spawnPiped(wc, 'npm', ['install'], sink)
|
||||
const installExit = await install.exit
|
||||
if (installExit !== 0) {
|
||||
throw new Error(`依赖安装失败(exit ${installExit}),详情见终端。可点击「重试」重新拉起。`)
|
||||
}
|
||||
|
||||
const previewUrl = new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('dev server 90s 未就绪,请查看终端输出')), 90_000)
|
||||
wc.on('server-ready', (_port, url) => {
|
||||
clearTimeout(timer)
|
||||
resolve(url)
|
||||
})
|
||||
})
|
||||
|
||||
// dev server 常驻,不等待退出
|
||||
spawnPiped(wc, 'npm', ['run', 'dev'], sink).catch((e) => sink(`\r\ndev server 异常退出:${e.message}\r\n`))
|
||||
|
||||
return { wc, previewUrl }
|
||||
}
|
||||
|
||||
export async function spawnPiped(
|
||||
wc: WebContainer,
|
||||
command: string,
|
||||
args: string[],
|
||||
sink: OutputSink,
|
||||
): Promise<WebContainerProcess> {
|
||||
const proc = await wc.spawn(command, args)
|
||||
proc.output.pipeTo(new WritableStream({ write: sink }))
|
||||
return proc
|
||||
}
|
||||
|
||||
export interface FileEntry {
|
||||
path: string
|
||||
kind: 'file' | 'dir'
|
||||
depth: number
|
||||
}
|
||||
|
||||
/** 只读文件树快照(跳过 node_modules):agent 每次 write 后重扫 */
|
||||
export async function scanFiles(wc: WebContainer, root = '/', maxDepth = 4): Promise<FileEntry[]> {
|
||||
const out: FileEntry[] = []
|
||||
async function walk(dir: string, depth: number) {
|
||||
if (depth > maxDepth) return
|
||||
const dirents = await wc.fs.readdir(dir, { withFileTypes: true })
|
||||
for (const d of dirents) {
|
||||
if (d.name === 'node_modules' || d.name.startsWith('.')) continue
|
||||
const path = `${dir === '/' ? '' : dir}/${d.name}`
|
||||
out.push({ path, kind: d.isFile() ? 'file' : 'dir', depth })
|
||||
if (d.isDirectory()) await walk(path, depth + 1)
|
||||
}
|
||||
}
|
||||
await walk(root, 1)
|
||||
return out.sort((a, b) => (a.path === b.path ? 0 : a.path.localeCompare(b.path)))
|
||||
}
|
||||
@@ -3470,9 +3470,6 @@ __metadata:
|
||||
"@types/react": "npm:^18.3.12"
|
||||
"@types/react-dom": "npm:^18.3.1"
|
||||
"@vitejs/plugin-react": "npm:^4.3.4"
|
||||
"@webcontainer/api": "npm:^1.6.4"
|
||||
"@xterm/addon-fit": "npm:^0.11.0"
|
||||
"@xterm/xterm": "npm:^6.0.0"
|
||||
react: "npm:^18.3.1"
|
||||
react-dom: "npm:^18.3.1"
|
||||
tailwindcss: "npm:^4.1.0"
|
||||
@@ -4484,27 +4481,6 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@webcontainer/api@npm:^1.6.4":
|
||||
version: 1.6.4
|
||||
resolution: "@webcontainer/api@npm:1.6.4"
|
||||
checksum: 10/dc5366edba062d318b7fb767484638ada330b65d0eb16d23cfee2b8684e0ef48ffd32024f662d799fa6e8baf667d4db3921248fe4e4ab6116447585417cac029
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@xterm/addon-fit@npm:^0.11.0":
|
||||
version: 0.11.0
|
||||
resolution: "@xterm/addon-fit@npm:0.11.0"
|
||||
checksum: 10/daeb1cc2be794e0ee3b0f6b1cbec0ba70ac7c65f14093b405a2dfbf93bf267cd3f81490a72bb71364044ff7fd68ff0e8e124977dd812ff9914ad864c6a610c0b
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@xterm/xterm@npm:^6.0.0":
|
||||
version: 6.0.0
|
||||
resolution: "@xterm/xterm@npm:6.0.0"
|
||||
checksum: 10/2e9aef4770ce4778f4823f261491ade3863fa2141ff4607785a4c22cb6948bb0897e21581536ab1a3327a7ee59467e3549c09b61278b07a558f03ff14ba45bc4
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@xtuc/ieee754@npm:^1.2.0":
|
||||
version: 1.2.0
|
||||
resolution: "@xtuc/ieee754@npm:1.2.0"
|
||||
|
||||
Reference in new issue
Block a user