mirror of
https://github.com/QwenLM/qwen-code.git
synced 2026-01-17 14:29:13 +00:00
Compare commits
3 Commits
feat/add-u
...
feat/suppo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7475ffcbeb | ||
|
|
ccd51a6a00 | ||
|
|
a7e14255c3 |
@@ -26,6 +26,7 @@ export default tseslint.config(
|
||||
'dist/**',
|
||||
'docs-site/.next/**',
|
||||
'docs-site/out/**',
|
||||
'packages/cli/src/services/insight-page/**',
|
||||
],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
|
||||
@@ -125,7 +125,7 @@
|
||||
"lint-staged": {
|
||||
"*.{js,jsx,ts,tsx}": [
|
||||
"prettier --write",
|
||||
"eslint --fix --max-warnings 0"
|
||||
"eslint --fix --max-warnings 0 --no-warn-ignored"
|
||||
],
|
||||
"*.{json,md}": [
|
||||
"prettier --write"
|
||||
|
||||
@@ -434,16 +434,6 @@ const SETTINGS_SCHEMA = {
|
||||
'Show welcome back dialog when returning to a project with conversation history.',
|
||||
showInDialog: true,
|
||||
},
|
||||
enableUserFeedback: {
|
||||
type: 'boolean',
|
||||
label: 'Enable User Feedback',
|
||||
category: 'UI',
|
||||
requiresRestart: false,
|
||||
default: true,
|
||||
description:
|
||||
'Show optional feedback dialog after conversations to help improve Qwen performance.',
|
||||
showInDialog: true,
|
||||
},
|
||||
accessibility: {
|
||||
type: 'object',
|
||||
label: 'Accessibility',
|
||||
|
||||
@@ -289,12 +289,6 @@ export default {
|
||||
'Show Citations': 'Quellenangaben anzeigen',
|
||||
'Custom Witty Phrases': 'Benutzerdefinierte Witzige Sprüche',
|
||||
'Enable Welcome Back': 'Willkommen-zurück aktivieren',
|
||||
'Enable User Feedback': 'Benutzerfeedback aktivieren',
|
||||
'How is Qwen doing this session? (optional)':
|
||||
'Wie macht sich Qwen in dieser Sitzung? (optional)',
|
||||
Bad: 'Schlecht',
|
||||
Good: 'Gut',
|
||||
'Not Sure Yet': 'Noch nicht sicher',
|
||||
'Disable Loading Phrases': 'Ladesprüche deaktivieren',
|
||||
'Screen Reader Mode': 'Bildschirmleser-Modus',
|
||||
'IDE Mode': 'IDE-Modus',
|
||||
|
||||
@@ -286,12 +286,6 @@ export default {
|
||||
'Show Citations': 'Show Citations',
|
||||
'Custom Witty Phrases': 'Custom Witty Phrases',
|
||||
'Enable Welcome Back': 'Enable Welcome Back',
|
||||
'Enable User Feedback': 'Enable User Feedback',
|
||||
'How is Qwen doing this session? (optional)':
|
||||
'How is Qwen doing this session? (optional)',
|
||||
Bad: 'Bad',
|
||||
Good: 'Good',
|
||||
'Not Sure Yet': 'Not Sure Yet',
|
||||
'Disable Loading Phrases': 'Disable Loading Phrases',
|
||||
'Screen Reader Mode': 'Screen Reader Mode',
|
||||
'IDE Mode': 'IDE Mode',
|
||||
|
||||
@@ -289,12 +289,6 @@ export default {
|
||||
'Show Citations': 'Показывать цитаты',
|
||||
'Custom Witty Phrases': 'Пользовательские остроумные фразы',
|
||||
'Enable Welcome Back': 'Включить приветствие при возврате',
|
||||
'Enable User Feedback': 'Включить отзывы пользователей',
|
||||
'How is Qwen doing this session? (optional)':
|
||||
'Как дела у Qwen в этой сессии? (необязательно)',
|
||||
Bad: 'Плохо',
|
||||
Good: 'Хорошо',
|
||||
'Not Sure Yet': 'Пока не уверен',
|
||||
'Disable Loading Phrases': 'Отключить фразы при загрузке',
|
||||
'Screen Reader Mode': 'Режим программы чтения с экрана',
|
||||
'IDE Mode': 'Режим IDE',
|
||||
|
||||
@@ -277,11 +277,6 @@ export default {
|
||||
'Show Citations': '显示引用',
|
||||
'Custom Witty Phrases': '自定义诙谐短语',
|
||||
'Enable Welcome Back': '启用欢迎回来',
|
||||
'Enable User Feedback': '启用用户反馈',
|
||||
'How is Qwen doing this session? (optional)': 'Qwen 这次表现如何?(可选)',
|
||||
Bad: '不满意',
|
||||
Good: '满意',
|
||||
'Not Sure Yet': '暂不评价',
|
||||
'Disable Loading Phrases': '禁用加载短语',
|
||||
'Screen Reader Mode': '屏幕阅读器模式',
|
||||
'IDE Mode': 'IDE 模式',
|
||||
|
||||
@@ -39,6 +39,7 @@ import { themeCommand } from '../ui/commands/themeCommand.js';
|
||||
import { toolsCommand } from '../ui/commands/toolsCommand.js';
|
||||
import { vimCommand } from '../ui/commands/vimCommand.js';
|
||||
import { setupGithubCommand } from '../ui/commands/setupGithubCommand.js';
|
||||
import { insightCommand } from '../ui/commands/insightCommand.js';
|
||||
|
||||
/**
|
||||
* Loads the core, hard-coded slash commands that are an integral part
|
||||
@@ -88,6 +89,7 @@ export class BuiltinCommandLoader implements ICommandLoader {
|
||||
vimCommand,
|
||||
setupGithubCommand,
|
||||
terminalSetupCommand,
|
||||
insightCommand,
|
||||
];
|
||||
|
||||
return allDefinitions.filter((cmd): cmd is SlashCommand => cmd !== null);
|
||||
|
||||
120
packages/cli/src/services/insight-page/README.md
Normal file
120
packages/cli/src/services/insight-page/README.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# Qwen Code Insights Page
|
||||
|
||||
A React-based visualization dashboard for displaying coding activity insights and statistics.
|
||||
|
||||
## Development
|
||||
|
||||
This application consists of two parts:
|
||||
|
||||
1. **Backend (Express Server)**: Serves API endpoints and processes chat history data
|
||||
2. **Frontend (Vite + React)**: Development server with HMR
|
||||
|
||||
### Running in Development Mode
|
||||
|
||||
You need to run both the backend and frontend servers:
|
||||
|
||||
**Terminal 1 - Backend Server (Port 3001):**
|
||||
|
||||
```bash
|
||||
pnpm dev:server
|
||||
```
|
||||
|
||||
**Terminal 2 - Frontend Dev Server (Port 3000):**
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Then open <http://localhost:3000> in your browser.
|
||||
|
||||
The Vite dev server will proxy `/api` requests to the backend server at port 3001.
|
||||
|
||||
### Building for Production
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
This compiles TypeScript and builds the React application. The output will be in the `dist/` directory.
|
||||
|
||||
In production, the Express server serves both the static files and API endpoints from a single port.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Frontend**: React + TypeScript + Vite + Chart.js
|
||||
- **Backend**: Express + Node.js
|
||||
- **Data Source**: JSONL chat history files from `~/.qwen/projects/*/chats/`
|
||||
|
||||
## Original Vite Template Info
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x';
|
||||
import reactDom from 'eslint-plugin-react-dom';
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
13
packages/cli/src/services/insight-page/index.html
Normal file
13
packages/cli/src/services/insight-page/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/qwen.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Qwen Code Insight</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
42
packages/cli/src/services/insight-page/package.json
Normal file
42
packages/cli/src/services/insight-page/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "insight-page",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:server": "BASE_DIR=$HOME/.qwen/projects PORT=3001 tsx ../insightServer.ts",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uiw/react-heat-map": "^2.3.3",
|
||||
"chart.js": "^4.5.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.5",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.46.4",
|
||||
"vite": "npm:rolldown-vite@7.2.5"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"vite": "npm:rolldown-vite@7.2.5"
|
||||
}
|
||||
}
|
||||
}
|
||||
1968
packages/cli/src/services/insight-page/pnpm-lock.yaml
generated
Normal file
1968
packages/cli/src/services/insight-page/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
6
packages/cli/src/services/insight-page/postcss.config.js
Normal file
6
packages/cli/src/services/insight-page/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
BIN
packages/cli/src/services/insight-page/public/qwen.png
Normal file
BIN
packages/cli/src/services/insight-page/public/qwen.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
395
packages/cli/src/services/insight-page/src/App.tsx
Normal file
395
packages/cli/src/services/insight-page/src/App.tsx
Normal file
@@ -0,0 +1,395 @@
|
||||
import { useEffect, useRef, useState, type CSSProperties } from 'react';
|
||||
import {
|
||||
Chart,
|
||||
LineController,
|
||||
LineElement,
|
||||
BarController,
|
||||
BarElement,
|
||||
CategoryScale,
|
||||
LinearScale,
|
||||
PointElement,
|
||||
Legend,
|
||||
Title,
|
||||
Tooltip,
|
||||
} from 'chart.js';
|
||||
import type { ChartConfiguration } from 'chart.js';
|
||||
import HeatMap from '@uiw/react-heat-map';
|
||||
import html2canvas from 'html2canvas';
|
||||
|
||||
// Register Chart.js components
|
||||
Chart.register(
|
||||
LineController,
|
||||
LineElement,
|
||||
BarController,
|
||||
BarElement,
|
||||
CategoryScale,
|
||||
LinearScale,
|
||||
PointElement,
|
||||
Legend,
|
||||
Title,
|
||||
Tooltip,
|
||||
);
|
||||
|
||||
interface UsageMetadata {
|
||||
input: number;
|
||||
output: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface InsightData {
|
||||
heatmap: { [date: string]: number };
|
||||
tokenUsage: { [date: string]: UsageMetadata };
|
||||
currentStreak: number;
|
||||
longestStreak: number;
|
||||
longestWorkDate: string | null;
|
||||
longestWorkDuration: number;
|
||||
activeHours: { [hour: number]: number };
|
||||
latestActiveTime: string | null;
|
||||
achievements: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [insights, setInsights] = useState<InsightData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const hourChartRef = useRef<HTMLCanvasElement>(null);
|
||||
const hourChartInstance = useRef<Chart | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Load insights data
|
||||
useEffect(() => {
|
||||
const loadInsights = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/insights');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch insights');
|
||||
}
|
||||
const data: InsightData = await response.json();
|
||||
setInsights(data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setInsights(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadInsights();
|
||||
}, []);
|
||||
|
||||
// Create hour chart when insights change
|
||||
useEffect(() => {
|
||||
if (!insights || !hourChartRef.current) return;
|
||||
|
||||
// Destroy existing chart if it exists
|
||||
if (hourChartInstance.current) {
|
||||
hourChartInstance.current.destroy();
|
||||
}
|
||||
|
||||
const labels = Array.from({ length: 24 }, (_, i) => `${i}:00`);
|
||||
const data = labels.map((_, i) => insights.activeHours[i] || 0);
|
||||
|
||||
const ctx = hourChartRef.current.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
hourChartInstance.current = new Chart(ctx, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Activity per Hour',
|
||||
data,
|
||||
backgroundColor: 'rgba(52, 152, 219, 0.7)',
|
||||
borderColor: 'rgba(52, 152, 219, 1)',
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
indexAxis: 'y',
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
},
|
||||
} as ChartConfiguration['options'],
|
||||
});
|
||||
}, [insights]);
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
try {
|
||||
const button = document.getElementById('export-btn') as HTMLButtonElement;
|
||||
button.style.display = 'none';
|
||||
|
||||
const canvas = await html2canvas(containerRef.current, {
|
||||
scale: 2,
|
||||
useCORS: true,
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const imgData = canvas.toDataURL('image/png');
|
||||
const link = document.createElement('a');
|
||||
link.href = imgData;
|
||||
link.download = `qwen-insights-${new Date().toISOString().slice(0, 10)}.png`;
|
||||
link.click();
|
||||
|
||||
button.style.display = 'block';
|
||||
} catch (err) {
|
||||
console.error('Error capturing image:', err);
|
||||
alert('Failed to export image. Please try again.');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-slate-50 via-white to-slate-100">
|
||||
<div className="glass-card px-8 py-6 text-center">
|
||||
<h2 className="text-xl font-semibold text-slate-900">
|
||||
Loading insights...
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-slate-600">
|
||||
Fetching your coding patterns
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !insights) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-slate-50 via-white to-slate-100">
|
||||
<div className="glass-card px-8 py-6 text-center">
|
||||
<h2 className="text-xl font-semibold text-rose-700">
|
||||
Error loading insights
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-slate-600">
|
||||
{error || 'Please try again later.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Prepare heatmap data for react-heat-map
|
||||
const heatmapData = Object.entries(insights.heatmap).map(([date, count]) => ({
|
||||
date,
|
||||
count,
|
||||
}));
|
||||
|
||||
const cardClass = 'glass-card p-6';
|
||||
const sectionTitleClass =
|
||||
'text-lg font-semibold tracking-tight text-slate-900';
|
||||
const captionClass = 'text-sm font-medium text-slate-500';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" ref={containerRef}>
|
||||
<div className="mx-auto max-w-6xl px-6 py-10 md:py-12">
|
||||
<header className="mb-8 space-y-3 text-center">
|
||||
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">
|
||||
Insights
|
||||
</p>
|
||||
<h1 className="text-3xl font-semibold text-slate-900 md:text-4xl">
|
||||
Qwen Code Insights
|
||||
</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
Your personalized coding journey and patterns
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3 md:gap-6">
|
||||
<div className={`${cardClass} h-full`}>
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<p className={captionClass}>Current Streak</p>
|
||||
<p className="mt-1 text-4xl font-bold text-slate-900">
|
||||
{insights.currentStreak}
|
||||
<span className="ml-2 text-base font-semibold text-slate-500">
|
||||
days
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<span className="rounded-full bg-emerald-50 px-4 py-2 text-sm font-semibold text-emerald-700">
|
||||
Longest {insights.longestStreak}d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${cardClass} h-full`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className={sectionTitleClass}>Active Hours</h3>
|
||||
<span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">
|
||||
24h
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-4 h-56 w-full">
|
||||
<canvas ref={hourChartRef}></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${cardClass} h-full space-y-3`}>
|
||||
<h3 className={sectionTitleClass}>Work Session</h3>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm text-slate-700">
|
||||
<div className="rounded-xl bg-slate-50 px-3 py-2">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Longest
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-semibold text-slate-900">
|
||||
{insights.longestWorkDuration}m
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-slate-50 px-3 py-2">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Date
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-semibold text-slate-900">
|
||||
{insights.longestWorkDate || '-'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="col-span-2 rounded-xl bg-slate-50 px-3 py-2">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Last Active
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-semibold text-slate-900">
|
||||
{insights.latestActiveTime || '-'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${cardClass} mt-4 space-y-4 md:mt-6`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className={sectionTitleClass}>Activity Heatmap</h3>
|
||||
<span className="text-xs font-semibold text-slate-500">
|
||||
Past year
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="min-w-[720px] rounded-xl border border-slate-100 bg-white/70 p-4 shadow-inner shadow-slate-100">
|
||||
<HeatMap
|
||||
value={heatmapData}
|
||||
width={1000}
|
||||
style={{ color: '#0f172a' } satisfies CSSProperties}
|
||||
startDate={
|
||||
new Date(new Date().setFullYear(new Date().getFullYear() - 1))
|
||||
}
|
||||
endDate={new Date()}
|
||||
rectSize={14}
|
||||
legendCellSize={12}
|
||||
rectProps={{
|
||||
rx: 2,
|
||||
}}
|
||||
panelColors={{
|
||||
0: '#e2e8f0',
|
||||
2: '#a5d8ff',
|
||||
4: '#74c0fc',
|
||||
10: '#339af0',
|
||||
20: '#1c7ed6',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${cardClass} mt-4 md:mt-6`}>
|
||||
<div className="space-y-3">
|
||||
<h3 className={sectionTitleClass}>Token Usage</h3>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="rounded-xl bg-slate-50 px-4 py-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Input
|
||||
</p>
|
||||
<p className="mt-1 text-2xl font-bold text-slate-900">
|
||||
{Object.values(insights.tokenUsage)
|
||||
.reduce((acc, usage) => acc + usage.input, 0)
|
||||
.toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-slate-50 px-4 py-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Output
|
||||
</p>
|
||||
<p className="mt-1 text-2xl font-bold text-slate-900">
|
||||
{Object.values(insights.tokenUsage)
|
||||
.reduce((acc, usage) => acc + usage.output, 0)
|
||||
.toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl bg-slate-50 px-4 py-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||
Total
|
||||
</p>
|
||||
<p className="mt-1 text-2xl font-bold text-slate-900">
|
||||
{Object.values(insights.tokenUsage)
|
||||
.reduce((acc, usage) => acc + usage.total, 0)
|
||||
.toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${cardClass} mt-4 space-y-4 md:mt-6`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className={sectionTitleClass}>Achievements</h3>
|
||||
<span className="text-xs font-semibold text-slate-500">
|
||||
{insights.achievements.length} total
|
||||
</span>
|
||||
</div>
|
||||
{insights.achievements.length === 0 ? (
|
||||
<p className="text-sm text-slate-600">
|
||||
No achievements yet. Keep coding!
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y divide-slate-200">
|
||||
{insights.achievements.map((achievement) => (
|
||||
<div
|
||||
key={achievement.id}
|
||||
className="flex flex-col gap-1 py-3 text-left"
|
||||
>
|
||||
<span className="text-base font-semibold text-slate-900">
|
||||
{achievement.name}
|
||||
</span>
|
||||
<p className="text-sm text-slate-600">
|
||||
{achievement.description}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-center">
|
||||
<button
|
||||
id="export-btn"
|
||||
className="group inline-flex items-center gap-2 rounded-full bg-slate-900 px-5 py-3 text-sm font-semibold text-white shadow-soft transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-400 hover:-translate-y-[1px] hover:shadow-lg active:translate-y-[1px]"
|
||||
onClick={handleExport}
|
||||
>
|
||||
Export as Image
|
||||
<span className="text-slate-200 transition group-hover:translate-x-0.5">
|
||||
→
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
15
packages/cli/src/services/insight-page/src/index.css
Normal file
15
packages/cli/src/services/insight-page/src/index.css
Normal file
@@ -0,0 +1,15 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 text-slate-900 antialiased;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.glass-card {
|
||||
@apply rounded-2xl border border-slate-200 bg-white/80 shadow-soft backdrop-blur;
|
||||
}
|
||||
}
|
||||
10
packages/cli/src/services/insight-page/src/main.tsx
Normal file
10
packages/cli/src/services/insight-page/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App.tsx';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
18
packages/cli/src/services/insight-page/tailwind.config.ts
Normal file
18
packages/cli/src/services/insight-page/tailwind.config.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
const config: Config = {
|
||||
content: ['./index.html', './src/**/*.{ts,tsx}'],
|
||||
theme: {
|
||||
extend: {
|
||||
boxShadow: {
|
||||
soft: '0 10px 40px rgba(15, 23, 42, 0.08)',
|
||||
},
|
||||
borderRadius: {
|
||||
xl: '1.25rem',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
28
packages/cli/src/services/insight-page/tsconfig.app.json
Normal file
28
packages/cli/src/services/insight-page/tsconfig.app.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
packages/cli/src/services/insight-page/tsconfig.json
Normal file
7
packages/cli/src/services/insight-page/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
packages/cli/src/services/insight-page/tsconfig.node.json
Normal file
26
packages/cli/src/services/insight-page/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
31210
packages/cli/src/services/insight-page/views/assets/index-D7obW1Jn.js
Normal file
31210
packages/cli/src/services/insight-page/views/assets/index-D7obW1Jn.js
Normal file
File diff suppressed because one or more lines are too long
14
packages/cli/src/services/insight-page/views/index.html
Normal file
14
packages/cli/src/services/insight-page/views/index.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/qwen.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>insight-page</title>
|
||||
<script type="module" crossorigin src="/assets/index-D7obW1Jn.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CV6J1oXz.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
BIN
packages/cli/src/services/insight-page/views/qwen.png
Normal file
BIN
packages/cli/src/services/insight-page/views/qwen.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
19
packages/cli/src/services/insight-page/vite.config.ts
Normal file
19
packages/cli/src/services/insight-page/vite.config.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: 'views',
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
404
packages/cli/src/services/insightServer.ts
Normal file
404
packages/cli/src/services/insightServer.ts
Normal file
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Qwen Code
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import express from 'express';
|
||||
import fs from 'fs/promises';
|
||||
import path, { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import type { ChatRecord } from '@qwen-code/qwen-code-core';
|
||||
import { read } from '@qwen-code/qwen-code-core/src/utils/jsonl-utils.js';
|
||||
|
||||
interface StreakData {
|
||||
currentStreak: number;
|
||||
longestStreak: number;
|
||||
dates: string[];
|
||||
}
|
||||
|
||||
// For heat map data
|
||||
interface HeatMapData {
|
||||
[date: string]: number;
|
||||
}
|
||||
|
||||
// For token usage data
|
||||
interface TokenUsageData {
|
||||
[date: string]: {
|
||||
input: number;
|
||||
output: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
// For achievement data
|
||||
interface AchievementData {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
// For the final insight data
|
||||
interface InsightData {
|
||||
heatmap: HeatMapData;
|
||||
tokenUsage: TokenUsageData;
|
||||
currentStreak: number;
|
||||
longestStreak: number;
|
||||
longestWorkDate: string | null;
|
||||
longestWorkDuration: number; // in minutes
|
||||
activeHours: { [hour: number]: number };
|
||||
latestActiveTime: string | null;
|
||||
achievements: AchievementData[];
|
||||
}
|
||||
|
||||
function debugLog(message: string) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const logMessage = `[${timestamp}] ${message}\n`;
|
||||
console.log(logMessage);
|
||||
}
|
||||
|
||||
debugLog('Insight server starting...');
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env['PORT'];
|
||||
const BASE_DIR = process.env['BASE_DIR'];
|
||||
|
||||
if (!BASE_DIR) {
|
||||
debugLog('BASE_DIR environment variable is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Serve static assets from the views/assets directory
|
||||
app.use(
|
||||
'/assets',
|
||||
express.static(path.join(__dirname, 'insight-page', 'views', 'assets')),
|
||||
);
|
||||
|
||||
app.get('/', (_req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'insight-page', 'views', 'index.html'));
|
||||
});
|
||||
|
||||
// API endpoint to get insight data
|
||||
app.get('/api/insights', async (_req, res) => {
|
||||
try {
|
||||
debugLog('Received request for insights data');
|
||||
const insights = await generateInsights(BASE_DIR);
|
||||
res.json(insights);
|
||||
} catch (error) {
|
||||
debugLog(`Error generating insights: ${error}`);
|
||||
res.status(500).json({ error: 'Failed to generate insights' });
|
||||
}
|
||||
});
|
||||
|
||||
// Process chat files from all projects in the base directory and generate insights
|
||||
async function generateInsights(baseDir: string): Promise<InsightData> {
|
||||
// Initialize data structures
|
||||
const heatmap: HeatMapData = {};
|
||||
const tokenUsage: TokenUsageData = {};
|
||||
const activeHours: { [hour: number]: number } = {};
|
||||
const sessionStartTimes: { [sessionId: string]: Date } = {};
|
||||
const sessionEndTimes: { [sessionId: string]: Date } = {};
|
||||
|
||||
try {
|
||||
// Get all project directories in the base directory
|
||||
const projectDirs = await fs.readdir(baseDir);
|
||||
|
||||
// Process each project directory
|
||||
for (const projectDir of projectDirs) {
|
||||
const projectPath = path.join(baseDir, projectDir);
|
||||
const stats = await fs.stat(projectPath);
|
||||
|
||||
// Only process if it's a directory
|
||||
if (stats.isDirectory()) {
|
||||
const chatsDir = path.join(projectPath, 'chats');
|
||||
|
||||
let chatFiles: string[] = [];
|
||||
try {
|
||||
// Get all chat files in the chats directory
|
||||
const files = await fs.readdir(chatsDir);
|
||||
chatFiles = files.filter((file) => file.endsWith('.jsonl'));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
debugLog(
|
||||
`Error reading chats directory for project ${projectDir}: ${error}`,
|
||||
);
|
||||
}
|
||||
// Continue to next project if chats directory doesn't exist
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process each chat file in this project
|
||||
for (const file of chatFiles) {
|
||||
const filePath = path.join(chatsDir, file);
|
||||
const records = await read<ChatRecord>(filePath);
|
||||
|
||||
// Process each record
|
||||
for (const record of records) {
|
||||
const timestamp = new Date(record.timestamp);
|
||||
const dateKey = formatDate(timestamp);
|
||||
const hour = timestamp.getHours();
|
||||
|
||||
// Update heatmap (count of interactions per day)
|
||||
heatmap[dateKey] = (heatmap[dateKey] || 0) + 1;
|
||||
|
||||
// Update active hours
|
||||
activeHours[hour] = (activeHours[hour] || 0) + 1;
|
||||
|
||||
// Update token usage
|
||||
if (record.usageMetadata) {
|
||||
const usage = tokenUsage[dateKey] || {
|
||||
input: 0,
|
||||
output: 0,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
usage.input += record.usageMetadata.promptTokenCount || 0;
|
||||
usage.output += record.usageMetadata.candidatesTokenCount || 0;
|
||||
usage.total += record.usageMetadata.totalTokenCount || 0;
|
||||
|
||||
tokenUsage[dateKey] = usage;
|
||||
}
|
||||
|
||||
// Track session times
|
||||
if (!sessionStartTimes[record.sessionId]) {
|
||||
sessionStartTimes[record.sessionId] = timestamp;
|
||||
}
|
||||
sessionEndTimes[record.sessionId] = timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
// Base directory doesn't exist, return empty insights
|
||||
debugLog(`Base directory does not exist: ${baseDir}`);
|
||||
} else {
|
||||
debugLog(`Error reading base directory: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate streak data
|
||||
const streakData = calculateStreaks(Object.keys(heatmap));
|
||||
|
||||
// Calculate longest work session
|
||||
let longestWorkDuration = 0;
|
||||
let longestWorkDate: string | null = null;
|
||||
for (const sessionId in sessionStartTimes) {
|
||||
const start = sessionStartTimes[sessionId];
|
||||
const end = sessionEndTimes[sessionId];
|
||||
const durationMinutes = Math.round(
|
||||
(end.getTime() - start.getTime()) / (1000 * 60),
|
||||
);
|
||||
|
||||
if (durationMinutes > longestWorkDuration) {
|
||||
longestWorkDuration = durationMinutes;
|
||||
longestWorkDate = formatDate(start);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate latest active time
|
||||
let latestActiveTime: string | null = null;
|
||||
let latestTimestamp = new Date(0);
|
||||
for (const dateStr in heatmap) {
|
||||
const date = new Date(dateStr);
|
||||
if (date > latestTimestamp) {
|
||||
latestTimestamp = date;
|
||||
latestActiveTime = date.toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate achievements
|
||||
const achievements = calculateAchievements(activeHours, heatmap, tokenUsage);
|
||||
|
||||
return {
|
||||
heatmap,
|
||||
tokenUsage,
|
||||
currentStreak: streakData.currentStreak,
|
||||
longestStreak: streakData.longestStreak,
|
||||
longestWorkDate,
|
||||
longestWorkDuration,
|
||||
activeHours,
|
||||
latestActiveTime,
|
||||
achievements,
|
||||
};
|
||||
}
|
||||
|
||||
// Helper function to format date as YYYY-MM-DD
|
||||
function formatDate(date: Date): string {
|
||||
return date.toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
// Calculate streaks from activity dates
|
||||
function calculateStreaks(dates: string[]): StreakData {
|
||||
if (dates.length === 0) {
|
||||
return { currentStreak: 0, longestStreak: 0, dates: [] };
|
||||
}
|
||||
|
||||
// Convert string dates to Date objects and sort them
|
||||
const dateObjects = dates.map((dateStr) => new Date(dateStr));
|
||||
dateObjects.sort((a, b) => a.getTime() - b.getTime());
|
||||
|
||||
let currentStreak = 1;
|
||||
let maxStreak = 1;
|
||||
let currentDate = new Date(dateObjects[0]);
|
||||
currentDate.setHours(0, 0, 0, 0); // Normalize to start of day
|
||||
|
||||
for (let i = 1; i < dateObjects.length; i++) {
|
||||
const nextDate = new Date(dateObjects[i]);
|
||||
nextDate.setHours(0, 0, 0, 0); // Normalize to start of day
|
||||
|
||||
// Calculate difference in days
|
||||
const diffDays = Math.floor(
|
||||
(nextDate.getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24),
|
||||
);
|
||||
|
||||
if (diffDays === 1) {
|
||||
// Consecutive day
|
||||
currentStreak++;
|
||||
maxStreak = Math.max(maxStreak, currentStreak);
|
||||
} else if (diffDays > 1) {
|
||||
// Gap in streak
|
||||
currentStreak = 1;
|
||||
}
|
||||
// If diffDays === 0, same day, so streak continues
|
||||
|
||||
currentDate = nextDate;
|
||||
}
|
||||
|
||||
// Check if the streak is still ongoing (if last activity was yesterday or today)
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
if (
|
||||
currentDate.getTime() === today.getTime() ||
|
||||
currentDate.getTime() === yesterday.getTime()
|
||||
) {
|
||||
// The streak might still be active, so we don't reset it
|
||||
}
|
||||
|
||||
return {
|
||||
currentStreak,
|
||||
longestStreak: maxStreak,
|
||||
dates,
|
||||
};
|
||||
}
|
||||
|
||||
// Calculate achievements based on user behavior
|
||||
function calculateAchievements(
|
||||
activeHours: { [hour: number]: number },
|
||||
heatmap: HeatMapData,
|
||||
_tokenUsage: TokenUsageData,
|
||||
): AchievementData[] {
|
||||
const achievements: AchievementData[] = [];
|
||||
|
||||
// Total activities
|
||||
const totalActivities = Object.values(heatmap).reduce(
|
||||
(sum, count) => sum + count,
|
||||
0,
|
||||
);
|
||||
|
||||
// Total tokens used - commented out since it's not currently used
|
||||
// const totalTokens = Object.values(tokenUsage).reduce((sum, usage) => sum + usage.total, 0);
|
||||
|
||||
// Total sessions
|
||||
const totalSessions = Object.keys(heatmap).length;
|
||||
|
||||
// Calculate percentage of activity per hour
|
||||
const totalHourlyActivity = Object.values(activeHours).reduce(
|
||||
(sum, count) => sum + count,
|
||||
0,
|
||||
);
|
||||
if (totalHourlyActivity > 0) {
|
||||
// Midnight debugger: 20% of sessions happen between 12AM-5AM
|
||||
const midnightActivity =
|
||||
(activeHours[0] || 0) +
|
||||
(activeHours[1] || 0) +
|
||||
(activeHours[2] || 0) +
|
||||
(activeHours[3] || 0) +
|
||||
(activeHours[4] || 0) +
|
||||
(activeHours[5] || 0);
|
||||
|
||||
if (midnightActivity / totalHourlyActivity >= 0.2) {
|
||||
achievements.push({
|
||||
id: 'midnight-debugger',
|
||||
name: 'Midnight Debugger',
|
||||
description: '20% of your sessions happen between 12AM-5AM',
|
||||
});
|
||||
}
|
||||
|
||||
// Morning coder: 20% of sessions happen between 6AM-9AM
|
||||
const morningActivity =
|
||||
(activeHours[6] || 0) +
|
||||
(activeHours[7] || 0) +
|
||||
(activeHours[8] || 0) +
|
||||
(activeHours[9] || 0);
|
||||
|
||||
if (morningActivity / totalHourlyActivity >= 0.2) {
|
||||
achievements.push({
|
||||
id: 'morning-coder',
|
||||
name: 'Morning Coder',
|
||||
description: '20% of your sessions happen between 6AM-9AM',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Patient king: average conversation length >= 10 exchanges
|
||||
if (totalSessions > 0) {
|
||||
const avgExchanges = totalActivities / totalSessions;
|
||||
if (avgExchanges >= 10) {
|
||||
achievements.push({
|
||||
id: 'patient-king',
|
||||
name: 'Patient King',
|
||||
description: 'Your average conversation length is 10+ exchanges',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Quick finisher: 70% of sessions have <= 2 exchanges
|
||||
let quickSessions = 0;
|
||||
// Since we don't have per-session exchange counts easily available,
|
||||
// we'll estimate based on the distribution of activities
|
||||
if (totalSessions > 0) {
|
||||
// This is a simplified calculation - in a real implementation,
|
||||
// we'd need to count exchanges per session
|
||||
const avgPerSession = totalActivities / totalSessions;
|
||||
if (avgPerSession <= 2) {
|
||||
// Estimate based on low average
|
||||
quickSessions = Math.floor(totalSessions * 0.7);
|
||||
}
|
||||
|
||||
if (quickSessions / totalSessions >= 0.7) {
|
||||
achievements.push({
|
||||
id: 'quick-finisher',
|
||||
name: 'Quick Finisher',
|
||||
description: '70% of your sessions end in 2 exchanges or fewer',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Explorer: for users with insufficient data or default
|
||||
if (achievements.length === 0) {
|
||||
achievements.push({
|
||||
id: 'explorer',
|
||||
name: 'Explorer',
|
||||
description: 'Getting started with Qwen Code',
|
||||
});
|
||||
}
|
||||
|
||||
return achievements;
|
||||
}
|
||||
|
||||
// Start the server
|
||||
app.listen(PORT, () => {
|
||||
debugLog(`Server running at http://localhost:${PORT}/`);
|
||||
debugLog(`Analyzing projects in: ${BASE_DIR}`);
|
||||
debugLog('Server is running. Press Ctrl+C to stop.');
|
||||
});
|
||||
@@ -45,7 +45,6 @@ import process from 'node:process';
|
||||
import { useHistory } from './hooks/useHistoryManager.js';
|
||||
import { useMemoryMonitor } from './hooks/useMemoryMonitor.js';
|
||||
import { useThemeCommand } from './hooks/useThemeCommand.js';
|
||||
import { useFeedbackDialog } from './hooks/useFeedbackDialog.js';
|
||||
import { useAuthCommand } from './auth/useAuth.js';
|
||||
import { useEditorSettings } from './hooks/useEditorSettings.js';
|
||||
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
|
||||
@@ -1197,20 +1196,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
isApprovalModeDialogOpen ||
|
||||
isResumeDialogOpen;
|
||||
|
||||
const {
|
||||
isFeedbackDialogOpen,
|
||||
openFeedbackDialog,
|
||||
closeFeedbackDialog,
|
||||
submitFeedback,
|
||||
} = useFeedbackDialog({
|
||||
config,
|
||||
settings,
|
||||
streamingState,
|
||||
history: historyManager.history,
|
||||
sessionStats,
|
||||
dialogsVisible,
|
||||
});
|
||||
|
||||
const pendingHistoryItems = useMemo(
|
||||
() => [...pendingSlashCommandHistoryItems, ...pendingGeminiHistoryItems],
|
||||
[pendingSlashCommandHistoryItems, pendingGeminiHistoryItems],
|
||||
@@ -1307,8 +1292,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
// Subagent dialogs
|
||||
isSubagentCreateDialogOpen,
|
||||
isAgentsManagerDialogOpen,
|
||||
// Feedback dialog
|
||||
isFeedbackDialogOpen,
|
||||
}),
|
||||
[
|
||||
isThemeDialogOpen,
|
||||
@@ -1399,8 +1382,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
// Subagent dialogs
|
||||
isSubagentCreateDialogOpen,
|
||||
isAgentsManagerDialogOpen,
|
||||
// Feedback dialog
|
||||
isFeedbackDialogOpen,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1441,10 +1422,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
openResumeDialog,
|
||||
closeResumeDialog,
|
||||
handleResume,
|
||||
// Feedback dialog
|
||||
openFeedbackDialog,
|
||||
closeFeedbackDialog,
|
||||
submitFeedback,
|
||||
}),
|
||||
[
|
||||
handleThemeSelect,
|
||||
@@ -1480,10 +1457,6 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
openResumeDialog,
|
||||
closeResumeDialog,
|
||||
handleResume,
|
||||
// Feedback dialog
|
||||
openFeedbackDialog,
|
||||
closeFeedbackDialog,
|
||||
submitFeedback,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import type React from 'react';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { useUIActions } from './contexts/UIActionsContext.js';
|
||||
import { useUIState } from './contexts/UIStateContext.js';
|
||||
import { useKeypress } from './hooks/useKeypress.js';
|
||||
|
||||
const FEEDBACK_OPTIONS = {
|
||||
GOOD: 1,
|
||||
BAD: 2,
|
||||
NOT_SURE: 3,
|
||||
} as const;
|
||||
|
||||
const FEEDBACK_OPTION_KEYS = {
|
||||
[FEEDBACK_OPTIONS.GOOD]: '1',
|
||||
[FEEDBACK_OPTIONS.BAD]: '2',
|
||||
[FEEDBACK_OPTIONS.NOT_SURE]: '3',
|
||||
} as const;
|
||||
|
||||
export const FEEDBACK_DIALOG_KEYS = ['1', '2', '3'] as const;
|
||||
|
||||
export const FeedbackDialog: React.FC = () => {
|
||||
const uiState = useUIState();
|
||||
const uiActions = useUIActions();
|
||||
|
||||
useKeypress(
|
||||
(key) => {
|
||||
if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.GOOD]) {
|
||||
uiActions.submitFeedback(FEEDBACK_OPTIONS.GOOD);
|
||||
} else if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.BAD]) {
|
||||
uiActions.submitFeedback(FEEDBACK_OPTIONS.BAD);
|
||||
} else if (key.name === FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.NOT_SURE]) {
|
||||
uiActions.submitFeedback(FEEDBACK_OPTIONS.NOT_SURE);
|
||||
}
|
||||
|
||||
uiActions.closeFeedbackDialog();
|
||||
},
|
||||
{ isActive: uiState.isFeedbackDialogOpen },
|
||||
);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginY={1}>
|
||||
<Box>
|
||||
<Text color="cyan">● </Text>
|
||||
<Text bold>{t('How is Qwen doing this session? (optional)')}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text color="cyan">
|
||||
{FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.GOOD]}:{' '}
|
||||
</Text>
|
||||
<Text>{t('Good')}</Text>
|
||||
<Text> </Text>
|
||||
<Text color="cyan">{FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.BAD]}: </Text>
|
||||
<Text>{t('Bad')}</Text>
|
||||
<Text> </Text>
|
||||
<Text color="cyan">
|
||||
{FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.NOT_SURE]}:{' '}
|
||||
</Text>
|
||||
<Text>{t('Not Sure Yet')}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
190
packages/cli/src/ui/commands/insightCommand.ts
Normal file
190
packages/cli/src/ui/commands/insightCommand.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Qwen Code
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import type { CommandContext, SlashCommand } from './types.js';
|
||||
import { CommandKind } from './types.js';
|
||||
import { MessageType } from '../types.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { spawn } from 'child_process';
|
||||
import { join } from 'path';
|
||||
import os from 'os';
|
||||
import { registerCleanup } from '../../utils/cleanup.js';
|
||||
import net from 'net';
|
||||
|
||||
// Track the insight server subprocess so we can terminate it on quit
|
||||
let insightServerProcess: import('child_process').ChildProcess | null = null;
|
||||
|
||||
// Find an available port starting from a default port
|
||||
async function findAvailablePort(startingPort: number = 3000): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let port = startingPort;
|
||||
|
||||
const checkPort = () => {
|
||||
const server = net.createServer();
|
||||
|
||||
server.listen(port, () => {
|
||||
server.once('close', () => {
|
||||
resolve(port);
|
||||
});
|
||||
server.close();
|
||||
});
|
||||
|
||||
server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
port++; // Try next port
|
||||
checkPort();
|
||||
} else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
checkPort();
|
||||
});
|
||||
}
|
||||
|
||||
export const insightCommand: SlashCommand = {
|
||||
name: 'insight',
|
||||
get description() {
|
||||
return t(
|
||||
'generate personalized programming insights from your chat history',
|
||||
);
|
||||
},
|
||||
kind: CommandKind.BUILT_IN,
|
||||
action: async (context: CommandContext) => {
|
||||
try {
|
||||
context.ui.setDebugMessage(t('Starting insight server...'));
|
||||
|
||||
// If there's an existing insight server process, terminate it first
|
||||
if (insightServerProcess && !insightServerProcess.killed) {
|
||||
insightServerProcess.kill();
|
||||
insightServerProcess = null;
|
||||
}
|
||||
|
||||
// Find an available port
|
||||
const availablePort = await findAvailablePort(3000);
|
||||
|
||||
const projectsDir = join(os.homedir(), '.qwen', 'projects');
|
||||
|
||||
// Path to the insight server script
|
||||
const insightScriptPath = join(
|
||||
process.cwd(),
|
||||
'packages',
|
||||
'cli',
|
||||
'src',
|
||||
'services',
|
||||
'insightServer.ts',
|
||||
);
|
||||
|
||||
// Spawn the insight server process
|
||||
const serverProcess = spawn('npx', ['tsx', insightScriptPath], {
|
||||
stdio: 'pipe',
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: 'production',
|
||||
BASE_DIR: projectsDir,
|
||||
PORT: String(availablePort),
|
||||
},
|
||||
});
|
||||
|
||||
// Store the server process for cleanup
|
||||
insightServerProcess = serverProcess;
|
||||
|
||||
// Register cleanup function to terminate the server process on quit
|
||||
registerCleanup(() => {
|
||||
if (insightServerProcess && !insightServerProcess.killed) {
|
||||
insightServerProcess.kill();
|
||||
insightServerProcess = null;
|
||||
}
|
||||
});
|
||||
|
||||
serverProcess.stderr.on('data', (data) => {
|
||||
// Forward error output to parent process stderr
|
||||
process.stderr.write(`Insight server error: ${data}`);
|
||||
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.ERROR,
|
||||
text: `Insight server error: ${data.toString()}`,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
});
|
||||
|
||||
serverProcess.on('close', (code) => {
|
||||
console.log(`Insight server process exited with code ${code}`);
|
||||
context.ui.setDebugMessage(t('Insight server stopped.'));
|
||||
// Reset the reference when the process closes
|
||||
if (insightServerProcess === serverProcess) {
|
||||
insightServerProcess = null;
|
||||
}
|
||||
});
|
||||
|
||||
const url = `http://localhost:${availablePort}`;
|
||||
|
||||
// Open browser automatically
|
||||
const openBrowser = async () => {
|
||||
try {
|
||||
const { exec } = await import('child_process');
|
||||
const { promisify } = await import('util');
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
switch (process.platform) {
|
||||
case 'darwin': // macOS
|
||||
await execAsync(`open ${url}`);
|
||||
break;
|
||||
case 'win32': // Windows
|
||||
await execAsync(`start ${url}`);
|
||||
break;
|
||||
default: // Linux and others
|
||||
await execAsync(`xdg-open ${url}`);
|
||||
}
|
||||
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: `Insight server started. Visit: ${url}`,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to open browser automatically:', err);
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: `Insight server started. Please visit: ${url}`,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Wait for the server to start (give it some time to bind to the port)
|
||||
setTimeout(openBrowser, 1000);
|
||||
|
||||
// Inform the user that the server is running
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.INFO,
|
||||
text: t(
|
||||
'Insight server started. Check your browser for the visualization.',
|
||||
),
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
} catch (error) {
|
||||
context.ui.addItem(
|
||||
{
|
||||
type: MessageType.ERROR,
|
||||
text: t('Failed to start insight server: {{error}}', {
|
||||
error: (error as Error).message,
|
||||
}),
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -26,7 +26,6 @@ import { useSettings } from '../contexts/SettingsContext.js';
|
||||
import { ApprovalMode } from '@qwen-code/qwen-code-core';
|
||||
import { StreamingState } from '../types.js';
|
||||
import { ConfigInitDisplay } from '../components/ConfigInitDisplay.js';
|
||||
import { FeedbackDialog } from '../FeedbackDialog.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export const Composer = () => {
|
||||
@@ -135,8 +134,6 @@ export const Composer = () => {
|
||||
</OverflowProvider>
|
||||
)}
|
||||
|
||||
{uiState.isFeedbackDialogOpen && <FeedbackDialog />}
|
||||
|
||||
{uiState.isInputActive && (
|
||||
<InputPrompt
|
||||
buffer={uiState.buffer}
|
||||
|
||||
@@ -33,9 +33,6 @@ vi.mock('../hooks/useCommandCompletion.js');
|
||||
vi.mock('../hooks/useInputHistory.js');
|
||||
vi.mock('../hooks/useReverseSearchCompletion.js');
|
||||
vi.mock('../utils/clipboardUtils.js');
|
||||
vi.mock('../contexts/UIStateContext.js', () => ({
|
||||
useUIState: vi.fn(() => ({ isFeedbackDialogOpen: false })),
|
||||
}));
|
||||
|
||||
const mockSlashCommands: SlashCommand[] = [
|
||||
{
|
||||
|
||||
@@ -36,8 +36,6 @@ import {
|
||||
import * as path from 'node:path';
|
||||
import { SCREEN_READER_USER_PREFIX } from '../textConstants.js';
|
||||
import { useShellFocusState } from '../contexts/ShellFocusContext.js';
|
||||
import { useUIState } from '../contexts/UIStateContext.js';
|
||||
import { FEEDBACK_DIALOG_KEYS } from '../FeedbackDialog.js';
|
||||
export interface InputPromptProps {
|
||||
buffer: TextBuffer;
|
||||
onSubmit: (value: string) => void;
|
||||
@@ -102,7 +100,6 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
|
||||
isEmbeddedShellFocused,
|
||||
}) => {
|
||||
const isShellFocused = useShellFocusState();
|
||||
const uiState = useUIState();
|
||||
const [justNavigatedHistory, setJustNavigatedHistory] = useState(false);
|
||||
const [escPressCount, setEscPressCount] = useState(0);
|
||||
const [showEscapePrompt, setShowEscapePrompt] = useState(false);
|
||||
@@ -329,14 +326,6 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
// Intercept feedback dialog option keys (1, 2, 3) when dialog is open
|
||||
if (
|
||||
uiState.isFeedbackDialogOpen &&
|
||||
(FEEDBACK_DIALOG_KEYS as readonly string[]).includes(key.name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset ESC count and hide prompt on any non-ESC key
|
||||
if (key.name !== 'escape') {
|
||||
if (escPressCount > 0 || showEscapePrompt) {
|
||||
@@ -681,7 +670,6 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
|
||||
recentPasteTime,
|
||||
commandSearchActive,
|
||||
commandSearchCompletion,
|
||||
uiState,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -66,10 +66,6 @@ export interface UIActions {
|
||||
openResumeDialog: () => void;
|
||||
closeResumeDialog: () => void;
|
||||
handleResume: (sessionId: string) => void;
|
||||
// Feedback dialog
|
||||
openFeedbackDialog: () => void;
|
||||
closeFeedbackDialog: () => void;
|
||||
submitFeedback: (rating: number) => void;
|
||||
}
|
||||
|
||||
export const UIActionsContext = createContext<UIActions | null>(null);
|
||||
|
||||
@@ -126,8 +126,6 @@ export interface UIState {
|
||||
// Subagent dialogs
|
||||
isSubagentCreateDialogOpen: boolean;
|
||||
isAgentsManagerDialogOpen: boolean;
|
||||
// Feedback dialog
|
||||
isFeedbackDialogOpen: boolean;
|
||||
}
|
||||
|
||||
export const UIStateContext = createContext<UIState | null>(null);
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import {
|
||||
type Config,
|
||||
logUserFeedback,
|
||||
UserFeedbackEvent,
|
||||
type UserFeedbackRating,
|
||||
Storage,
|
||||
isNodeError,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import { StreamingState, MessageType, type HistoryItem } from '../types.js';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
import type { SessionStatsState } from '../contexts/SessionContext.js';
|
||||
|
||||
const FEEDBACK_SHOW_PROBABILITY = 0.25; // 25% probability of showing feedback dialog
|
||||
const MIN_TOOL_CALLS = 10; // Minimum tool calls to show feedback dialog
|
||||
const MIN_USER_MESSAGES = 5; // Minimum user messages to show feedback dialog
|
||||
|
||||
// Fatigue mechanism constants
|
||||
const FEEDBACK_COOLDOWN_HOURS = 24; // Hours to wait before showing feedback dialog again
|
||||
const FEEDBACK_HISTORY_FILENAME = 'feedback-history.json';
|
||||
|
||||
/**
|
||||
* Check if there's an AI response after the last user message in the conversation history
|
||||
*/
|
||||
const hasAIResponseAfterLastUserMessage = (history: HistoryItem[]): boolean => {
|
||||
// Find the last user message
|
||||
let lastUserMessageIndex = -1;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
if (history[i].type === MessageType.USER) {
|
||||
lastUserMessageIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if there's any AI response (GEMINI message) after the last user message
|
||||
if (lastUserMessageIndex !== -1) {
|
||||
for (let i = lastUserMessageIndex + 1; i < history.length; i++) {
|
||||
if (history[i].type === MessageType.GEMINI) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Count the number of user messages in the conversation history
|
||||
*/
|
||||
const countUserMessages = (history: HistoryItem[]): number =>
|
||||
history.filter((item) => item.type === MessageType.USER).length;
|
||||
|
||||
/**
|
||||
* Interface for feedback history storage
|
||||
*/
|
||||
interface FeedbackHistory {
|
||||
lastShownTimestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the feedback history file path using global Storage
|
||||
*/
|
||||
function getFeedbackHistoryPath(): string {
|
||||
const globalQwenDir = Storage.getGlobalQwenDir();
|
||||
return path.join(globalQwenDir, FEEDBACK_HISTORY_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last feedback dialog show time from file storage
|
||||
*/
|
||||
const getFeedbackHistory = async (): Promise<FeedbackHistory | null> => {
|
||||
try {
|
||||
const filePath = getFeedbackHistoryPath();
|
||||
const content = await fs.readFile(filePath, 'utf-8');
|
||||
return JSON.parse(content) as FeedbackHistory;
|
||||
} catch (error) {
|
||||
if (isNodeError(error) && error.code === 'ENOENT') {
|
||||
// File doesn't exist yet, which is normal for first time
|
||||
return null;
|
||||
}
|
||||
console.warn('Failed to read feedback history from file:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Save feedback history to file storage
|
||||
*/
|
||||
const saveFeedbackHistory = async (history: FeedbackHistory): Promise<void> => {
|
||||
try {
|
||||
const filePath = getFeedbackHistoryPath();
|
||||
|
||||
// Ensure the directory exists
|
||||
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
||||
|
||||
// Write the history file
|
||||
await fs.writeFile(filePath, JSON.stringify(history, null, 2), 'utf-8');
|
||||
} catch (error) {
|
||||
console.warn('Failed to save feedback history to file:', error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if we should show the feedback dialog based on fatigue mechanism
|
||||
*/
|
||||
const shouldShowFeedbackBasedOnFatigue = async (): Promise<boolean> => {
|
||||
const history = await getFeedbackHistory();
|
||||
if (!history) return true; // No history, allow showing
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastShown = now - history.lastShownTimestamp;
|
||||
const cooldownMs = FEEDBACK_COOLDOWN_HOURS * 60 * 60 * 1000;
|
||||
|
||||
return timeSinceLastShown >= cooldownMs;
|
||||
};
|
||||
|
||||
export interface UseFeedbackDialogProps {
|
||||
config: Config;
|
||||
settings: LoadedSettings;
|
||||
streamingState: StreamingState;
|
||||
history: HistoryItem[];
|
||||
sessionStats: SessionStatsState;
|
||||
dialogsVisible: boolean;
|
||||
}
|
||||
|
||||
export const useFeedbackDialog = ({
|
||||
config,
|
||||
settings,
|
||||
streamingState,
|
||||
history,
|
||||
sessionStats,
|
||||
dialogsVisible,
|
||||
}: UseFeedbackDialogProps) => {
|
||||
// Feedback dialog state
|
||||
const [isFeedbackDialogOpen, setIsFeedbackDialogOpen] = useState(false);
|
||||
|
||||
const openFeedbackDialog = useCallback(() => {
|
||||
setIsFeedbackDialogOpen(true);
|
||||
|
||||
// Record the timestamp when feedback dialog is shown (fire and forget)
|
||||
saveFeedbackHistory({
|
||||
lastShownTimestamp: Date.now(),
|
||||
});
|
||||
}, []);
|
||||
|
||||
const closeFeedbackDialog = useCallback(
|
||||
() => setIsFeedbackDialogOpen(false),
|
||||
[],
|
||||
);
|
||||
|
||||
const submitFeedback = useCallback(
|
||||
(rating: number) => {
|
||||
// Calculate session duration and turn count
|
||||
const sessionDurationMs =
|
||||
Date.now() - sessionStats.sessionStartTime.getTime();
|
||||
let lastUserMessageIndex = -1;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
if (history[i].type === MessageType.USER) {
|
||||
lastUserMessageIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const turnCount =
|
||||
lastUserMessageIndex === -1 ? 0 : history.length - lastUserMessageIndex;
|
||||
|
||||
// Create and log the feedback event
|
||||
const feedbackEvent = new UserFeedbackEvent(
|
||||
sessionStats.sessionId,
|
||||
rating as UserFeedbackRating,
|
||||
sessionDurationMs,
|
||||
turnCount,
|
||||
config.getModel(),
|
||||
config.getApprovalMode(),
|
||||
);
|
||||
|
||||
logUserFeedback(config, feedbackEvent);
|
||||
closeFeedbackDialog();
|
||||
},
|
||||
[config, sessionStats, history, closeFeedbackDialog],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAndShowFeedback = async () => {
|
||||
if (streamingState === StreamingState.Idle && history.length > 0) {
|
||||
const hasAIResponseAfterLastUser =
|
||||
hasAIResponseAfterLastUserMessage(history);
|
||||
|
||||
// Get tool calls count and user messages count
|
||||
const toolCallsCount = sessionStats.metrics.tools.totalCalls;
|
||||
const userMessagesCount = countUserMessages(history);
|
||||
|
||||
// Check if the session meets the minimum requirements:
|
||||
// Either tool calls > 10 OR user messages > 5
|
||||
const meetsMinimumRequirements =
|
||||
toolCallsCount > MIN_TOOL_CALLS ||
|
||||
userMessagesCount > MIN_USER_MESSAGES;
|
||||
|
||||
// Check fatigue mechanism (async)
|
||||
let passedFatigueCheck = false;
|
||||
try {
|
||||
passedFatigueCheck = await shouldShowFeedbackBasedOnFatigue();
|
||||
} catch (error) {
|
||||
console.warn('Failed to check feedback fatigue:', error);
|
||||
}
|
||||
|
||||
// Show feedback dialog if:
|
||||
// 1. Qwen logger is enabled (required for feedback submission)
|
||||
// 2. User feedback is enabled in settings
|
||||
// 3. There's an AI response after the last user message (real AI conversation)
|
||||
// 4. No other dialogs are currently visible
|
||||
// 5. Random chance (25% probability)
|
||||
// 6. Meets minimum requirements (tool calls > 10 OR user messages > 5)
|
||||
// 7. Fatigue mechanism allows showing (not shown recently across sessions)
|
||||
if (
|
||||
config.getUsageStatisticsEnabled() &&
|
||||
settings.merged.ui?.enableUserFeedback !== false &&
|
||||
hasAIResponseAfterLastUser &&
|
||||
!dialogsVisible &&
|
||||
Math.random() < FEEDBACK_SHOW_PROBABILITY &&
|
||||
meetsMinimumRequirements &&
|
||||
passedFatigueCheck
|
||||
) {
|
||||
openFeedbackDialog();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkAndShowFeedback().catch((error) => {
|
||||
console.warn('Error in feedback check:', error);
|
||||
});
|
||||
}, [
|
||||
streamingState,
|
||||
history,
|
||||
sessionStats,
|
||||
isFeedbackDialogOpen,
|
||||
openFeedbackDialog,
|
||||
settings.merged.ui?.enableUserFeedback,
|
||||
config,
|
||||
dialogsVisible,
|
||||
]);
|
||||
|
||||
return {
|
||||
isFeedbackDialogOpen,
|
||||
openFeedbackDialog,
|
||||
closeFeedbackDialog,
|
||||
submitFeedback,
|
||||
};
|
||||
};
|
||||
@@ -35,7 +35,6 @@ export const EVENT_MODEL_SLASH_COMMAND = 'qwen-code.slash_command.model';
|
||||
export const EVENT_SUBAGENT_EXECUTION = 'qwen-code.subagent_execution';
|
||||
export const EVENT_SKILL_LAUNCH = 'qwen-code.skill_launch';
|
||||
export const EVENT_AUTH = 'qwen-code.auth';
|
||||
export const EVENT_USER_FEEDBACK = 'qwen-code.user_feedback';
|
||||
|
||||
// Performance Events
|
||||
export const EVENT_STARTUP_PERFORMANCE = 'qwen-code.startup.performance';
|
||||
|
||||
@@ -45,7 +45,6 @@ export {
|
||||
logNextSpeakerCheck,
|
||||
logAuth,
|
||||
logSkillLaunch,
|
||||
logUserFeedback,
|
||||
} from './loggers.js';
|
||||
export type { SlashCommandEvent, ChatCompressionEvent } from './types.js';
|
||||
export {
|
||||
@@ -66,8 +65,6 @@ export {
|
||||
NextSpeakerCheckEvent,
|
||||
AuthEvent,
|
||||
SkillLaunchEvent,
|
||||
UserFeedbackEvent,
|
||||
UserFeedbackRating,
|
||||
} from './types.js';
|
||||
export { makeSlashCommandEvent, makeChatCompressionEvent } from './types.js';
|
||||
export type { TelemetryEvent } from './types.js';
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
EVENT_INVALID_CHUNK,
|
||||
EVENT_AUTH,
|
||||
EVENT_SKILL_LAUNCH,
|
||||
EVENT_USER_FEEDBACK,
|
||||
} from './constants.js';
|
||||
import {
|
||||
recordApiErrorMetrics,
|
||||
@@ -87,7 +86,6 @@ import type {
|
||||
InvalidChunkEvent,
|
||||
AuthEvent,
|
||||
SkillLaunchEvent,
|
||||
UserFeedbackEvent,
|
||||
} from './types.js';
|
||||
import type { UiEvent } from './uiTelemetry.js';
|
||||
import { uiTelemetryService } from './uiTelemetry.js';
|
||||
@@ -889,32 +887,3 @@ export function logSkillLaunch(config: Config, event: SkillLaunchEvent): void {
|
||||
};
|
||||
logger.emit(logRecord);
|
||||
}
|
||||
|
||||
export function logUserFeedback(
|
||||
config: Config,
|
||||
event: UserFeedbackEvent,
|
||||
): void {
|
||||
const uiEvent = {
|
||||
...event,
|
||||
'event.name': EVENT_USER_FEEDBACK,
|
||||
'event.timestamp': new Date().toISOString(),
|
||||
} as UiEvent;
|
||||
uiTelemetryService.addEvent(uiEvent);
|
||||
config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
|
||||
QwenLogger.getInstance(config)?.logUserFeedbackEvent(event);
|
||||
if (!isTelemetrySdkInitialized()) return;
|
||||
|
||||
const attributes: LogAttributes = {
|
||||
...getCommonAttributes(config),
|
||||
...event,
|
||||
'event.name': EVENT_USER_FEEDBACK,
|
||||
'event.timestamp': new Date().toISOString(),
|
||||
};
|
||||
|
||||
const logger = logs.getLogger(SERVICE_NAME);
|
||||
const logRecord: LogRecord = {
|
||||
body: `User feedback: Rating ${event.rating} for session ${event.session_id}. Turn count: ${event.turn_count}. Duration: ${event.session_duration_ms}ms.`,
|
||||
attributes,
|
||||
};
|
||||
logger.emit(logRecord);
|
||||
}
|
||||
|
||||
@@ -39,7 +39,6 @@ import type {
|
||||
ExtensionDisableEvent,
|
||||
AuthEvent,
|
||||
SkillLaunchEvent,
|
||||
UserFeedbackEvent,
|
||||
RipgrepFallbackEvent,
|
||||
EndSessionEvent,
|
||||
} from '../types.js';
|
||||
@@ -843,23 +842,6 @@ export class QwenLogger {
|
||||
this.flushIfNeeded();
|
||||
}
|
||||
|
||||
logUserFeedbackEvent(event: UserFeedbackEvent): void {
|
||||
const rumEvent = this.createActionEvent('user', 'user_feedback', {
|
||||
properties: {
|
||||
session_id: event.session_id,
|
||||
rating: event.rating,
|
||||
session_duration_ms: event.session_duration_ms,
|
||||
turn_count: event.turn_count,
|
||||
model: event.model,
|
||||
approval_mode: event.approval_mode,
|
||||
prompt_id: event.prompt_id || '',
|
||||
},
|
||||
});
|
||||
|
||||
this.enqueueLogEvent(rumEvent);
|
||||
this.flushIfNeeded();
|
||||
}
|
||||
|
||||
logChatCompressionEvent(event: ChatCompressionEvent): void {
|
||||
const rumEvent = this.createActionEvent('misc', 'chat_compression', {
|
||||
properties: {
|
||||
|
||||
@@ -757,44 +757,6 @@ export class SkillLaunchEvent implements BaseTelemetryEvent {
|
||||
}
|
||||
}
|
||||
|
||||
export enum UserFeedbackRating {
|
||||
BAD = 1,
|
||||
FINE = 2,
|
||||
GOOD = 3,
|
||||
}
|
||||
|
||||
export class UserFeedbackEvent implements BaseTelemetryEvent {
|
||||
'event.name': 'user_feedback';
|
||||
'event.timestamp': string;
|
||||
session_id: string;
|
||||
rating: UserFeedbackRating;
|
||||
session_duration_ms: number;
|
||||
turn_count: number;
|
||||
model: string;
|
||||
approval_mode: string;
|
||||
prompt_id?: string;
|
||||
|
||||
constructor(
|
||||
session_id: string,
|
||||
rating: UserFeedbackRating,
|
||||
session_duration_ms: number,
|
||||
turn_count: number,
|
||||
model: string,
|
||||
approval_mode: string,
|
||||
prompt_id?: string,
|
||||
) {
|
||||
this['event.name'] = 'user_feedback';
|
||||
this['event.timestamp'] = new Date().toISOString();
|
||||
this.session_id = session_id;
|
||||
this.rating = rating;
|
||||
this.session_duration_ms = session_duration_ms;
|
||||
this.turn_count = turn_count;
|
||||
this.model = model;
|
||||
this.approval_mode = approval_mode;
|
||||
this.prompt_id = prompt_id;
|
||||
}
|
||||
}
|
||||
|
||||
export type TelemetryEvent =
|
||||
| StartSessionEvent
|
||||
| EndSessionEvent
|
||||
@@ -824,8 +786,7 @@ export type TelemetryEvent =
|
||||
| ToolOutputTruncatedEvent
|
||||
| ModelSlashCommandEvent
|
||||
| AuthEvent
|
||||
| SkillLaunchEvent
|
||||
| UserFeedbackEvent;
|
||||
| SkillLaunchEvent;
|
||||
|
||||
export class ExtensionDisableEvent implements BaseTelemetryEvent {
|
||||
'event.name': 'extension_disable';
|
||||
|
||||
Reference in New Issue
Block a user