Trae Assistant commited on
Commit
9cd53be
·
1 Parent(s): cbeed7a
Files changed (9) hide show
  1. .env +3 -0
  2. api/app.ts +15 -5
  3. api/routes/ai.ts +12 -1
  4. api/routes/auth.ts +8 -8
  5. api/server.ts +8 -8
  6. src/App.tsx +1 -1
  7. src/hooks/useTheme.ts +7 -0
  8. src/pages/Home.tsx +107 -19
  9. vite.config.ts +10 -16
.env ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SILICONFLOW_API_KEY=sk-uuejewptzohwsbbutfnrkbcloaqxydjmxbeqptwphnhiuopl
2
+ SILICONFLOW_MODEL=deepseek-ai/DeepSeek-V3
3
+ PORT=3001
api/app.ts CHANGED
@@ -33,6 +33,12 @@ app.use(express.urlencoded({ extended: true, limit: '10mb' }))
33
  app.use('/api/auth', authRoutes)
34
  app.use('/api/ai', aiRoutes)
35
 
 
 
 
 
 
 
36
  /**
37
  * 健康检查接口
38
  */
@@ -58,13 +64,17 @@ app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
58
  })
59
 
60
  /**
61
- * 404 未找到处理
62
  */
63
  app.use((req: Request, res: Response) => {
64
- res.status(404).json({
65
- success: false,
66
- error: '接口不存在',
67
- })
 
 
 
 
68
  })
69
 
70
  export default app
 
33
  app.use('/api/auth', authRoutes)
34
  app.use('/api/ai', aiRoutes)
35
 
36
+ /**
37
+ * 静态文件服务 - 用于生产环境
38
+ */
39
+ const distPath = path.join(__dirname, '../dist')
40
+ app.use(express.static(distPath))
41
+
42
  /**
43
  * 健康检查接口
44
  */
 
64
  })
65
 
66
  /**
67
+ * 404 未找到处理 - 重定向到前端首页以支持 SPA 路由
68
  */
69
  app.use((req: Request, res: Response) => {
70
+ if (req.path.startsWith('/api/')) {
71
+ res.status(404).json({
72
+ success: false,
73
+ error: '接口不存在',
74
+ })
75
+ } else {
76
+ res.sendFile(path.join(distPath, 'index.html'))
77
+ }
78
  })
79
 
80
  export default app
api/routes/ai.ts CHANGED
@@ -68,7 +68,18 @@ router.post('/generate', async (req: Request, res: Response): Promise<void> => {
68
  },
69
  })
70
  } catch (error: any) {
71
- console.error('AI Generation Error:', error.response?.data || error.message)
 
 
 
 
 
 
 
 
 
 
 
72
  res.status(500).json({
73
  success: false,
74
  error: 'AI 生成失败,请稍后再试',
 
68
  },
69
  })
70
  } catch (error: any) {
71
+ const errorData = error.response?.data
72
+ console.error('AI Generation Error:', errorData || error.message)
73
+
74
+ // 针对余额不足提供更明确的提示
75
+ if (errorData?.code === 30001) {
76
+ res.status(500).json({
77
+ success: false,
78
+ error: '硅基流 API 账户余额不足,请检查您的账户余额。',
79
+ })
80
+ return
81
+ }
82
+
83
  res.status(500).json({
84
  success: false,
85
  error: 'AI 生成失败,请稍后再试',
api/routes/auth.ts CHANGED
@@ -1,33 +1,33 @@
1
  /**
2
- * This is a user authentication API route demo.
3
- * Handle user registration, login, token management, etc.
4
  */
5
  import { Router, type Request, type Response } from 'express'
6
 
7
  const router = Router()
8
 
9
  /**
10
- * User Login
11
  * POST /api/auth/register
12
  */
13
  router.post('/register', async (req: Request, res: Response): Promise<void> => {
14
- // TODO: Implement register logic
15
  })
16
 
17
  /**
18
- * User Login
19
  * POST /api/auth/login
20
  */
21
  router.post('/login', async (req: Request, res: Response): Promise<void> => {
22
- // TODO: Implement login logic
23
  })
24
 
25
  /**
26
- * User Logout
27
  * POST /api/auth/logout
28
  */
29
  router.post('/logout', async (req: Request, res: Response): Promise<void> => {
30
- // TODO: Implement logout logic
31
  })
32
 
33
  export default router
 
1
  /**
2
+ * 用户认证 API 路由演示。
3
+ * 处理用户注册、登录、Token 管理等。
4
  */
5
  import { Router, type Request, type Response } from 'express'
6
 
7
  const router = Router()
8
 
9
  /**
10
+ * 用户注册
11
  * POST /api/auth/register
12
  */
13
  router.post('/register', async (req: Request, res: Response): Promise<void> => {
14
+ // TODO: 实现注册逻辑
15
  })
16
 
17
  /**
18
+ * 用户登录
19
  * POST /api/auth/login
20
  */
21
  router.post('/login', async (req: Request, res: Response): Promise<void> => {
22
+ // TODO: 实现登录逻辑
23
  })
24
 
25
  /**
26
+ * 用户退出
27
  * POST /api/auth/logout
28
  */
29
  router.post('/logout', async (req: Request, res: Response): Promise<void> => {
30
+ // TODO: 实现退出逻辑
31
  })
32
 
33
  export default router
api/server.ts CHANGED
@@ -1,32 +1,32 @@
1
  /**
2
- * local server entry file, for local development
3
  */
4
  import app from './app.js';
5
 
6
  /**
7
- * start server with port
8
  */
9
  const PORT = process.env.PORT || 3001;
10
 
11
  const server = app.listen(PORT, () => {
12
- console.log(`Server ready on port ${PORT}`);
13
  });
14
 
15
  /**
16
- * close server
17
  */
18
  process.on('SIGTERM', () => {
19
- console.log('SIGTERM signal received');
20
  server.close(() => {
21
- console.log('Server closed');
22
  process.exit(0);
23
  });
24
  });
25
 
26
  process.on('SIGINT', () => {
27
- console.log('SIGINT signal received');
28
  server.close(() => {
29
- console.log('Server closed');
30
  process.exit(0);
31
  });
32
  });
 
1
  /**
2
+ * 本地服务入口文件,用于本地开发
3
  */
4
  import app from './app.js';
5
 
6
  /**
7
+ * 启动服务器,指定端口
8
  */
9
  const PORT = process.env.PORT || 3001;
10
 
11
  const server = app.listen(PORT, () => {
12
+ console.log(`服务器已在端口 ${PORT} 就绪`);
13
  });
14
 
15
  /**
16
+ * 优雅关闭服务器
17
  */
18
  process.on('SIGTERM', () => {
19
+ console.log('收到 SIGTERM 信号');
20
  server.close(() => {
21
+ console.log('服务器已关闭');
22
  process.exit(0);
23
  });
24
  });
25
 
26
  process.on('SIGINT', () => {
27
+ console.log('收到 SIGINT 信号');
28
  server.close(() => {
29
+ console.log('服务器已关闭');
30
  process.exit(0);
31
  });
32
  });
src/App.tsx CHANGED
@@ -6,7 +6,7 @@ export default function App() {
6
  <Router>
7
  <Routes>
8
  <Route path="/" element={<Home />} />
9
- <Route path="/other" element={<div className="text-center text-xl">Other Page - Coming Soon</div>} />
10
  </Routes>
11
  </Router>
12
  );
 
6
  <Router>
7
  <Routes>
8
  <Route path="/" element={<Home />} />
9
+ <Route path="/other" element={<div className="text-center text-xl">其他页面 - 敬请期待</div>} />
10
  </Routes>
11
  </Router>
12
  );
src/hooks/useTheme.ts CHANGED
@@ -2,21 +2,28 @@ import { useState, useEffect } from 'react';
2
 
3
  type Theme = 'light' | 'dark';
4
 
 
 
 
5
  export function useTheme() {
6
  const [theme, setTheme] = useState<Theme>(() => {
 
7
  const savedTheme = localStorage.getItem('theme') as Theme;
8
  if (savedTheme) {
9
  return savedTheme;
10
  }
 
11
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
12
  });
13
 
14
  useEffect(() => {
 
15
  document.documentElement.classList.remove('light', 'dark');
16
  document.documentElement.classList.add(theme);
17
  localStorage.setItem('theme', theme);
18
  }, [theme]);
19
 
 
20
  const toggleTheme = () => {
21
  setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
22
  };
 
2
 
3
  type Theme = 'light' | 'dark';
4
 
5
+ /**
6
+ * 主题切换 Hook
7
+ */
8
  export function useTheme() {
9
  const [theme, setTheme] = useState<Theme>(() => {
10
+ // 从本地存储读取主题
11
  const savedTheme = localStorage.getItem('theme') as Theme;
12
  if (savedTheme) {
13
  return savedTheme;
14
  }
15
+ // 默认跟随系统
16
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
17
  });
18
 
19
  useEffect(() => {
20
+ // 更新 HTML class 和本地存储
21
  document.documentElement.classList.remove('light', 'dark');
22
  document.documentElement.classList.add(theme);
23
  localStorage.setItem('theme', theme);
24
  }, [theme]);
25
 
26
+ // 切换主题方法
27
  const toggleTheme = () => {
28
  setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
29
  };
src/pages/Home.tsx CHANGED
@@ -1,6 +1,7 @@
1
  import React, { useState } from 'react';
2
- import { Layout, Input, Button, Card, List, Typography, Space, Divider } from 'antd';
3
- import { SendOutlined, HistoryOutlined, SettingOutlined, ProjectOutlined } from '@ant-design/icons';
 
4
 
5
  const { Header, Content, Sider } = Layout;
6
  const { TextArea } = Input;
@@ -8,16 +9,43 @@ const { Title, Text } = Typography;
8
 
9
  export default function Home() {
10
  const [input, setInput] = useState('');
11
- const [history] = useState([
 
 
12
  '生成一个蓝色风格的登录页面',
13
  '创建一个电商首页轮播图',
14
  '设计一个响应式的个人主页',
15
  ]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  return (
18
  <Layout style={{ minHeight: '100vh' }}>
19
  <Header style={{ background: '#fff', padding: '0 24px', display: 'flex', alignItems: 'center', borderBottom: '1px solid #f0f0f0' }}>
20
- <Title level={4} style={{ margin: 0, color: '#1890ff' }}>Generative UI Agent</Title>
21
  <div style={{ marginLeft: 'auto' }}>
22
  <Space size="large">
23
  <Button type="text" icon={<ProjectOutlined />}>项目管理</Button>
@@ -32,7 +60,10 @@ export default function Home() {
32
  <List
33
  dataSource={history}
34
  renderItem={(item) => (
35
- <List.Item style={{ cursor: 'pointer', padding: '8px 0' }}>
 
 
 
36
  <Text ellipsis>{item}</Text>
37
  </List.Item>
38
  )}
@@ -41,30 +72,37 @@ export default function Home() {
41
  </Sider>
42
  <Content style={{ padding: '24px', display: 'flex', gap: '24px' }}>
43
  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '16px' }}>
44
- <Card title="AI 对话输入" bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
45
  <TextArea
46
  rows={4}
47
  value={input}
48
  onChange={(e) => setInput(e.target.value)}
49
- placeholder="描述你想要的 UI 界面..."
50
  style={{ marginBottom: '16px' }}
 
51
  />
52
  <div style={{ textAlign: 'right' }}>
53
- <Button type="primary" icon={<SendOutlined />} size="large">
54
- 开始生成
 
 
 
 
 
 
55
  </Button>
56
  </div>
57
  </Card>
58
 
59
- <Card title="系统状态" bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
60
  <Space direction="vertical" style={{ width: '100%' }}>
61
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
62
  <Text>API 状态</Text>
63
- <Text type="success">已连接</Text>
64
  </div>
65
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
66
- <Text>模型版本</Text>
67
- <Text>GPT-4o</Text>
68
  </div>
69
  </Space>
70
  </Card>
@@ -73,13 +111,63 @@ export default function Home() {
73
  <div style={{ flex: 2 }}>
74
  <Card
75
  title="实时预览"
76
- extra={<Space><Button size="small">桌面端</Button><Button size="small">移动端</Button></Space>}
77
- style={{ height: '100%', boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}
78
- bodyStyle={{ height: 'calc(100% - 58px)', display: 'flex', alignItems: 'center', justifyCenter: 'center', background: '#f5f5f5' }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  >
80
- <div style={{ width: '100%', height: '100%', background: '#fff', border: '1px dashed #d9d9d9', borderRadius: '4px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
81
- <Text type="secondary">生成的 UI 将在这里实时显示</Text>
82
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  </Card>
84
  </div>
85
  </Content>
 
1
  import React, { useState } from 'react';
2
+ import { Layout, Input, Button, Card, List, Typography, Space, Divider, message, Spin } from 'antd';
3
+ import { SendOutlined, HistoryOutlined, SettingOutlined, ProjectOutlined, CodeOutlined, EyeOutlined } from '@ant-design/icons';
4
+ import axios from 'axios';
5
 
6
  const { Header, Content, Sider } = Layout;
7
  const { TextArea } = Input;
 
9
 
10
  export default function Home() {
11
  const [input, setInput] = useState('');
12
+ const [loading, setLoading] = useState(false);
13
+ const [generatedCode, setGeneratedCode] = useState('');
14
+ const [history, setHistory] = useState([
15
  '生成一个蓝色风格的登录页面',
16
  '创建一个电商首页轮播图',
17
  '设计一个响应式的个人主页',
18
  ]);
19
+ const [viewMode, setViewMode] = useState<'preview' | 'code'>('preview');
20
+
21
+ const handleGenerate = async () => {
22
+ if (!input.trim()) {
23
+ message.warning('请输入您的描述内容');
24
+ return;
25
+ }
26
+
27
+ setLoading(true);
28
+ try {
29
+ const response = await axios.post('/api/ai/generate', { prompt: input });
30
+ if (response.data.success) {
31
+ setGeneratedCode(response.data.data.code);
32
+ setHistory([input, ...history.slice(0, 9)]);
33
+ message.success('生成成功!');
34
+ } else {
35
+ message.error(response.data.error || '生成失败');
36
+ }
37
+ } catch (error) {
38
+ console.error('Generation failed:', error);
39
+ message.error('请求失败,请检查后端服务是否正常运行');
40
+ } finally {
41
+ setLoading(false);
42
+ }
43
+ };
44
 
45
  return (
46
  <Layout style={{ minHeight: '100vh' }}>
47
  <Header style={{ background: '#fff', padding: '0 24px', display: 'flex', alignItems: 'center', borderBottom: '1px solid #f0f0f0' }}>
48
+ <Title level={4} style={{ margin: 0, color: '#1890ff' }}>生成式 UI Agent</Title>
49
  <div style={{ marginLeft: 'auto' }}>
50
  <Space size="large">
51
  <Button type="text" icon={<ProjectOutlined />}>项目管理</Button>
 
60
  <List
61
  dataSource={history}
62
  renderItem={(item) => (
63
+ <List.Item
64
+ style={{ cursor: 'pointer', padding: '8px 0' }}
65
+ onClick={() => setInput(item)}
66
+ >
67
  <Text ellipsis>{item}</Text>
68
  </List.Item>
69
  )}
 
72
  </Sider>
73
  <Content style={{ padding: '24px', display: 'flex', gap: '24px' }}>
74
  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '16px' }}>
75
+ <Card title="AI 对话输入" variant="borderless" style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
76
  <TextArea
77
  rows={4}
78
  value={input}
79
  onChange={(e) => setInput(e.target.value)}
80
+ placeholder="描述你想要的 UI 界面,例如:'生成一个精美的博客主页'..."
81
  style={{ marginBottom: '16px' }}
82
+ disabled={loading}
83
  />
84
  <div style={{ textAlign: 'right' }}>
85
+ <Button
86
+ type="primary"
87
+ icon={<SendOutlined />}
88
+ size="large"
89
+ onClick={handleGenerate}
90
+ loading={loading}
91
+ >
92
+ {loading ? '正在生成...' : '开始生成'}
93
  </Button>
94
  </div>
95
  </Card>
96
 
97
+ <Card title="系统状态" variant="borderless" style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
98
  <Space direction="vertical" style={{ width: '100%' }}>
99
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
100
  <Text>API 状态</Text>
101
+ <Text type="success">已连接 (SiliconFlow)</Text>
102
  </div>
103
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
104
+ <Text>当前模型</Text>
105
+ <Text>DeepSeek-V3</Text>
106
  </div>
107
  </Space>
108
  </Card>
 
111
  <div style={{ flex: 2 }}>
112
  <Card
113
  title="实时预览"
114
+ extra={
115
+ <Space>
116
+ <Button
117
+ size="small"
118
+ type={viewMode === 'preview' ? 'primary' : 'default'}
119
+ icon={<EyeOutlined />}
120
+ onClick={() => setViewMode('preview')}
121
+ >
122
+ 预览
123
+ </Button>
124
+ <Button
125
+ size="small"
126
+ type={viewMode === 'code' ? 'primary' : 'default'}
127
+ icon={<CodeOutlined />}
128
+ onClick={() => setViewMode('code')}
129
+ >
130
+ 代码
131
+ </Button>
132
+ </Space>
133
+ }
134
+ style={{ height: '100%', minHeight: '600px', boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}
135
+ styles={{ body: { height: 'calc(100% - 58px)', padding: 0, overflow: 'auto', background: '#f5f5f5' } }}
136
  >
137
+ {loading ? (
138
+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
139
+ <Space direction="vertical" align="center">
140
+ <Spin size="large" />
141
+ <Text type="secondary">AI 正在为您精心设计界面...</Text>
142
+ </Space>
143
+ </div>
144
+ ) : generatedCode ? (
145
+ viewMode === 'preview' ? (
146
+ <div style={{ padding: '24px', height: '100%', width: '100%' }}>
147
+ <div style={{ background: '#fff', padding: '24px', borderRadius: '8px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', minHeight: '100%' }}>
148
+ {/* 简单起见,这里显示生成的代码说明,真实预览通常需要 react-live 或类似组件 */}
149
+ <Title level={4}>预览说明</Title>
150
+ <Text style={{ display: 'block', marginBottom: 16 }}>
151
+ AI 已为您生成了完整的 React + Tailwind 代码。
152
+ </Text>
153
+ <Divider />
154
+ <div style={{ background: '#fafafa', padding: '16px', borderRadius: '4px', border: '1px solid #eee' }}>
155
+ <Text type="secondary">
156
+ 由于环境限制,当前预览仅支持静态渲染提示。您可以点击右上角“代码”查看并复制生成的完整源代码。
157
+ </Text>
158
+ </div>
159
+ </div>
160
+ </div>
161
+ ) : (
162
+ <pre style={{ margin: 0, padding: '24px', background: '#1e1e1e', color: '#d4d4d4', overflow: 'auto', height: '100%' }}>
163
+ <code>{generatedCode}</code>
164
+ </pre>
165
+ )
166
+ ) : (
167
+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
168
+ <Text type="secondary">生成的 UI 将在这里实时显示</Text>
169
+ </div>
170
+ )}
171
  </Card>
172
  </div>
173
  </Content>
vite.config.ts CHANGED
@@ -6,22 +6,16 @@ import { traeBadgePlugin } from 'vite-plugin-trae-solo-badge';
6
  // https://vite.dev/config/
7
  export default defineConfig({
8
  plugins: [
9
- react({
10
- babel: {
11
- plugins: [
12
- 'react-dev-locator',
13
- ],
14
- },
15
- }),
16
- traeBadgePlugin({
17
- variant: 'dark',
18
- position: 'bottom-right',
19
- prodOnly: true,
20
- clickable: true,
21
- clickUrl: 'https://www.trae.ai/solo?showJoin=1',
22
- autoTheme: true,
23
- autoThemeTarget: '#root'
24
- }),
25
  tsconfigPaths(),
26
  ],
27
  server: {
 
6
  // https://vite.dev/config/
7
  export default defineConfig({
8
  plugins: [
9
+ react(),
10
+ // traeBadgePlugin({
11
+ // variant: 'dark',
12
+ // position: 'bottom-right',
13
+ // prodOnly: true,
14
+ // clickable: true,
15
+ // clickUrl: 'https://www.trae.ai/solo?showJoin=1',
16
+ // autoTheme: true,
17
+ // autoThemeTarget: '#root'
18
+ // }),
 
 
 
 
 
 
19
  tsconfigPaths(),
20
  ],
21
  server: {