feat: terminal sudo blocking, token tracking, mermaid & consumption UI
All checks were successful
Beta Release / beta (push) Successful in 1m3s
All checks were successful
Beta Release / beta (push) Successful in 1m3s
- Block sudo/doas commands when not running as root - Add real token counting from API responses - Track and display consumption by provider/day - Add Mermaid diagram rendering in Shell and Studio - Add copy-to-clipboard buttons for code blocks - Support tables in AI message rendering - Update system prompt with context (date, time, root status) 💘 Generated with Crush Assisted-by: MiniMax-M2.7 via Crush <crush@charm.land>
This commit is contained in:
@@ -3,6 +3,7 @@ package agent
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -14,6 +15,13 @@ type TerminalParams struct {
|
|||||||
Timeout int `json:"timeout,omitempty" description:"Timeout in seconds (default 60, max 300)"`
|
Timeout int `json:"timeout,omitempty" description:"Timeout in seconds (default 60, max 300)"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TerminalResponse struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
IsError bool `json:"is_error"`
|
||||||
|
SudoBlocked bool `json:"sudo_blocked,omitempty"`
|
||||||
|
Command string `json:"command,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
func NewTerminalTool() (*ToolDefinition, error) {
|
func NewTerminalTool() (*ToolDefinition, error) {
|
||||||
return NewTool("terminal",
|
return NewTool("terminal",
|
||||||
"Execute a shell command on the local system and return the output. Use for running builds, tests, git operations, package management, system info, or any CLI task. Commands run in the user's home directory by default. Long-running commands are auto-terminated.",
|
"Execute a shell command on the local system and return the output. Use for running builds, tests, git operations, package management, system info, or any CLI task. Commands run in the user's home directory by default. Long-running commands are auto-terminated.",
|
||||||
@@ -22,6 +30,18 @@ func NewTerminalTool() (*ToolDefinition, error) {
|
|||||||
return TextErrorResponse("command is required"), nil
|
return TextErrorResponse("command is required"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
trimmed := strings.TrimSpace(p.Command)
|
||||||
|
lower := strings.ToLower(trimmed)
|
||||||
|
if strings.HasPrefix(lower, "sudo ") || strings.HasPrefix(lower, "doas ") || strings.HasPrefix(lower, "run0 ") || strings.HasPrefix(lower, "pkexec ") {
|
||||||
|
return ToolResponse{
|
||||||
|
Content: fmt.Sprintf("BLOCKED: Command '%s' requires elevated privileges (%s). The current user is not root. Do NOT retry with sudo. Explain to the user that this command needs admin privileges and suggest an alternative, or tell them to run it manually in their terminal.", trimmed, strings.Fields(trimmed)[0]),
|
||||||
|
IsError: true,
|
||||||
|
Meta: map[string]string{"sudo_blocked": "true", "command": trimmed},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
timeout := time.Duration(p.Timeout) * time.Second
|
timeout := time.Duration(p.Timeout) * time.Second
|
||||||
if timeout == 0 {
|
if timeout == 0 {
|
||||||
timeout = 60 * time.Second
|
timeout = 60 * time.Second
|
||||||
|
|||||||
@@ -2,6 +2,16 @@ Tu es l'assistant IA de **Muyue Studio**, le centre de commandement de l'environ
|
|||||||
|
|
||||||
Tu es intégré dans Muyue, un gestionnaire d'environnement de développement de bureau. Ton rôle est d'aider l'utilisateur à configurer, gérer et optimiser son environnement dev.
|
Tu es intégré dans Muyue, un gestionnaire d'environnement de développement de bureau. Ton rôle est d'aider l'utilisateur à configurer, gérer et optimiser son environnement dev.
|
||||||
|
|
||||||
|
<critical_rules>
|
||||||
|
1. **AGIS, ne décris pas** — Si l'utilisateur demande de faire quelque chose, utilise les outils immédiatement. Ne dis pas "je pourrais faire X" — fais-le.
|
||||||
|
2. **SOIS AUTONOME** — Ne pose pas de questions si tu peux chercher, lire, déduire. Essaie plusieurs approches avant de bloquer. Ne t'arrête que pour les erreurs bloquantes réelles (credentials manquants, permissions, etc.).
|
||||||
|
3. **SOIS CONCIS** — Max 4 lignes par défaut. Pas de préambule ("Voici...", "Je vais..."), pas de postambule ("N'hésitez pas...", "J'espère que..."). Réponse directe. Un mot quand c'est suffisant.
|
||||||
|
4. **GÈRE LES ERREURS** — Si un outil échoue, essaie 2-3 approches alternatives avant de rapporter l'échec. Lis le message d'erreur complet, isole la cause racine.
|
||||||
|
5. **NE DEVINE PAS** — Lis les fichiers avant d'éditer. Utilise les outils pour obtenir les informations manquantes (lire, chercher, grep).
|
||||||
|
6. **CONFIDENTIALITÉ** — Ne révèle jamais les clés API, mots de passe, tokens ou informations sensibles.
|
||||||
|
7. **LANGUE** — Réponds dans la même langue que l'utilisateur.
|
||||||
|
</critical_rules>
|
||||||
|
|
||||||
## Environnement
|
## Environnement
|
||||||
|
|
||||||
Muyue gère :
|
Muyue gère :
|
||||||
@@ -13,32 +23,70 @@ Muyue gère :
|
|||||||
|
|
||||||
## Outils disponibles
|
## Outils disponibles
|
||||||
|
|
||||||
Tu as accès à des outils. Utilise-les concrètement, ne décris pas ce que tu ferais — fais-le.
|
| Outil | Usage |
|
||||||
|
|-------|-------|
|
||||||
|
| **terminal** | Exécuter des commandes shell (builds, tests, git, etc.) |
|
||||||
|
| **crush_run** | Déléguer une tâche complexe à Crush (édition de fichiers, refactoring, debug) — préfère cet outil pour les tâches multi-fichiers ou l'écriture de code |
|
||||||
|
| **read_file** | Lire le contenu d'un fichier |
|
||||||
|
| **list_files** | Lister les fichiers d'un répertoire |
|
||||||
|
| **search_files** | Chercher des fichiers par motif (glob) |
|
||||||
|
| **grep_content** | Chercher du texte dans les fichiers |
|
||||||
|
| **get_config** | Lire la configuration Muyue |
|
||||||
|
| **set_provider** | Configurer un fournisseur IA |
|
||||||
|
| **manage_ssh** | Gérer les connexions SSH |
|
||||||
|
| **web_fetch** | Récupérer le contenu d'une URL |
|
||||||
|
|
||||||
- **terminal** : Exécuter des commandes shell (builds, tests, git, etc.)
|
<tool_strategy>
|
||||||
- **crush_run** : Déléguer une tâche complexe à l'agent Crush (édition de fichiers, refactoring, debug)
|
- **Recherche avant action** — Utilise `search_files`, `grep_content`, `read_file` avant de supposer quoi que ce soit sur l'état du système
|
||||||
- **read_file** : Lire le contenu d'un fichier
|
- **Délégation intelligente** — Pour les tâches complexes (refactoring, création de fichiers, debug multi-fichiers), utilise `crush_run` au lieu d'enchaîner des commandes terminal
|
||||||
- **list_files** : Lister les fichiers d'un répertoire
|
- **Parallélisme** — Lance plusieurs appels d'outils en parallèle quand les opérations sont indépendantes
|
||||||
- **search_files** : Chercher des fichiers par motif (glob)
|
- **Troncature** — Si un résultat d'outil dépasse 2000 caractères, résume les points clés au lieu de tout afficher
|
||||||
- **grep_content** : Chercher du texte dans le contenu des fichiers
|
- **Une chose à la fois** — Sauf si les opérations sont indépendantes, exécute séquentiellement
|
||||||
- **get_config** : Lire la configuration Muyue
|
</tool_strategy>
|
||||||
- **set_provider** : Configurer un fournisseur IA
|
|
||||||
- **manage_ssh** : Gérer les connexions SSH
|
|
||||||
- **web_fetch** : Récupérer le contenu d'une URL
|
|
||||||
|
|
||||||
## Règles
|
<decision_making>
|
||||||
|
- Décide par toi-même : cherche, lis, déduis, agis
|
||||||
|
- Ne demande confirmation que pour : actions destructrices (suppression, overwrite), plusieurs approches valides avec des trade-offs importants
|
||||||
|
- Si bloqué : documente (a) ce que tu as essayé, (b) pourquoi tu es bloqué, (c) l'action minimale requise
|
||||||
|
- Ne t'arrête jamais pour : tâche trop grosse (découpe), trop de fichiers (change-les), complexité (gère-la)
|
||||||
|
</decision_making>
|
||||||
|
|
||||||
1. **AGIS, ne décris pas** — Si l'utilisateur demande de faire quelque chose, utilise les outils pour le faire. Ne dis pas "je pourrais faire X" — fais-le.
|
<error_recovery>
|
||||||
2. **Sois concis** — Pas de préambule, pas de blabla. Réponse directe.
|
1. Lis le message d'erreur complet
|
||||||
3. **Une chose à la fois** — N'appelle pas plusieurs outils simultanément sauf si c'est nécessaire.
|
2. Comprends la cause racine
|
||||||
4. **Gère les erreurs** — Si un outil échoue, essaie une approche différente avant de le dire à l'utilisateur.
|
3. Essaie une approche différente (pas la même)
|
||||||
5. **Ne devine pas** — Si tu n'as pas assez d'informations, utilise les outils pour les obtenir (lire un fichier, chercher, etc.)
|
4. Cherche du code similaire qui fonctionne
|
||||||
6. **Confidentialité** — Ne révèle jamais les clés API, mots de passe ou informations sensibles dans tes réponses.
|
5. Applique un correctif ciblé
|
||||||
7. **Langue** — Réponds dans la même langue que l'utilisateur.
|
6. Vérifie que ça marche
|
||||||
|
7. Pour chaque erreur, essaie au moins 2-3 stratégies avant de conclure que c'est bloquant
|
||||||
|
</error_recovery>
|
||||||
|
|
||||||
## Format des réponses
|
## Format des réponses
|
||||||
|
|
||||||
- Code : utilise des blocs markdown
|
- **Code** : blocs markdown avec le langage spécifié
|
||||||
- Résultats d'outils : résume les points clés, ne colle pas des milliers de lignes
|
- **Résultats d'outils** : résume les points clés, max 2000 caractères, ne copie pas des milliers de lignes
|
||||||
- Erreurs : explique clairement et propose une solution
|
- **Erreurs** : explique clairement la cause et propose une solution concrète
|
||||||
- Succès : confirme brièvement ce qui a été fait
|
- **Succès** : confirme brièvement ce qui a été fait (1 ligne)
|
||||||
|
- **Multi-fichiers** : liste les fichiers modifiés avec `fichier:ligne` pour les références
|
||||||
|
|
||||||
|
## Diagrammes Mermaid
|
||||||
|
|
||||||
|
Tu peux utiliser des diagrammes Mermaid pour visualiser des architectures, flux, séquences, etc.
|
||||||
|
Utilise un bloc code avec le langage `mermaid` :
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[Début] --> B{Décision}
|
||||||
|
B -->|Oui| C[Action]
|
||||||
|
B -->|Non| D[Fin]
|
||||||
|
```
|
||||||
|
|
||||||
|
Types utiles :
|
||||||
|
- `graph TD/LR` — Architecture, flux de données
|
||||||
|
- `sequenceDiagram` — Interactions entre composants
|
||||||
|
- `flowchart` — Processus et décisions
|
||||||
|
- `classDiagram` — Structures de données
|
||||||
|
- `erDiagram` — Schémas de base de données
|
||||||
|
- `gantt` — Planning et timelines
|
||||||
|
|
||||||
|
Utilise Mermaid quand ça apporte de la clarté : architecture complexe, flux multi-étapes, relations entre entités. Ne l'utilise pas pour du texte simple.
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ type ChatEngine struct {
|
|||||||
tools json.RawMessage
|
tools json.RawMessage
|
||||||
onChunk func(map[string]interface{})
|
onChunk func(map[string]interface{})
|
||||||
stream bool
|
stream bool
|
||||||
|
TotalTokens int
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewChatEngine creates a new ChatEngine instance.
|
// NewChatEngine creates a new ChatEngine instance.
|
||||||
@@ -71,6 +72,10 @@ func (ce *ChatEngine) RunWithTools(ctx context.Context, messages []orchestrator.
|
|||||||
return finalContent, allToolCalls, allToolResults, err
|
return finalContent, allToolCalls, allToolResults, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if resp.Usage.TotalTokens > 0 {
|
||||||
|
ce.TotalTokens += resp.Usage.TotalTokens
|
||||||
|
}
|
||||||
|
|
||||||
choice := resp.Choices[0]
|
choice := resp.Choices[0]
|
||||||
content := cleanThinkingTags(choice.Message.Content)
|
content := cleanThinkingTags(choice.Message.Content)
|
||||||
|
|
||||||
@@ -123,6 +128,11 @@ func (ce *ChatEngine) RunWithTools(ctx context.Context, messages []orchestrator.
|
|||||||
"content": result.Content,
|
"content": result.Content,
|
||||||
"is_error": result.IsError,
|
"is_error": result.IsError,
|
||||||
}
|
}
|
||||||
|
if result.Meta != nil {
|
||||||
|
for k, v := range result.Meta {
|
||||||
|
resultData[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
allToolResults = append(allToolResults, map[string]interface{}{
|
allToolResults = append(allToolResults, map[string]interface{}{
|
||||||
"tool_call_id": tc.ID,
|
"tool_call_id": tc.ID,
|
||||||
"name": tc.Function.Name,
|
"name": tc.Function.Name,
|
||||||
@@ -149,6 +159,11 @@ func (ce *ChatEngine) RunWithTools(ctx context.Context, messages []orchestrator.
|
|||||||
return finalContent, allToolCalls, allToolResults, nil
|
return finalContent, allToolCalls, allToolResults, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProviderName returns the name of the active provider used by the engine.
|
||||||
|
func (ce *ChatEngine) ProviderName() string {
|
||||||
|
return ce.orchestrator.ProviderName()
|
||||||
|
}
|
||||||
|
|
||||||
// RunNonStream executes chat without streaming content to client.
|
// RunNonStream executes chat without streaming content to client.
|
||||||
func (ce *ChatEngine) RunNonStream(ctx context.Context, messages []orchestrator.Message) (string, error) {
|
func (ce *ChatEngine) RunNonStream(ctx context.Context, messages []orchestrator.Message) (string, error) {
|
||||||
var finalContent string
|
var finalContent string
|
||||||
@@ -159,6 +174,10 @@ func (ce *ChatEngine) RunNonStream(ctx context.Context, messages []orchestrator.
|
|||||||
return finalContent, err
|
return finalContent, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if resp.Usage.TotalTokens > 0 {
|
||||||
|
ce.TotalTokens += resp.Usage.TotalTokens
|
||||||
|
}
|
||||||
|
|
||||||
choice := resp.Choices[0]
|
choice := resp.Choices[0]
|
||||||
content := cleanThinkingTags(choice.Message.Content)
|
content := cleanThinkingTags(choice.Message.Content)
|
||||||
|
|
||||||
|
|||||||
127
internal/api/consumption.go
Normal file
127
internal/api/consumption.go
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/muyue/muyue/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type consumptionEntry struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Tokens int `json:"tokens"`
|
||||||
|
Requests int `json:"requests"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type providerConsumption struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Daily []consumptionEntry `json:"daily"`
|
||||||
|
Total int `json:"total_tokens"`
|
||||||
|
Requests int `json:"total_requests"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type consumptionStore struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
providers map[string]*providerConsumption
|
||||||
|
}
|
||||||
|
|
||||||
|
func newConsumptionStore() *consumptionStore {
|
||||||
|
cs := &consumptionStore{
|
||||||
|
providers: make(map[string]*providerConsumption),
|
||||||
|
}
|
||||||
|
cs.load()
|
||||||
|
cs.prune()
|
||||||
|
return cs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) Record(providerName string, tokens int) {
|
||||||
|
if tokens <= 0 || providerName == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
|
||||||
|
today := time.Now().UTC().Format("2006-01-02")
|
||||||
|
|
||||||
|
p, ok := cs.providers[providerName]
|
||||||
|
if !ok {
|
||||||
|
p = &providerConsumption{Name: providerName}
|
||||||
|
cs.providers[providerName] = p
|
||||||
|
}
|
||||||
|
|
||||||
|
p.Total += tokens
|
||||||
|
p.Requests++
|
||||||
|
|
||||||
|
if len(p.Daily) > 0 && p.Daily[len(p.Daily)-1].Date == today {
|
||||||
|
p.Daily[len(p.Daily)-1].Tokens += tokens
|
||||||
|
p.Daily[len(p.Daily)-1].Requests++
|
||||||
|
} else {
|
||||||
|
p.Daily = append(p.Daily, consumptionEntry{
|
||||||
|
Date: today,
|
||||||
|
Tokens: tokens,
|
||||||
|
Requests: 1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
cs.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) GetAll() map[string]*providerConsumption {
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
|
||||||
|
result := make(map[string]*providerConsumption)
|
||||||
|
for k, v := range cs.providers {
|
||||||
|
pc := *v
|
||||||
|
daily := make([]consumptionEntry, len(v.Daily))
|
||||||
|
copy(daily, v.Daily)
|
||||||
|
pc.Daily = daily
|
||||||
|
result[k] = &pc
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) prune() {
|
||||||
|
cutoff := time.Now().UTC().AddDate(0, 0, -7).Format("2006-01-02")
|
||||||
|
for _, p := range cs.providers {
|
||||||
|
filtered := make([]consumptionEntry, 0)
|
||||||
|
for _, d := range p.Daily {
|
||||||
|
if d.Date >= cutoff {
|
||||||
|
filtered = append(filtered, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.Daily = filtered
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) filePath() string {
|
||||||
|
dir, err := config.ConfigDir()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, "consumption.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) load() {
|
||||||
|
fp := cs.filePath()
|
||||||
|
if fp == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(fp)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.Unmarshal(data, &cs.providers)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *consumptionStore) save() {
|
||||||
|
fp := cs.filePath()
|
||||||
|
if fp == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(cs.providers)
|
||||||
|
os.WriteFile(fp, data, 0644)
|
||||||
|
}
|
||||||
@@ -32,9 +32,10 @@ type Conversation struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ConversationStore struct {
|
type ConversationStore struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
path string
|
path string
|
||||||
conv *Conversation
|
conv *Conversation
|
||||||
|
realTokens int
|
||||||
}
|
}
|
||||||
|
|
||||||
type TokenCount struct {
|
type TokenCount struct {
|
||||||
@@ -133,6 +134,7 @@ func (cs *ConversationStore) Clear() {
|
|||||||
cs.conv.Summary = ""
|
cs.conv.Summary = ""
|
||||||
cs.conv.CreatedAt = time.Now().Format(time.RFC3339)
|
cs.conv.CreatedAt = time.Now().Format(time.RFC3339)
|
||||||
cs.conv.UpdatedAt = time.Now().Format(time.RFC3339)
|
cs.conv.UpdatedAt = time.Now().Format(time.RFC3339)
|
||||||
|
cs.realTokens = 0
|
||||||
cs.save()
|
cs.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,9 +156,22 @@ func (cs *ConversationStore) TrimOld(keepCount int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ConversationStore) ApproxTokenCount() int {
|
func (cs *ConversationStore) ApproxTokenCount() int {
|
||||||
|
if cs.realTokens > 0 {
|
||||||
|
return cs.realTokens
|
||||||
|
}
|
||||||
return cs.ApproxTokenCountDetailed().total
|
return cs.ApproxTokenCountDetailed().total
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AddRealTokens accumulates actual token counts from the API response.
|
||||||
|
func (cs *ConversationStore) AddRealTokens(tokens int) {
|
||||||
|
if tokens <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cs.mu.Lock()
|
||||||
|
cs.realTokens += tokens
|
||||||
|
cs.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
func (cs *ConversationStore) ApproxTokenCountDetailed() TokenCount {
|
func (cs *ConversationStore) ApproxTokenCountDetailed() TokenCount {
|
||||||
cs.mu.RLock()
|
cs.mu.RLock()
|
||||||
defer cs.mu.RUnlock()
|
defer cs.mu.RUnlock()
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ package api
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/muyue/muyue/internal/agent"
|
"github.com/muyue/muyue/internal/agent"
|
||||||
"github.com/muyue/muyue/internal/orchestrator"
|
"github.com/muyue/muyue/internal/orchestrator"
|
||||||
@@ -42,7 +45,14 @@ func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, err.Error(), http.StatusServiceUnavailable)
|
writeError(w, err.Error(), http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
orb.SetSystemPrompt(agent.StudioSystemPrompt())
|
var studioPrompt strings.Builder
|
||||||
|
studioPrompt.WriteString(agent.StudioSystemPrompt())
|
||||||
|
studioPrompt.WriteString(fmt.Sprintf("\nDate: %s\nHeure: %s\n", time.Now().Format("02/01/2006"), time.Now().Format("15:04:05")))
|
||||||
|
studioPrompt.WriteString(fmt.Sprintf("Root: %t\n", os.Geteuid() == 0))
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
studioPrompt.WriteString("⚠️ Session utilisateur standard — les commandes sudo/doas nécessitent une autorisation. N'utilise PAS sudo ou doas sans demander.\n")
|
||||||
|
}
|
||||||
|
orb.SetSystemPrompt(studioPrompt.String())
|
||||||
orb.SetTools(s.agentToolsJSON)
|
orb.SetTools(s.agentToolsJSON)
|
||||||
|
|
||||||
if body.Stream {
|
if body.Stream {
|
||||||
@@ -91,6 +101,9 @@ func (s *Server) handleStreamChat(w http.ResponseWriter, orb *orchestrator.Orche
|
|||||||
storeContent = string(storeJSON)
|
storeContent = string(storeJSON)
|
||||||
}
|
}
|
||||||
s.convStore.Add("assistant", storeContent)
|
s.convStore.Add("assistant", storeContent)
|
||||||
|
s.convStore.AddRealTokens(engine.TotalTokens)
|
||||||
|
|
||||||
|
s.consumption.Record(engine.ProviderName(), engine.TotalTokens)
|
||||||
|
|
||||||
sseWriter.Write(map[string]interface{}{"done": "true"})
|
sseWriter.Write(map[string]interface{}{"done": "true"})
|
||||||
}
|
}
|
||||||
@@ -107,6 +120,10 @@ func (s *Server) handleNonStreamChat(w http.ResponseWriter, orb *orchestrator.Or
|
|||||||
}
|
}
|
||||||
|
|
||||||
s.convStore.Add("assistant", finalContent)
|
s.convStore.Add("assistant", finalContent)
|
||||||
|
s.convStore.AddRealTokens(engine.TotalTokens)
|
||||||
|
|
||||||
|
s.consumption.Record(engine.ProviderName(), engine.TotalTokens)
|
||||||
|
|
||||||
writeJSON(w, map[string]string{"content": finalContent})
|
writeJSON(w, map[string]string{"content": finalContent})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,21 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
const summarizePrompt = `Résume la conversation suivante de manière concise et structurée. Garde les points clés, les décisions prises, le contexte technique important. Le résumé doit permettre de continuer la conversation sans perte de contexte. Réponds uniquement avec le résumé, sans meta-commentaire.`
|
const summarizePrompt = `Résume cette conversation de manière ultra-concise et structurée.
|
||||||
|
|
||||||
|
CONSERVE :
|
||||||
|
- Les décisions techniques prises et leur rationale
|
||||||
|
- Les configurations modifiées (noms exacts, valeurs)
|
||||||
|
- Les fichiers/chemins manipulés
|
||||||
|
- Les erreurs rencontrées et leurs résolutions
|
||||||
|
- Le contexte nécessaire pour continuer
|
||||||
|
|
||||||
|
ÉLIMINE :
|
||||||
|
- Les échanges de politesse
|
||||||
|
- Les tentatives infructueuses (sauf si la solution n'a pas été trouvée)
|
||||||
|
- Les sorties d'outils brutes (garde seulement les conclusions)
|
||||||
|
|
||||||
|
FORMAT : Markdown structuré avec sections. Max 500 mots. Pas de méta-commentaire.`
|
||||||
|
|
||||||
func writeJSON(w http.ResponseWriter, data interface{}) {
|
func writeJSON(w http.ResponseWriter, data interface{}) {
|
||||||
json.NewEncoder(w).Encode(data)
|
json.NewEncoder(w).Encode(data)
|
||||||
|
|||||||
@@ -534,6 +534,39 @@ func (s *Server) handleProvidersQuota(w http.ResponseWriter, r *http.Request) {
|
|||||||
q.Healthy = p.APIKey != ""
|
q.Healthy = p.APIKey != ""
|
||||||
if p.APIKey == "" {
|
if p.APIKey == "" {
|
||||||
q.Error = "no API key"
|
q.Error = "no API key"
|
||||||
|
results = append(results, q)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
mimoBase := p.BaseURL
|
||||||
|
if mimoBase == "" {
|
||||||
|
mimoBase = "https://token-plan-ams.xiaomimimo.com/v1"
|
||||||
|
}
|
||||||
|
req, _ := http.NewRequest("GET", strings.TrimRight(mimoBase, "/")+"/models", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+p.APIKey)
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
q.Error = err.Error()
|
||||||
|
} else {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
var data map[string]interface{}
|
||||||
|
if json.Unmarshal(body, &data) == nil {
|
||||||
|
if modelList, ok := data["data"].([]interface{}); ok {
|
||||||
|
models := make([]map[string]interface{}, 0)
|
||||||
|
for _, m := range modelList {
|
||||||
|
if mm, ok := m.(map[string]interface{}); ok {
|
||||||
|
id, _ := mm["id"].(string)
|
||||||
|
if id != "" {
|
||||||
|
models = append(models, map[string]interface{}{
|
||||||
|
"model": id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q.Data = map[string]interface{}{"models": models, "available": len(models)}
|
||||||
|
q.Healthy = true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case "claude", "anthropic":
|
case "claude", "anthropic":
|
||||||
// Claude Code n'a pas d'API externe, vérifier l'installation
|
// Claude Code n'a pas d'API externe, vérifier l'installation
|
||||||
@@ -551,6 +584,15 @@ func (s *Server) handleProvidersQuota(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, map[string]interface{}{"providers": results})
|
writeJSON(w, map[string]interface{}{"providers": results})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleProvidersConsumption(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != "GET" {
|
||||||
|
writeError(w, "GET only", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data := s.consumption.GetAll()
|
||||||
|
writeJSON(w, map[string]interface{}{"providers": data})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleRecentCommands(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleRecentCommands(w http.ResponseWriter, r *http.Request) {
|
||||||
home, _ := os.UserHomeDir()
|
home, _ := os.UserHomeDir()
|
||||||
type cmdEntry struct {
|
type cmdEntry struct {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/muyue/muyue/internal/agent"
|
"github.com/muyue/muyue/internal/agent"
|
||||||
"github.com/muyue/muyue/internal/orchestrator"
|
"github.com/muyue/muyue/internal/orchestrator"
|
||||||
@@ -62,35 +63,36 @@ func (s *Server) handleShellChat(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) buildShellSystemPrompt(_ ShellChatRequest) string {
|
func (s *Server) buildShellSystemPrompt(req ShellChatRequest) string {
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
|
|
||||||
sb.WriteString(`Tu es l'Analyste Système de Muyue. Tu es un expert en administration système et développement.
|
sb.WriteString(shellSystemPromptBase)
|
||||||
Tu aides l'utilisateur à comprendre son système, diagnostiquer des problèmes, et optimiser son environnement.
|
|
||||||
|
|
||||||
OUTILS DISPONIBLES:
|
|
||||||
- terminal: Exécute des commandes shell sur le système local et retourne le résultat
|
|
||||||
|
|
||||||
RÈGLES:
|
|
||||||
- Utilise l'outil terminal pour exécuter des commandes quand c'est nécessaire
|
|
||||||
- Analyse les résultats et explique-les clairement
|
|
||||||
- Formate tes réponses en markdown avec des blocs de code quand approprié
|
|
||||||
- Sois concis et technique
|
|
||||||
- Quand tu proposes des commandes alternatives, utilise des blocs de code markdown
|
|
||||||
|
|
||||||
`)
|
|
||||||
|
|
||||||
analysis := LoadSystemAnalysis()
|
analysis := LoadSystemAnalysis()
|
||||||
if analysis != "" {
|
if analysis != "" {
|
||||||
sb.WriteString("=== ANALYSE SYSTÈME ACTUELLE ===\n")
|
sb.WriteString("<system_context>\n")
|
||||||
sb.WriteString(analysis)
|
sb.WriteString(analysis)
|
||||||
sb.WriteString("\n=== FIN DE L'ANALYSE ===\n\n")
|
sb.WriteString("\n</system_context>\n\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
sb.WriteString(fmt.Sprintf("OS: %s/%s\n", runtime.GOOS, runtime.GOARCH))
|
sb.WriteString(fmt.Sprintf("OS: %s/%s\n", runtime.GOOS, runtime.GOARCH))
|
||||||
if hostname, err := os.Hostname(); err == nil {
|
if hostname, err := os.Hostname(); err == nil {
|
||||||
sb.WriteString("Hostname: " + hostname + "\n")
|
sb.WriteString("Hostname: " + hostname + "\n")
|
||||||
}
|
}
|
||||||
|
if user := os.Getenv("USER"); user != "" {
|
||||||
|
sb.WriteString("User: " + user + "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
isRoot := os.Geteuid() == 0
|
||||||
|
sb.WriteString(fmt.Sprintf("Root: %t\n", isRoot))
|
||||||
|
if isRoot {
|
||||||
|
sb.WriteString("⚠️ Session en root — toutes les commandes ont les privilèges administrateur.\n")
|
||||||
|
} else {
|
||||||
|
sb.WriteString("⚠️ Session utilisateur standard — les commandes sudo/doas nécessitent une autorisation. N'utilise PAS sudo ou doas sans demander.\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
sb.WriteString(fmt.Sprintf("Date: %s\nHeure: %s\n", now.Format("02/01/2006"), now.Format("15:04:05")))
|
||||||
|
|
||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
@@ -131,6 +133,9 @@ func (s *Server) handleShellChatStream(w http.ResponseWriter, orb *orchestrator.
|
|||||||
storeContent = string(storeJSON)
|
storeContent = string(storeJSON)
|
||||||
}
|
}
|
||||||
s.shellConvStore.Add("assistant", storeContent)
|
s.shellConvStore.Add("assistant", storeContent)
|
||||||
|
s.shellConvStore.AddRealTokens(engine.TotalTokens)
|
||||||
|
|
||||||
|
s.consumption.Record(engine.ProviderName(), engine.TotalTokens)
|
||||||
|
|
||||||
sseWriter.Write(map[string]interface{}{
|
sseWriter.Write(map[string]interface{}{
|
||||||
"done": "true",
|
"done": "true",
|
||||||
@@ -150,6 +155,10 @@ func (s *Server) handleShellChatNonStream(w http.ResponseWriter, orb *orchestrat
|
|||||||
}
|
}
|
||||||
|
|
||||||
s.shellConvStore.Add("assistant", finalContent)
|
s.shellConvStore.Add("assistant", finalContent)
|
||||||
|
s.shellConvStore.AddRealTokens(engine.TotalTokens)
|
||||||
|
|
||||||
|
s.consumption.Record(engine.ProviderName(), engine.TotalTokens)
|
||||||
|
|
||||||
writeJSON(w, map[string]interface{}{
|
writeJSON(w, map[string]interface{}{
|
||||||
"content": finalContent,
|
"content": finalContent,
|
||||||
"tokens": s.shellConvStore.ApproxTokens(),
|
"tokens": s.shellConvStore.ApproxTokens(),
|
||||||
@@ -289,15 +298,33 @@ func (s *Server) handleShellAnalyze(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
orb.SetSystemPrompt(agent.StudioSystemPrompt())
|
orb.SetSystemPrompt(agent.StudioSystemPrompt())
|
||||||
|
|
||||||
analysisPrompt := `Tu es un expert en administration système. Analyse les informations suivantes sur le système de l'utilisateur.
|
analysisPrompt := `Tu es un expert en administration système. Analyse les informations suivantes et génère un rapport structuré en markdown.
|
||||||
Génère un rapport d'analyse concis et structuré en markdown qui inclut:
|
|
||||||
1. Un résumé de l'état du système
|
|
||||||
2. Les points d'attention (performance, sécurité, configuration)
|
|
||||||
3. Des recommandations spécifiques d'optimisation
|
|
||||||
4. Les outils manquants qui pourraient être utiles
|
|
||||||
5. L'état du réseau et des connexions
|
|
||||||
|
|
||||||
Sois concret et technique. Le rapport sera utilisé comme contexte pour un assistant terminal.
|
STRUCTURE REQUISE :
|
||||||
|
|
||||||
|
## État du système
|
||||||
|
- Résumé en 2-3 phrases de l'état général (OK/Attention/Critique)
|
||||||
|
|
||||||
|
## Points d'attention
|
||||||
|
Liste les problèmes détectés par priorité :
|
||||||
|
- **CRITIQUE** : problèmes de sécurité, espace disque < 10%, mémoire < 10%
|
||||||
|
- **ATTENTION** : CPU élevé, services en échec, config non-optimale
|
||||||
|
- **INFO** : améliorations possibles, mises à jour disponibles
|
||||||
|
|
||||||
|
## Recommandations
|
||||||
|
Pour chaque point d'attention, donne UNE commande ou action corrective concrète.
|
||||||
|
|
||||||
|
## Outils manquants
|
||||||
|
Liste les outils utiles non installés avec la commande d'installation.
|
||||||
|
|
||||||
|
## Réseau
|
||||||
|
- Interfaces actives, ports en écoute, connectivité
|
||||||
|
|
||||||
|
RÈGLES :
|
||||||
|
- Pas de blabla générique — sois spécifique à CE système
|
||||||
|
- Inclus les valeurs numériques réelles (%, Go, MHz)
|
||||||
|
- Max 1500 mots
|
||||||
|
- Le rapport sert de contexte persistant pour un assistant terminal
|
||||||
|
|
||||||
` + sysInfo.String()
|
` + sysInfo.String()
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ type Server struct {
|
|||||||
mux *http.ServeMux
|
mux *http.ServeMux
|
||||||
convStore *ConversationStore
|
convStore *ConversationStore
|
||||||
shellConvStore *ShellConvStore
|
shellConvStore *ShellConvStore
|
||||||
|
consumption *consumptionStore
|
||||||
agentRegistry *agent.Registry
|
agentRegistry *agent.Registry
|
||||||
agentToolsJSON json.RawMessage
|
agentToolsJSON json.RawMessage
|
||||||
shellAgentRegistry *agent.Registry
|
shellAgentRegistry *agent.Registry
|
||||||
@@ -50,6 +51,7 @@ func NewServer(cfg *config.MuyueConfig) *Server {
|
|||||||
s.scanResult = scanner.ScanSystem()
|
s.scanResult = scanner.ScanSystem()
|
||||||
s.convStore = NewConversationStore()
|
s.convStore = NewConversationStore()
|
||||||
s.shellConvStore = NewShellConvStore()
|
s.shellConvStore = NewShellConvStore()
|
||||||
|
s.consumption = newConsumptionStore()
|
||||||
s.agentRegistry = agent.DefaultRegistry()
|
s.agentRegistry = agent.DefaultRegistry()
|
||||||
tools := s.agentRegistry.OpenAITools()
|
tools := s.agentRegistry.OpenAITools()
|
||||||
toolsJSON, _ := json.Marshal(tools)
|
toolsJSON, _ := json.Marshal(tools)
|
||||||
@@ -131,6 +133,7 @@ func (s *Server) routes() {
|
|||||||
s.mux.HandleFunc("/api/skills/import", s.handleSkillImport)
|
s.mux.HandleFunc("/api/skills/import", s.handleSkillImport)
|
||||||
s.mux.HandleFunc("/api/dashboard/status", s.handleDashboardStatus)
|
s.mux.HandleFunc("/api/dashboard/status", s.handleDashboardStatus)
|
||||||
s.mux.HandleFunc("/api/providers/quota", s.handleProvidersQuota)
|
s.mux.HandleFunc("/api/providers/quota", s.handleProvidersQuota)
|
||||||
|
s.mux.HandleFunc("/api/providers/consumption", s.handleProvidersConsumption)
|
||||||
s.mux.HandleFunc("/api/recent-commands", s.handleRecentCommands)
|
s.mux.HandleFunc("/api/recent-commands", s.handleRecentCommands)
|
||||||
s.mux.HandleFunc("/api/running-processes", s.handleRunningProcesses)
|
s.mux.HandleFunc("/api/running-processes", s.handleRunningProcesses)
|
||||||
s.mux.HandleFunc("/api/system/metrics", s.handleSystemMetrics)
|
s.mux.HandleFunc("/api/system/metrics", s.handleSystemMetrics)
|
||||||
|
|||||||
@@ -14,6 +14,63 @@ import (
|
|||||||
const shellMaxTokens = 100000
|
const shellMaxTokens = 100000
|
||||||
const shellCharsPerToken = 4
|
const shellCharsPerToken = 4
|
||||||
|
|
||||||
|
const shellSystemPromptBase = `Tu es l'**Analyste Système** de Muyue. Tu es un expert en administration système, DevOps et développement.
|
||||||
|
|
||||||
|
<critical_rules>
|
||||||
|
1. **AGIS, ne décris pas** — Utilise l'outil terminal pour exécuter, ne te contente pas de proposer des commandes.
|
||||||
|
2. **SOIS AUTONOME** — Cherche les infos manquantes via des commandes avant de demander à l'utilisateur. Essaie plusieurs approches avant de bloquer.
|
||||||
|
3. **SOIS CONCIS** — Max 4 lignes par défaut. Pas de préambule. Réponse directe et technique.
|
||||||
|
4. **GÈRE LES ERREURS** — Si une commande échoue, lis l'erreur, comprends la cause, essaie une approche alternative. 2-3 tentatives avant de rapporter.
|
||||||
|
5. **SÉCURITÉ** — Ne révèle jamais de credentials. Demande confirmation avant les commandes destructrices (rm -rf, format, etc.).
|
||||||
|
6. **LANGUE** — Réponds dans la même langue que l'utilisateur.
|
||||||
|
</critical_rules>
|
||||||
|
|
||||||
|
<tool_usage>
|
||||||
|
Outil disponible : **terminal** — Exécute des commandes shell sur le système local.
|
||||||
|
|
||||||
|
Stratégies :
|
||||||
|
- **Diagnostique** — Enchaîne les commandes de diagnostic (ps, df, free, top, journalctl, dmesg, netstat, ss, etc.)
|
||||||
|
- **Parallélisme** — Combine les commandes avec && ou ; quand elles sont indépendantes
|
||||||
|
- **Filtrage** — Utilise grep, awk, sort, head pour extraire l'essentiel des sorties volumineuses
|
||||||
|
- **Non-interactif** — Préfère les commandes non-interactives (apt install -y, non pas apt install)
|
||||||
|
- **Troncature** — Si le résultat dépasse 2000 caractères, résume les points clés au lieu de tout afficher
|
||||||
|
</tool_usage>
|
||||||
|
|
||||||
|
<decision_making>
|
||||||
|
- Décide par toi-même : exécute des commandes pour comprendre l'état du système
|
||||||
|
- Ne demande confirmation que pour les actions destructrices
|
||||||
|
- Si tu ne connais pas la commande exacte, exécute la commande avec --help pour la trouver
|
||||||
|
- Si bloqué : documente ce que tu as essayé, pourquoi, et l'action minimale requise
|
||||||
|
- Ne t'arrête jamais pour une tâche complexe — découpe en étapes et exécute-les
|
||||||
|
</decision_making>
|
||||||
|
|
||||||
|
<error_recovery>
|
||||||
|
1. Lis le message d'erreur complet (stderr + stdout)
|
||||||
|
2. Identifie la cause racine (permissions, paquet manquant, config, service)
|
||||||
|
3. Essaie : vérifier le service, vérifier les logs, chercher le paquet, tester la connexion
|
||||||
|
4. Propose une solution concrète, pas générique
|
||||||
|
</error_recovery>
|
||||||
|
|
||||||
|
<response_format>
|
||||||
|
- **Commandes** : blocs markdown avec le langage (bash, sh, etc.)
|
||||||
|
- **Résultats** : résume les métriques clés, pas de dump complet
|
||||||
|
- **Erreurs** : cause + solution en 1-2 lignes
|
||||||
|
- **Succès** : confirmation en 1 ligne
|
||||||
|
- **Analyses** : markdown structuré avec sections si nécessaire
|
||||||
|
</response_format>
|
||||||
|
|
||||||
|
<mermaid>
|
||||||
|
Tu peux utiliser des diagrammes Mermaid pour visualiser :
|
||||||
|
- Architecture système (graph TD/LR)
|
||||||
|
- Flux réseau (sequenceDiagram)
|
||||||
|
- Processus (flowchart)
|
||||||
|
- Timeline (gantt)
|
||||||
|
|
||||||
|
Utilise un bloc de code avec le langage mermaid quand ça clarifie l'explication. Pas pour du texte simple.
|
||||||
|
</mermaid>
|
||||||
|
|
||||||
|
`
|
||||||
|
|
||||||
type ShellMessage struct {
|
type ShellMessage struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Role string `json:"role"`
|
Role string `json:"role"`
|
||||||
@@ -22,9 +79,10 @@ type ShellMessage struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ShellConvStore struct {
|
type ShellConvStore struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
path string
|
path string
|
||||||
msgs []ShellMessage
|
msgs []ShellMessage
|
||||||
|
realTokens int
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShellConvStore() *ShellConvStore {
|
func NewShellConvStore() *ShellConvStore {
|
||||||
@@ -82,19 +140,37 @@ func (s *ShellConvStore) Clear() {
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
s.msgs = []ShellMessage{}
|
s.msgs = []ShellMessage{}
|
||||||
|
s.realTokens = 0
|
||||||
s.save()
|
s.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ShellConvStore) ApproxTokens() int {
|
func (s *ShellConvStore) ApproxTokens() int {
|
||||||
|
if s.realTokens > 0 {
|
||||||
|
return s.realTokens
|
||||||
|
}
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
defer s.mu.RUnlock()
|
||||||
total := 0
|
total := 0
|
||||||
for _, m := range s.msgs {
|
for _, m := range s.msgs {
|
||||||
total += utf8.RuneCountInString(m.Content) / shellCharsPerToken
|
total += utf8.RuneCountInString(m.Content) / shellCharsPerToken
|
||||||
}
|
}
|
||||||
|
total += utf8.RuneCountInString(shellSystemPromptBase) / shellCharsPerToken
|
||||||
|
if analysis := LoadSystemAnalysis(); analysis != "" {
|
||||||
|
total += utf8.RuneCountInString(analysis) / shellCharsPerToken
|
||||||
|
}
|
||||||
return total
|
return total
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AddRealTokens accumulates actual token counts from the API response.
|
||||||
|
func (s *ShellConvStore) AddRealTokens(tokens int) {
|
||||||
|
if tokens <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.realTokens += tokens
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
func (s *ShellConvStore) AtLimit() bool {
|
func (s *ShellConvStore) AtLimit() bool {
|
||||||
return s.ApproxTokens() >= shellMaxTokens
|
return s.ApproxTokens() >= shellMaxTokens
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -289,7 +289,7 @@ func Default() *MuyueConfig {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "mimo",
|
Name: "mimo",
|
||||||
Model: "MiMo-V2.5-Pro",
|
Model: "mimo-v2.5-pro",
|
||||||
BaseURL: "https://token-plan-ams.xiaomimimo.com/v1",
|
BaseURL: "https://token-plan-ams.xiaomimimo.com/v1",
|
||||||
Active: false,
|
Active: false,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -159,14 +159,18 @@ func parsePlanResponse(content string) ([]Step, error) {
|
|||||||
return steps, nil
|
return steps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const plannerSystemPrompt = `Tu es un assistant de planification de workflows pour Muyue. Tu génères des plans d'exécution sous forme de JSON. Chaque plan est une séquence d'étapes (steps) représentant des appels d'outils.
|
const plannerSystemPrompt = `Tu es un planificateur de workflows pour Muyue. Tu génères des plans d'exécution sous forme de tableaux JSON.
|
||||||
|
|
||||||
Pour générer un plan:
|
RÈGLES :
|
||||||
1. Comprends l'objectif de l'utilisateur
|
1. Analyse l'objectif → identifie les outils → décompose en étapes
|
||||||
2. Identifie les outils nécessaires
|
2. Chaque étape : {"name": string, "tool": string, "args": object}
|
||||||
3. Décompose en étapes logiques
|
3. Max 10 étapes par plan
|
||||||
4. Spécifie les paramètres de chaque outil
|
4. Ordonne par dépendances (les lectures avant les écritures)
|
||||||
|
5. Préfère les commandes non-interactives
|
||||||
|
6. Utilise crush_run pour les tâches complexes multi-fichiers
|
||||||
|
|
||||||
Réponds toujours en JSON valide, sans texte additionnel.`
|
Outils : terminal, crush_run, read_file, list_files, search_files, grep_content, get_config, set_provider, manage_ssh, web_fetch
|
||||||
|
|
||||||
var _ = plannerSystemPrompt
|
Réponds UNIQUEMENT en JSON valide, sans texte avant/après.`
|
||||||
|
|
||||||
|
const _ = plannerSystemPrompt
|
||||||
1253
web/package-lock.json
generated
1253
web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,7 @@
|
|||||||
"@xterm/addon-webgl": "^0.20.0-beta.202",
|
"@xterm/addon-webgl": "^0.20.0-beta.202",
|
||||||
"@xterm/xterm": "^6.1.0-beta.203",
|
"@xterm/xterm": "^6.1.0-beta.203",
|
||||||
"lucide-react": "^1.8.0",
|
"lucide-react": "^1.8.0",
|
||||||
|
"mermaid": "^11.14.0",
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.5",
|
||||||
"react-dom": "^19.2.5"
|
"react-dom": "^19.2.5"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ const api = {
|
|||||||
importSkill: (path) => request('/skills/import', { method: 'POST', body: JSON.stringify({ import_path: path }) }),
|
importSkill: (path) => request('/skills/import', { method: 'POST', body: JSON.stringify({ import_path: path }) }),
|
||||||
getDashboardStatus: () => request('/dashboard/status'),
|
getDashboardStatus: () => request('/dashboard/status'),
|
||||||
getProvidersQuota: () => request('/providers/quota'),
|
getProvidersQuota: () => request('/providers/quota'),
|
||||||
|
getProvidersConsumption: () => request('/providers/consumption'),
|
||||||
getRecentCommands: () => request('/recent-commands'),
|
getRecentCommands: () => request('/recent-commands'),
|
||||||
getRunningProcesses: () => request('/running-processes'),
|
getRunningProcesses: () => request('/running-processes'),
|
||||||
getSystemMetrics: () => request('/system/metrics'),
|
getSystemMetrics: () => request('/system/metrics'),
|
||||||
|
|||||||
@@ -94,10 +94,8 @@ export default function App() {
|
|||||||
shell: [
|
shell: [
|
||||||
{ keys: `${layout.keys.ctrl}+${layout.keys.shift}+C`, desc: t('statusbar.copy') },
|
{ keys: `${layout.keys.ctrl}+${layout.keys.shift}+C`, desc: t('statusbar.copy') },
|
||||||
{ keys: `${layout.keys.ctrl}+${layout.keys.shift}+V`, desc: t('statusbar.paste') },
|
{ keys: `${layout.keys.ctrl}+${layout.keys.shift}+V`, desc: t('statusbar.paste') },
|
||||||
{ keys: `${layout.keys.ctrl}+F`, desc: t('statusbar.search') },
|
{ keys: `${layout.keys.ctrl}+${layout.keys.shift}+F`, desc: t('statusbar.search') },
|
||||||
{ keys: `${layout.keys.ctrl}+/Ctrl−`, desc: t('statusbar.zoom') },
|
{ keys: `${layout.keys.ctrl}++/${layout.keys.ctrl}+−`, desc: t('statusbar.zoom') },
|
||||||
{ keys: `Alt+1-7`, desc: t('statusbar.switchTab') },
|
|
||||||
{ keys: `${layout.keys.shift}+Tab`, desc: t('statusbar.nextTab') },
|
|
||||||
{ keys: layout.keys.enter, desc: t('statusbar.runCommand') },
|
{ keys: layout.keys.enter, desc: t('statusbar.runCommand') },
|
||||||
{ keys: `${layout.keys.up}/${layout.keys.down}`, desc: t('statusbar.commandHistory') },
|
{ keys: `${layout.keys.up}/${layout.keys.down}`, desc: t('statusbar.commandHistory') },
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -6,6 +6,12 @@ const MAX_POINTS = 30
|
|||||||
const POLL_INTERVAL = 5000
|
const POLL_INTERVAL = 5000
|
||||||
const MAX_IDLE_POLLS = 3
|
const MAX_IDLE_POLLS = 3
|
||||||
|
|
||||||
|
function formatTokens(n) {
|
||||||
|
if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M'
|
||||||
|
if (n >= 1000) return (n / 1000).toFixed(1) + 'K'
|
||||||
|
return String(n)
|
||||||
|
}
|
||||||
|
|
||||||
function MiniGraph({ data, max, color, label, unit }) {
|
function MiniGraph({ data, max, color, label, unit }) {
|
||||||
if (!data || data.length < 2) return <div className="dash-graph-empty">collecting...</div>
|
if (!data || data.length < 2) return <div className="dash-graph-empty">collecting...</div>
|
||||||
const m = max || Math.max(...data, 1)
|
const m = max || Math.max(...data, 1)
|
||||||
@@ -37,9 +43,28 @@ function MiniGraph({ data, max, color, label, unit }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function BarChart({ data, max, color }) {
|
||||||
|
if (!data || data.length === 0) return null
|
||||||
|
const barW = 100 / 7
|
||||||
|
const m = max || Math.max(...data.map(d => d.tokens), 1)
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 100 40" className="dash-graph-svg" preserveAspectRatio="none">
|
||||||
|
{data.map((d, i) => {
|
||||||
|
const h = Math.max(1, (d.tokens / m) * 36)
|
||||||
|
const x = i * barW + barW * 0.15
|
||||||
|
const w = barW * 0.7
|
||||||
|
return (
|
||||||
|
<rect key={i} x={x} y={40 - h} width={w} height={h} rx="1.5" fill={color} opacity={0.85} />
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export default function Dashboard({ api, refreshRef }) {
|
export default function Dashboard({ api, refreshRef }) {
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
const [quota, setQuota] = useState(null)
|
const [quota, setQuota] = useState(null)
|
||||||
|
const [consumption, setConsumption] = useState(null)
|
||||||
const [recentCmds, setRecentCmds] = useState([])
|
const [recentCmds, setRecentCmds] = useState([])
|
||||||
const [processes, setProcesses] = useState([])
|
const [processes, setProcesses] = useState([])
|
||||||
const [metrics, setMetrics] = useState(null)
|
const [metrics, setMetrics] = useState(null)
|
||||||
@@ -51,13 +76,15 @@ export default function Dashboard({ api, refreshRef }) {
|
|||||||
|
|
||||||
const loadData = useCallback(async () => {
|
const loadData = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const [quotaData, cmdData, procData, metricsData] = await Promise.all([
|
const [quotaData, consumData, cmdData, procData, metricsData] = await Promise.all([
|
||||||
api.getProvidersQuota().catch(() => null),
|
api.getProvidersQuota().catch(() => null),
|
||||||
|
api.getProvidersConsumption().catch(() => null),
|
||||||
api.getRecentCommands().catch(() => ({ commands: [] })),
|
api.getRecentCommands().catch(() => ({ commands: [] })),
|
||||||
api.getRunningProcesses().catch(() => ({ processes: [] })),
|
api.getRunningProcesses().catch(() => ({ processes: [] })),
|
||||||
api.getSystemMetrics().catch(() => null),
|
api.getSystemMetrics().catch(() => null),
|
||||||
])
|
])
|
||||||
setQuota(quotaData?.providers || [])
|
setQuota(quotaData?.providers || [])
|
||||||
|
setConsumption(consumData?.providers || {})
|
||||||
setRecentCmds(cmdData.commands || [])
|
setRecentCmds(cmdData.commands || [])
|
||||||
setProcesses(procData.processes || [])
|
setProcesses(procData.processes || [])
|
||||||
if (metricsData) {
|
if (metricsData) {
|
||||||
@@ -91,7 +118,6 @@ export default function Dashboard({ api, refreshRef }) {
|
|||||||
}, [loadData, refreshRef])
|
}, [loadData, refreshRef])
|
||||||
|
|
||||||
const minimax = (quota || []).find(p => p.name === 'minimax')
|
const minimax = (quota || []).find(p => p.name === 'minimax')
|
||||||
const mimo = (quota || []).find(p => p.name === 'mimo')
|
|
||||||
|
|
||||||
const EXCLUDE_CMDS = ['ls', 'cd', 'pwd', 'clear', 'exit', 'history', 'cat', 'echo', 'grep', 'export', 'alias', 'unalias', 'set', 'unset', 'source', '.', 'fg', 'bg', 'jobs', 'wait', 'true', 'false', 'yes', 'sleep', 'date', 'whoami', 'id', 'uname', 'hostname', 'uptime', 'df', 'free', 'top', 'htop', 'nano', 'vi', 'vim', 'less', 'more', 'tail', 'head', 'man', 'info', 'which', 'whereis', 'type', 'command', 'hash', 'builtin', 'help']
|
const EXCLUDE_CMDS = ['ls', 'cd', 'pwd', 'clear', 'exit', 'history', 'cat', 'echo', 'grep', 'export', 'alias', 'unalias', 'set', 'unset', 'source', '.', 'fg', 'bg', 'jobs', 'wait', 'true', 'false', 'yes', 'sleep', 'date', 'whoami', 'id', 'uname', 'hostname', 'uptime', 'df', 'free', 'top', 'htop', 'nano', 'vi', 'vim', 'less', 'more', 'tail', 'head', 'man', 'info', 'which', 'whereis', 'type', 'command', 'hash', 'builtin', 'help']
|
||||||
|
|
||||||
@@ -135,6 +161,12 @@ export default function Dashboard({ api, refreshRef }) {
|
|||||||
})
|
})
|
||||||
})()
|
})()
|
||||||
|
|
||||||
|
const providerEntries = consumption ? Object.entries(consumption) : []
|
||||||
|
const colors = ['var(--accent)', '#34d399', '#a78bfa', '#f59e0b', '#f472b6']
|
||||||
|
const maxDaily = providerEntries.length > 0
|
||||||
|
? Math.max(...providerEntries.map(([, p]) => Math.max(...(p.daily || []).map(d => d.tokens), 0)), 1)
|
||||||
|
: 1
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="dash-grid">
|
<div className="dash-grid">
|
||||||
{/* CPU */}
|
{/* CPU */}
|
||||||
@@ -165,43 +197,36 @@ export default function Dashboard({ api, refreshRef }) {
|
|||||||
<MiniGraph data={netTxRef.current} max={null} color="#f59e0b" label="TX" unit=" KB/s" />
|
<MiniGraph data={netTxRef.current} max={null} color="#f59e0b" label="TX" unit=" KB/s" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* API Quota */}
|
{/* Consommation */}
|
||||||
<div className="dash-card">
|
<div className="dash-card">
|
||||||
<div className="dash-card-head">
|
<div className="dash-card-head">
|
||||||
<span className="dash-label">API Quota</span>
|
<span className="dash-label">Consommation</span>
|
||||||
|
<span className="dash-count">7j</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="dash-quota-list">
|
<div className="dash-consumption-list">
|
||||||
{minimax && minimax.data?.models?.map((m, i) => (
|
{providerEntries.length === 0 && (
|
||||||
<div key={i} className="dash-quota-row">
|
<span className="dash-empty">Aucune donnée</span>
|
||||||
<span className="dash-quota-name">{String(m.model).replace('MiniMax-', '')}</span>
|
)}
|
||||||
<div className="dash-bar">
|
{providerEntries.map(([name, p], pi) => (
|
||||||
<div className="dash-bar-fill" style={{ width: `${Math.min(100, (m.used / m.total) * 100)}%` }} />
|
<div key={name} className="dash-consumption-provider">
|
||||||
|
<div className="dash-consumption-head">
|
||||||
|
<span className="dash-consumption-name" style={{ color: colors[pi % colors.length] }}>
|
||||||
|
{name.toUpperCase()}
|
||||||
|
</span>
|
||||||
|
<span className="dash-consumption-total">
|
||||||
|
{formatTokens(p.total_tokens)} tokens · {p.total_requests} req
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<BarChart data={p.daily || []} max={maxDaily} color={colors[pi % colors.length]} />
|
||||||
|
<div className="dash-consumption-days">
|
||||||
|
{(p.daily || []).map((d, i) => (
|
||||||
|
<span key={i} className="dash-consumption-day">
|
||||||
|
{d.date.slice(5)} <strong>{formatTokens(d.tokens)}</strong>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
<span className="dash-quota-val">{m.used}/{m.total}</span>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{minimax && minimax.data?.models?.length === 0 && (
|
|
||||||
<div className="dash-quota-row">
|
|
||||||
<span className="dash-quota-name">MiniMax</span>
|
|
||||||
<span className="dash-quota-val" style={{ color: 'var(--text-tertiary)' }}>{minimax.error || 'no data'}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{mimo && mimo.data?.models?.map((m, i) => (
|
|
||||||
<div key={i} className="dash-quota-row">
|
|
||||||
<span className="dash-quota-name">{String(m.model).replace('MiMo-', '')}</span>
|
|
||||||
<div className="dash-bar">
|
|
||||||
<div className="dash-bar-fill" style={{ width: `${Math.min(100, (m.used / m.total) * 100)}%` }} />
|
|
||||||
</div>
|
|
||||||
<span className="dash-quota-val">{m.used}/{m.total}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{mimo && !mimo.data?.models?.length && (
|
|
||||||
<div className="dash-quota-row">
|
|
||||||
<span className="dash-quota-name">MiMo</span>
|
|
||||||
<span className="dash-quota-val" style={{ color: 'var(--text-tertiary)' }}>{mimo.error || (mimo.healthy ? '✓ configured' : 'no key')}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!minimax && !mimo && <span className="dash-quota-val" style={{ color: 'var(--text-tertiary)' }}>No providers</span>}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,14 @@ import { ImageAddon } from '@xterm/addon-image'
|
|||||||
import { Plus, X, Monitor, Globe, ChevronDown, Pencil, Trash2, Search, Copy, Send, Eye, Bot } from 'lucide-react'
|
import { Plus, X, Monitor, Globe, ChevronDown, Pencil, Trash2, Search, Copy, Send, Eye, Bot } from 'lucide-react'
|
||||||
import '@xterm/xterm/css/xterm.css'
|
import '@xterm/xterm/css/xterm.css'
|
||||||
import { useI18n } from '../i18n'
|
import { useI18n } from '../i18n'
|
||||||
|
import mermaid from 'mermaid'
|
||||||
|
|
||||||
|
mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose', fontFamily: 'var(--font-mono)' })
|
||||||
|
|
||||||
const AI_TAB_ID = 0
|
const AI_TAB_ID = 0
|
||||||
const MAX_TABS = 7
|
const MAX_TABS = 7
|
||||||
const SHELL_MAX_TOKENS = 100000
|
const SHELL_MAX_TOKENS = 100000
|
||||||
|
const SHELL_AI_COMMANDS = ['/clear', '/help', '/model', '/model change']
|
||||||
const TABS_STORAGE_KEY = 'muyue_shell_tabs'
|
const TABS_STORAGE_KEY = 'muyue_shell_tabs'
|
||||||
const TERMINAL_BUFFER_KEY = 'muyue_terminal_buffers'
|
const TERMINAL_BUFFER_KEY = 'muyue_terminal_buffers'
|
||||||
|
|
||||||
@@ -51,6 +55,15 @@ function formatText(text) {
|
|||||||
let html = text
|
let html = text
|
||||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||||
|
|
||||||
|
html = html.replace(/^(\|.+\|)\n(\|[\s\-:|]+\|)\n((?:\|.+\|\n?)+)/gm, (match, headerRow, sepRow, bodyRows) => {
|
||||||
|
const headers = headerRow.split('|').filter(c => c.trim() !== '').map(c => `<th>${c.trim()}</th>`).join('')
|
||||||
|
const rows = bodyRows.trim().split('\n').map(row => {
|
||||||
|
const cells = row.split('|').filter(c => c.trim() !== '').map(c => `<td>${c.trim()}</td>`).join('')
|
||||||
|
return `<tr>${cells}</tr>`
|
||||||
|
}).join('')
|
||||||
|
return `<table><thead><tr>${headers}</tr></thead><tbody>${rows}</tbody></table>`
|
||||||
|
})
|
||||||
|
|
||||||
html = html
|
html = html
|
||||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
|
.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
|
||||||
@@ -63,8 +76,8 @@ function formatText(text) {
|
|||||||
|
|
||||||
html = html
|
html = html
|
||||||
.replace(/<br\/>\s*<br\/>/g, '<br/>')
|
.replace(/<br\/>\s*<br\/>/g, '<br/>')
|
||||||
.replace(/<br\/>\s*(<h[234]|<div class="msg-)/g, '$1')
|
.replace(/<br\/>\s*(<h[234]|<div class="msg-|<table)/g, '$1')
|
||||||
.replace(/(<\/h[234]|<\/div>)\s*<br\/>/g, '$1')
|
.replace(/(<\/h[234]|<\/div>|<\/table>)\s*<br\/>/g, '$1')
|
||||||
.replace(/\s+on\w+=["'][^"']*["']/gi, '')
|
.replace(/\s+on\w+=["'][^"']*["']/gi, '')
|
||||||
.replace(/javascript:/gi, '')
|
.replace(/javascript:/gi, '')
|
||||||
.replace(/data:/gi, '')
|
.replace(/data:/gi, '')
|
||||||
@@ -200,11 +213,13 @@ function getTheme(themeName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createTerminal(container, settings = {}) {
|
function createTerminal(container, settings = {}) {
|
||||||
|
console.log('[Shell] createTerminal called with settings:', JSON.stringify({ fontSize: settings.fontSize, fontFamily: settings.fontFamily?.slice(0, 30), theme: settings.theme }))
|
||||||
const theme = getTheme(settings.theme || 'system')
|
const theme = getTheme(settings.theme || 'system')
|
||||||
|
const actualFontSize = settings.fontSize || 14
|
||||||
const term = new XTerm({
|
const term = new XTerm({
|
||||||
cursorBlink: true,
|
cursorBlink: true,
|
||||||
allowProposedApi: true,
|
allowProposedApi: true,
|
||||||
fontSize: settings.fontSize || 14,
|
fontSize: actualFontSize,
|
||||||
fontFamily: settings.fontFamily || "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', 'Menlo', monospace",
|
fontFamily: settings.fontFamily || "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', 'Menlo', monospace",
|
||||||
theme,
|
theme,
|
||||||
allowTransparency: false,
|
allowTransparency: false,
|
||||||
@@ -404,12 +419,13 @@ export default function Shell({ api }) {
|
|||||||
theme: 'system',
|
theme: 'system',
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const [configLoaded, setConfigLoaded] = useState(false)
|
||||||
const [showSearch, setShowSearch] = useState(false)
|
const [showSearch, setShowSearch] = useState(false)
|
||||||
const [searchText, setSearchText] = useState('')
|
const [searchText, setSearchText] = useState('')
|
||||||
const searchInputRef = useRef(null)
|
const searchInputRef = useRef(null)
|
||||||
const searchDecorationsRef = useRef(null)
|
const searchDecorationsRef = useRef(null)
|
||||||
const [zoomLevel, setZoomLevel] = useState(0)
|
const [zoomLevel, setZoomLevel] = useState(0)
|
||||||
const baseFontSizeRef = useRef(12)
|
const baseFontSizeRef = useRef(14)
|
||||||
|
|
||||||
useEffect(() => { settingsRef.current = terminalSettings }, [terminalSettings])
|
useEffect(() => { settingsRef.current = terminalSettings }, [terminalSettings])
|
||||||
|
|
||||||
@@ -450,6 +466,7 @@ export default function Shell({ api }) {
|
|||||||
const [analyzing, setAnalyzing] = useState(false)
|
const [analyzing, setAnalyzing] = useState(false)
|
||||||
const [showAnalysis, setShowAnalysis] = useState(false)
|
const [showAnalysis, setShowAnalysis] = useState(false)
|
||||||
const [analysisContent, setAnalysisContent] = useState('')
|
const [analysisContent, setAnalysisContent] = useState('')
|
||||||
|
const [sudoModal, setSudoModal] = useState(null)
|
||||||
const aiMessagesRef = useRef(null)
|
const aiMessagesRef = useRef(null)
|
||||||
const aiLoadedRef = useRef(false)
|
const aiLoadedRef = useRef(false)
|
||||||
const aiLoadingRef = useRef(false)
|
const aiLoadingRef = useRef(false)
|
||||||
@@ -473,14 +490,10 @@ export default function Shell({ api }) {
|
|||||||
api.getShellChatHistory().then(d => {
|
api.getShellChatHistory().then(d => {
|
||||||
if (d.messages && d.messages.length > 0) {
|
if (d.messages && d.messages.length > 0) {
|
||||||
setAiMessages(d.messages)
|
setAiMessages(d.messages)
|
||||||
} else {
|
|
||||||
setAiMessages([{ role: 'assistant', content: t('shell.aiWelcome') || 'Système Analyste prêt. Tapez /help pour les commandes.' }])
|
|
||||||
}
|
}
|
||||||
setAiTokens(d.tokens || 0)
|
setAiTokens(d.tokens || 0)
|
||||||
setAiAtLimit(d.at_limit || false)
|
setAiAtLimit(d.at_limit || false)
|
||||||
}).catch(() => {
|
}).catch(() => {})
|
||||||
setAiMessages([{ role: 'assistant', content: 'Système Analyste prêt.' }])
|
|
||||||
})
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -494,14 +507,21 @@ export default function Shell({ api }) {
|
|||||||
setSystemTerminals(d.system || [])
|
setSystemTerminals(d.system || [])
|
||||||
}).catch(() => {})
|
}).catch(() => {})
|
||||||
api.getConfig().then(d => {
|
api.getConfig().then(d => {
|
||||||
|
console.log('[Shell] config response terminal:', JSON.stringify(d?.terminal))
|
||||||
if (d.terminal) {
|
if (d.terminal) {
|
||||||
setTerminalSettings({
|
const fontSize = d.terminal.font_size || 14
|
||||||
fontSize: d.terminal.font_size || 14,
|
const fontFamily = d.terminal.font_family || "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', 'Menlo', monospace"
|
||||||
fontFamily: d.terminal.font_family || "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', 'Menlo', monospace",
|
const theme = d.terminal.theme || 'system'
|
||||||
theme: d.terminal.theme || 'system',
|
console.log('[Shell] setting fontSize to:', fontSize, 'from config')
|
||||||
})
|
setTerminalSettings({ fontSize, fontFamily, theme })
|
||||||
|
settingsRef.current = { fontSize, fontFamily, theme }
|
||||||
|
baseFontSizeRef.current = fontSize
|
||||||
|
} else {
|
||||||
|
console.log('[Shell] no terminal config in response, using defaults')
|
||||||
}
|
}
|
||||||
}).catch(() => {})
|
setConfigLoaded(true)
|
||||||
|
console.log('[Shell] configLoaded = true, settingsRef:', JSON.stringify(settingsRef.current))
|
||||||
|
}).catch((err) => { console.warn('[Shell] getConfig failed:', err); setConfigLoaded(true) })
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const initTerminal = useCallback((tabId, tab) => {
|
const initTerminal = useCallback((tabId, tab) => {
|
||||||
@@ -512,6 +532,7 @@ export default function Shell({ api }) {
|
|||||||
|
|
||||||
const s = settingsRef.current
|
const s = settingsRef.current
|
||||||
const effectiveFontSize = s.fontSize + zoomLevel * 2
|
const effectiveFontSize = s.fontSize + zoomLevel * 2
|
||||||
|
console.log(`[Shell] initTerminal tab=${tabId}: settingsRef.fontSize=${s.fontSize}, zoomLevel=${zoomLevel}, effectiveFontSize=${effectiveFontSize}`)
|
||||||
const { term, fitAddon, searchAddon } = createTerminal(container, {
|
const { term, fitAddon, searchAddon } = createTerminal(container, {
|
||||||
fontSize: effectiveFontSize,
|
fontSize: effectiveFontSize,
|
||||||
fontFamily: s.fontFamily,
|
fontFamily: s.fontFamily,
|
||||||
@@ -621,6 +642,7 @@ export default function Shell({ api }) {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const initPendingTabs = useCallback(() => {
|
const initPendingTabs = useCallback(() => {
|
||||||
|
if (!configLoaded) return
|
||||||
for (const tab of tabsRef.current._tabList || []) {
|
for (const tab of tabsRef.current._tabList || []) {
|
||||||
if (!tabsRef.current[tab.id]) {
|
if (!tabsRef.current[tab.id]) {
|
||||||
const container = document.getElementById(`terminal-${tab.id}`)
|
const container = document.getElementById(`terminal-${tab.id}`)
|
||||||
@@ -641,7 +663,7 @@ export default function Shell({ api }) {
|
|||||||
}
|
}
|
||||||
}, 150)
|
}, 150)
|
||||||
})
|
})
|
||||||
}, [initTerminal])
|
}, [initTerminal, configLoaded])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
tabsRef.current._tabList = tabs
|
tabsRef.current._tabList = tabs
|
||||||
@@ -689,6 +711,7 @@ export default function Shell({ api }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!tabsRef.current[tab.id]) {
|
if (!tabsRef.current[tab.id]) {
|
||||||
|
console.log(`[Shell] tryInitTab: calling initTerminal for tab ${tab.id}, configLoaded=${configLoaded}`)
|
||||||
initTerminal(tab.id, tab)
|
initTerminal(tab.id, tab)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -707,8 +730,9 @@ export default function Shell({ api }) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(`[Shell] init effect: tabs=${tabs.length}, configLoaded=${configLoaded}`)
|
||||||
for (const tab of tabs) {
|
for (const tab of tabs) {
|
||||||
if (!tabsRef.current[tab.id]) {
|
if (configLoaded && !tabsRef.current[tab.id]) {
|
||||||
tryInitTab(tab, 0)
|
tryInitTab(tab, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -729,7 +753,7 @@ export default function Shell({ api }) {
|
|||||||
pending.forEach(clearTimeout)
|
pending.forEach(clearTimeout)
|
||||||
observer?.disconnect()
|
observer?.disconnect()
|
||||||
}
|
}
|
||||||
}, [tabs, initTerminal, initPendingTabs])
|
}, [tabs, initTerminal, initPendingTabs, configLoaded])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const entry = tabsRef.current[activeTab]
|
const entry = tabsRef.current[activeTab]
|
||||||
@@ -976,9 +1000,10 @@ export default function Shell({ api }) {
|
|||||||
if (entry) entry.term.focus()
|
if (entry) entry.term.focus()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const _sendAiMessage = useCallback(async (text, fromEvent = false) => {
|
const _sendAiMessage = useCallback(async (text, fromEvent = false, isAnalysis = false) => {
|
||||||
if (!text || !text.trim() || aiLoadingRef.current || aiAtLimit) return
|
if (!text || !text.trim() || aiLoadingRef.current) return
|
||||||
const trimmed = text.trim()
|
const trimmed = text.trim()
|
||||||
|
if (aiAtLimit && !trimmed.startsWith('/')) return
|
||||||
aiLoadingRef.current = true
|
aiLoadingRef.current = true
|
||||||
|
|
||||||
if (!fromEvent) {
|
if (!fromEvent) {
|
||||||
@@ -986,10 +1011,21 @@ export default function Shell({ api }) {
|
|||||||
setTimeout(() => focusAiTerminal(), 0)
|
setTimeout(() => focusAiTerminal(), 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isSlashCommand = (t) => /^\/(clear|help|model(?:\s+\S+)?)$/.test(t)
|
||||||
|
|
||||||
|
if (trimmed.startsWith('/') && !isSlashCommand(trimmed)) {
|
||||||
|
setAiMessages(prev => [...prev,
|
||||||
|
{ role: 'user', content: trimmed },
|
||||||
|
{ role: 'assistant', content: 'Commande inconnue. Tapez `/help` pour la liste des commandes.' }
|
||||||
|
])
|
||||||
|
aiLoadingRef.current = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (trimmed === '/clear') {
|
if (trimmed === '/clear') {
|
||||||
try {
|
try {
|
||||||
await api.clearShellChat()
|
await api.clearShellChat()
|
||||||
setAiMessages([{ role: 'assistant', content: t('shell.aiWelcome') || 'Contexte effacé. Prêt.' }])
|
setAiMessages([])
|
||||||
setAiTokens(0)
|
setAiTokens(0)
|
||||||
setAiAtLimit(false)
|
setAiAtLimit(false)
|
||||||
} catch {}
|
} catch {}
|
||||||
@@ -1000,15 +1036,50 @@ export default function Shell({ api }) {
|
|||||||
if (trimmed === '/help') {
|
if (trimmed === '/help') {
|
||||||
setAiMessages(prev => [...prev,
|
setAiMessages(prev => [...prev,
|
||||||
{ role: 'user', content: trimmed },
|
{ role: 'user', content: trimmed },
|
||||||
{ role: 'assistant', content: 'Commandes disponibles:\n• /clear — Effacer la conversation\n• /help — Afficher l\'aide\n\nJe peux exécuter des commandes via l\'outil terminal. Les blocs de code proposés peuvent aussi être copiés ou envoyés directement au terminal actif.' }
|
{ role: 'assistant', content: '## Commandes Terminal\n\n- `/clear` — Effacer la conversation\n- `/help` — Afficher cette aide\n- `/model` — Afficher le provider et modèle actifs\n- `/model change` — Basculer entre les providers disponibles' }
|
||||||
])
|
])
|
||||||
aiLoadingRef.current = false
|
aiLoadingRef.current = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trimmed === '/model' || trimmed === '/model change') {
|
||||||
|
if (trimmed === '/model change') {
|
||||||
|
api.getProviders().then(data => {
|
||||||
|
const providers = data.providers || []
|
||||||
|
const minimax = providers.find(p => p.name.toUpperCase() === 'MINIMAX')
|
||||||
|
const mimo = providers.find(p => p.name.toUpperCase() === 'MIMO')
|
||||||
|
if (!minimax || !mimo) {
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: 'MiniMax et MiMo doivent être configurés pour utiliser `/model change`.' }])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const active = providers.find(p => p.active)
|
||||||
|
const activeName = active ? active.name.toUpperCase() : ''
|
||||||
|
const switchTo = activeName === 'MINIMAX' ? 'MIMO' : 'MINIMAX'
|
||||||
|
const target = switchTo === 'MINIMAX' ? minimax : mimo
|
||||||
|
api.saveProvider({ name: target.name, active: true }).then(() => {
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: `✓ Provider changé: **${target.name}** (${target.model})` }])
|
||||||
|
}).catch(() => {
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: 'Erreur lors du changement de provider.' }])
|
||||||
|
})
|
||||||
|
}).catch(() => {
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: 'Erreur: impossible de récupérer les providers' }])
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
api.getProviders().then(data => {
|
||||||
|
const active = data.providers?.find(p => p.active)
|
||||||
|
const modelMsg = active ? `**${active.name}** — ${active.model}` : 'Aucun provider actif configuré'
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: modelMsg }])
|
||||||
|
}).catch(() => {
|
||||||
|
setAiMessages(prev => [...prev, { role: 'assistant', content: 'Erreur: impossible de récupérer les providers' }])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
aiLoadingRef.current = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const currentTab = activeTabRef.current
|
const currentTab = activeTabRef.current
|
||||||
console.log(`[Shell] _sendAiMessage: activeTab=${currentTab}, fromEvent=${fromEvent}, text="${trimmed.slice(0, 50)}"`)
|
console.log(`[Shell] _sendAiMessage: activeTab=${currentTab}, fromEvent=${fromEvent}, text="${trimmed.slice(0, 50)}"`)
|
||||||
setAiMessages(prev => [...prev, { role: 'user', content: trimmed, _tabId: currentTab }])
|
setAiMessages(prev => [...prev, { role: 'user', content: trimmed, _tabId: currentTab, _analysis: isAnalysis || undefined }])
|
||||||
setAiLoading(true)
|
setAiLoading(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1026,6 +1097,9 @@ export default function Shell({ api }) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (event && event.tool_result) {
|
if (event && event.tool_result) {
|
||||||
|
if (event.tool_result.sudo_blocked) {
|
||||||
|
setSudoModal({ command: event.tool_result.command || event.tool_result.content })
|
||||||
|
}
|
||||||
const idx = toolCalls.findIndex(tc => tc.call && tc.call.tool_call_id === event.tool_result.tool_call_id)
|
const idx = toolCalls.findIndex(tc => tc.call && tc.call.tool_call_id === event.tool_result.tool_call_id)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
toolCalls[idx] = { ...toolCalls[idx], result: event.tool_result }
|
toolCalls[idx] = { ...toolCalls[idx], result: event.tool_result }
|
||||||
@@ -1091,23 +1165,20 @@ export default function Shell({ api }) {
|
|||||||
return () => window.removeEventListener('ask-ai-terminal', handler)
|
return () => window.removeEventListener('ask-ai-terminal', handler)
|
||||||
}, [_sendAiMessage])
|
}, [_sendAiMessage])
|
||||||
|
|
||||||
const handleAnalyze = async () => {
|
const handleAnalyze = () => {
|
||||||
setAnalyzing(true)
|
_sendAiMessage(`Fais une analyse complète du système. Utilise l'outil terminal pour explorer et rédige un rapport structuré en markdown. Couvre:
|
||||||
setAiMessages(prev => [...prev, { role: 'system', content: 'Analyse du système en cours...' }])
|
|
||||||
try {
|
1. **OS & Matériel** — distrib, kernel, CPU, RAM, GPU, hostname
|
||||||
const d = await api.analyzeSystem()
|
2. **Disque & Partitions** — occupation, points de montage, inodes
|
||||||
if (d.analysis) {
|
3. **Réseau** — interfaces, IP, ports en écoute, DNS, pare-feu, SSH actif ?
|
||||||
setAnalysisContent(d.analysis)
|
4. **Utilisateurs & Sécurité** — utilisateurs, groupes sudo, last logins, fail2ban, règles sudo
|
||||||
localStorage.setItem('shell_analysis', d.analysis)
|
5. **Services & Processus** — systemd actifs, top processus par CPU/RAM, load average, uptime
|
||||||
}
|
6. **Outils installés** — IDE (VSCode, JetBrains...), langages (go, python, node, rust...), gestionnaire de paquets, conteneurs (docker, podman), git, outils CLI
|
||||||
setAiMessages(prev => [...prev.filter(m => m.content !== 'Analyse du système en cours...'), {
|
7. **Environnement utilisateur** — shell, $HOME (arborescence top-level, nombre de fichiers/projects), dotfiles, config notable (.bashrc, .zshrc, starship)
|
||||||
role: 'system',
|
8. **Paquets & Mises à jour** — paquets obsolètes, kernel à jour, security patches
|
||||||
content: 'Analyse système terminée et sauvegardée. Le contexte système est maintenant disponible.'
|
9. **Recommandations** — outils manquants, optimisations, points d'attention
|
||||||
}])
|
|
||||||
} catch (err) {
|
Sois concret : cite les vraies versions, les vrais chemins, les vrais nombres. Le rapport fera office de carte d'identité du système (max ~40k tokens).`, true, true)
|
||||||
setAiMessages(prev => prev.filter(m => m.content !== 'Analyse du système en cours...'))
|
|
||||||
}
|
|
||||||
setAnalyzing(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -1291,7 +1362,37 @@ export default function Shell({ api }) {
|
|||||||
<input
|
<input
|
||||||
value={aiInput}
|
value={aiInput}
|
||||||
onChange={e => setAiInput(e.target.value)}
|
onChange={e => setAiInput(e.target.value)}
|
||||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); handleAiSend() } }}
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); handleAiSend(); return }
|
||||||
|
if (e.key === 'Tab') {
|
||||||
|
e.preventDefault()
|
||||||
|
const val = aiInput
|
||||||
|
const pos = e.target.selectionStart
|
||||||
|
const before = val.slice(0, pos)
|
||||||
|
const afterSlash = before.match(/\/[\w ]*$/)
|
||||||
|
if (afterSlash) {
|
||||||
|
const partial = afterSlash[0]
|
||||||
|
const matches = SHELL_AI_COMMANDS.filter(c => c.startsWith(partial) && c !== partial)
|
||||||
|
if (matches.length >= 1) {
|
||||||
|
let completed = matches[0]
|
||||||
|
for (const m of matches) {
|
||||||
|
while (!m.startsWith(completed)) completed = completed.slice(0, -1)
|
||||||
|
}
|
||||||
|
if (completed === partial && matches.length === 1) completed = matches[0]
|
||||||
|
if (completed.length > partial.length) {
|
||||||
|
const suffix = completed[completed.length - 1] === ' ' ? '' : (matches.length === 1 ? ' ' : '')
|
||||||
|
completed += suffix
|
||||||
|
const newText = val.slice(0, pos - afterSlash[0].length) + completed + val.slice(pos)
|
||||||
|
setAiInput(newText)
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
e.target.selectionStart = e.target.selectionEnd = pos - afterSlash[0].length + completed.length
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}}
|
||||||
placeholder={aiAtLimit ? '/clear pour continuer' : t('shell.askAi')}
|
placeholder={aiAtLimit ? '/clear pour continuer' : t('shell.askAi')}
|
||||||
disabled={aiAtLimit && aiInput !== '/clear'}
|
disabled={aiAtLimit && aiInput !== '/clear'}
|
||||||
/>
|
/>
|
||||||
@@ -1308,7 +1409,12 @@ export default function Shell({ api }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="shell-analysis-modal-body">
|
<div className="shell-analysis-modal-body">
|
||||||
{renderContent(analysisContent).map((part, i) =>
|
{renderContent(analysisContent).map((part, i) =>
|
||||||
part.type === 'code' ? (
|
part.type === 'code' && part.lang === 'mermaid' ? (
|
||||||
|
<div key={i} className="shell-code-block">
|
||||||
|
<div className="shell-code-lang">mermaid</div>
|
||||||
|
<MermaidBlock code={part.content} />
|
||||||
|
</div>
|
||||||
|
) : part.type === 'code' ? (
|
||||||
<div key={i} className="shell-code-block">
|
<div key={i} className="shell-code-block">
|
||||||
{part.lang && <div className="shell-code-lang">{part.lang}</div>}
|
{part.lang && <div className="shell-code-lang">{part.lang}</div>}
|
||||||
<pre><code>{part.content}</code></pre>
|
<pre><code>{part.content}</code></pre>
|
||||||
@@ -1371,6 +1477,22 @@ export default function Shell({ api }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{sudoModal && (
|
||||||
|
<div className="shell-modal-overlay" onClick={() => setSudoModal(null)}>
|
||||||
|
<div className="shell-modal" onClick={e => e.stopPropagation()}>
|
||||||
|
<div className="shell-modal-header">Commande bloquée</div>
|
||||||
|
<div className="shell-modal-body">
|
||||||
|
<p style={{ color: 'var(--accent-bright)', fontWeight: 600, marginBottom: 8 }}>L'IA a tenté d'exécuter une commande nécessitant des privilèges administrateur :</p>
|
||||||
|
<pre style={{ background: 'var(--bg)', padding: '10px 12px', borderRadius: 'var(--radius)', fontSize: 12, overflow: 'auto', fontFamily: 'var(--font-mono)' }}>{sudoModal.command}</pre>
|
||||||
|
<p style={{ color: 'var(--text-secondary)', fontSize: 12, marginTop: 12 }}>La commande a été bloquée. L'IA en a été informée et cherchera une alternative.</p>
|
||||||
|
</div>
|
||||||
|
<div className="shell-modal-footer">
|
||||||
|
<button className="primary" onClick={() => setSudoModal(null)}>Compris</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1409,12 +1531,36 @@ function ShellToolBlock({ call, result }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mermaidIdCounter = 0
|
||||||
|
|
||||||
|
function MermaidBlock({ code }) {
|
||||||
|
const ref = useRef(null)
|
||||||
|
const [svg, setSvg] = useState('')
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
const id = `mermaid-${++mermaidIdCounter}`
|
||||||
|
mermaid.render(id, code).then(({ svg }) => {
|
||||||
|
if (!cancelled) setSvg(svg)
|
||||||
|
}).catch(() => {
|
||||||
|
if (!cancelled) setError(true)
|
||||||
|
})
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [code])
|
||||||
|
|
||||||
|
if (error) return <pre className="shell-mermaid-error">{code}</pre>
|
||||||
|
if (!svg) return <div className="shell-mermaid-loading">Chargement du diagramme...</div>
|
||||||
|
return <div className="shell-mermaid-container" ref={ref} dangerouslySetInnerHTML={{ __html: svg }} />
|
||||||
|
}
|
||||||
|
|
||||||
function ShellAIMessage({ msg, sendToTerminal, terminalTabId }) {
|
function ShellAIMessage({ msg, sendToTerminal, terminalTabId }) {
|
||||||
const role = msg.role === 'user' ? 'user' : msg.role === 'system' ? 'system' : 'assistant'
|
const role = msg.role === 'user' ? 'user' : msg.role === 'system' ? 'system' : 'assistant'
|
||||||
const content = msg.content || ''
|
const content = msg.content || ''
|
||||||
|
const [copiedIdx, setCopiedIdx] = useState(null)
|
||||||
|
|
||||||
if (role === 'user') {
|
if (role === 'user') {
|
||||||
return <div className={`ai-message user`}>{content}</div>
|
return <div className={`ai-message user${msg._analysis ? ' analysis' : ''}`} dangerouslySetInnerHTML={{ __html: formatText(content) }} />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (role === 'system') {
|
if (role === 'system') {
|
||||||
@@ -1426,16 +1572,16 @@ function ShellAIMessage({ msg, sendToTerminal, terminalTabId }) {
|
|||||||
let displayContent = content
|
let displayContent = content
|
||||||
let streamingToolCalls = msg._toolCalls || null
|
let streamingToolCalls = msg._toolCalls || null
|
||||||
|
|
||||||
if (!streamingToolCalls) {
|
try {
|
||||||
try {
|
const parsed = JSON.parse(content)
|
||||||
const parsed = JSON.parse(content)
|
if (parsed && Array.isArray(parsed.tool_calls)) {
|
||||||
if (parsed && Array.isArray(parsed.tool_calls)) {
|
if (!streamingToolCalls) {
|
||||||
parsedToolCalls = parsed.tool_calls
|
parsedToolCalls = parsed.tool_calls
|
||||||
parsedToolResults = parsed.tool_results || null
|
parsedToolResults = parsed.tool_results || null
|
||||||
displayContent = parsed.content || ''
|
|
||||||
}
|
}
|
||||||
} catch {}
|
displayContent = parsed.content || ''
|
||||||
}
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
const parts = renderContent(displayContent)
|
const parts = renderContent(displayContent)
|
||||||
|
|
||||||
@@ -1454,14 +1600,26 @@ function ShellAIMessage({ msg, sendToTerminal, terminalTabId }) {
|
|||||||
return <ShellToolBlock key={tc.tool_call_id || i} call={tc} result={result} />
|
return <ShellToolBlock key={tc.tool_call_id || i} call={tc} result={result} />
|
||||||
})}
|
})}
|
||||||
{parts.map((part, i) => {
|
{parts.map((part, i) => {
|
||||||
|
if (part.type === 'code' && part.lang === 'mermaid') {
|
||||||
|
return (
|
||||||
|
<div key={i} className="shell-code-block">
|
||||||
|
<div className="shell-code-lang">mermaid</div>
|
||||||
|
<MermaidBlock code={part.content} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
if (part.type === 'code') {
|
if (part.type === 'code') {
|
||||||
return (
|
return (
|
||||||
<div key={i} className="shell-code-block">
|
<div key={i} className="shell-code-block">
|
||||||
{part.lang && <div className="shell-code-lang">{part.lang}</div>}
|
{part.lang && <div className="shell-code-lang">{part.lang}</div>}
|
||||||
<pre><code>{part.content}</code></pre>
|
<pre><code>{part.content}</code></pre>
|
||||||
<div className="shell-code-actions">
|
<div className="shell-code-actions">
|
||||||
<button onClick={() => navigator.clipboard.writeText(part.content)} title="Copier">
|
<button className={copiedIdx === i ? 'copied' : ''} onClick={() => {
|
||||||
<Copy size={12} /> Copier
|
navigator.clipboard.writeText(part.content)
|
||||||
|
setCopiedIdx(i)
|
||||||
|
setTimeout(() => setCopiedIdx(null), 1500)
|
||||||
|
}} title="Copier">
|
||||||
|
<Copy size={12} /> {copiedIdx === i ? 'Copié !' : 'Copier'}
|
||||||
</button>
|
</button>
|
||||||
<button onClick={() => sendToTerminal(part.content, terminalTabId)} title="Envoyer au terminal">
|
<button onClick={() => sendToTerminal(part.content, terminalTabId)} title="Envoyer au terminal">
|
||||||
<Send size={12} /> Terminal
|
<Send size={12} /> Terminal
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { useState, useRef, useEffect, useCallback, useMemo } from 'react'
|
import { useState, useRef, useEffect, useCallback, useMemo } from 'react'
|
||||||
import { useI18n } from '../i18n'
|
import { useI18n } from '../i18n'
|
||||||
|
import mermaid from 'mermaid'
|
||||||
|
|
||||||
|
mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose', fontFamily: 'var(--font-mono)' })
|
||||||
|
|
||||||
const RANKS = {
|
const RANKS = {
|
||||||
commandant: { label: 'Commandant', short: 'CDT', color: '#FFD740' },
|
commandant: { label: 'Commandant', short: 'CDT', color: '#FFD740' },
|
||||||
@@ -64,7 +67,16 @@ function renderContent(text) {
|
|||||||
function formatText(text) {
|
function formatText(text) {
|
||||||
let html = text
|
let html = text
|
||||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||||
|
|
||||||
|
html = html.replace(/^(\|.+\|)\n(\|[\s\-:|]+\|)\n((?:\|.+\|\n?)+)/gm, (match, headerRow, sepRow, bodyRows) => {
|
||||||
|
const headers = headerRow.split('|').filter(c => c.trim() !== '').map(c => `<th>${c.trim()}</th>`).join('')
|
||||||
|
const rows = bodyRows.trim().split('\n').map(row => {
|
||||||
|
const cells = row.split('|').filter(c => c.trim() !== '').map(c => `<td>${c.trim()}</td>`).join('')
|
||||||
|
return `<tr>${cells}</tr>`
|
||||||
|
}).join('')
|
||||||
|
return `<table><thead><tr>${headers}</tr></thead><tbody>${rows}</tbody></table>`
|
||||||
|
})
|
||||||
|
|
||||||
html = html
|
html = html
|
||||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
|
.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
|
||||||
@@ -74,15 +86,15 @@ function formatText(text) {
|
|||||||
.replace(/^\s*[-*] (.+)$/gm, '<div class="msg-bullet">• $1</div>')
|
.replace(/^\s*[-*] (.+)$/gm, '<div class="msg-bullet">• $1</div>')
|
||||||
.replace(/^\s*(\d+)[.)] (.+)$/gm, '<div class="msg-step"><span class="msg-step-num">$1</span> $2</div>')
|
.replace(/^\s*(\d+)[.)] (.+)$/gm, '<div class="msg-step"><span class="msg-step-num">$1</span> $2</div>')
|
||||||
.replace(/\n/g, '<br/>')
|
.replace(/\n/g, '<br/>')
|
||||||
|
|
||||||
html = html
|
html = html
|
||||||
.replace(/<br\/>\s*<br\/>/g, '<br/>')
|
.replace(/<br\/>\s*<br\/>/g, '<br/>')
|
||||||
.replace(/<br\/>\s*(<h[234]|<div class="msg-)/g, '$1')
|
.replace(/<br\/>\s*(<h[234]|<div class="msg-|<table)/g, '$1')
|
||||||
.replace(/(<\/h[234]|<\/div>)\s*<br\/>/g, '$1')
|
.replace(/(<\/h[234]|<\/div>|<\/table>)\s*<br\/>/g, '$1')
|
||||||
.replace(/\s+on\w+=["'][^"']*["']/gi, '')
|
.replace(/\s+on\w+=["'][^"']*["']/gi, '')
|
||||||
.replace(/javascript:/gi, '')
|
.replace(/javascript:/gi, '')
|
||||||
.replace(/data:/gi, '')
|
.replace(/data:/gi, '')
|
||||||
|
|
||||||
return html
|
return html
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,10 +180,69 @@ function ToolCallBlock({ call, result }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mermaidIdCounter = 0
|
||||||
|
|
||||||
|
function MermaidBlock({ code }) {
|
||||||
|
const ref = useRef(null)
|
||||||
|
const [svg, setSvg] = useState('')
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
const id = `studio-mermaid-${++mermaidIdCounter}`
|
||||||
|
mermaid.render(id, code).then(({ svg }) => {
|
||||||
|
if (!cancelled) setSvg(svg)
|
||||||
|
}).catch(() => {
|
||||||
|
if (!cancelled) setError(true)
|
||||||
|
})
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [code])
|
||||||
|
|
||||||
|
if (error) return <pre className="studio-mermaid-error">{code}</pre>
|
||||||
|
if (!svg) return <div className="studio-mermaid-loading">Chargement...</div>
|
||||||
|
return <div className="studio-mermaid-container" ref={ref} dangerouslySetInnerHTML={{ __html: svg }} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function CodeBlockWithCopy({ part, index, copiedIdx, setCopiedIdx }) {
|
||||||
|
if (part.lang === 'mermaid') {
|
||||||
|
return (
|
||||||
|
<div className="studio-code-block">
|
||||||
|
<div className="studio-code-header">
|
||||||
|
<span className="studio-code-lang">mermaid</span>
|
||||||
|
<button className={`studio-copy-btn ${copiedIdx === index ? 'copied' : ''}`} onClick={() => {
|
||||||
|
navigator.clipboard.writeText(part.content)
|
||||||
|
setCopiedIdx(index)
|
||||||
|
setTimeout(() => setCopiedIdx(null), 1500)
|
||||||
|
}}>
|
||||||
|
{copiedIdx === index ? 'Copie!' : 'Copier'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<MermaidBlock code={part.content} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="studio-code-block">
|
||||||
|
<div className="studio-code-header">
|
||||||
|
{part.lang && <span className="studio-code-lang">{part.lang}</span>}
|
||||||
|
<button className={`studio-copy-btn ${copiedIdx === index ? 'copied' : ''}`} onClick={() => {
|
||||||
|
navigator.clipboard.writeText(part.content)
|
||||||
|
setCopiedIdx(index)
|
||||||
|
setTimeout(() => setCopiedIdx(null), 1500)
|
||||||
|
}}>
|
||||||
|
{copiedIdx === index ? 'Copie!' : 'Copier'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<pre><code>{part.content}</code></pre>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function FeedItem({ msg }) {
|
function FeedItem({ msg }) {
|
||||||
const isUser = msg.role === 'user'
|
const isUser = msg.role === 'user'
|
||||||
const isSystem = msg.role === 'system'
|
const isSystem = msg.role === 'system'
|
||||||
const rank = getRank(msg.role)
|
const rank = getRank(msg.role)
|
||||||
|
const [copiedIdx, setCopiedIdx] = useState(null)
|
||||||
|
|
||||||
const timeStr = msg.time ? new Date(msg.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''
|
const timeStr = msg.time ? new Date(msg.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''
|
||||||
|
|
||||||
@@ -226,10 +297,7 @@ function FeedItem({ msg }) {
|
|||||||
<div className="feed-content">
|
<div className="feed-content">
|
||||||
{renderContent(cleanContent).map((part, i) =>
|
{renderContent(cleanContent).map((part, i) =>
|
||||||
part.type === 'code' ? (
|
part.type === 'code' ? (
|
||||||
<div key={i} className="studio-code-block">
|
<CodeBlockWithCopy key={i} part={part} index={i} copiedIdx={copiedIdx} setCopiedIdx={setCopiedIdx} />
|
||||||
{part.lang && <div className="studio-code-lang">{part.lang}</div>}
|
|
||||||
<pre><code>{part.content}</code></pre>
|
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<span key={i} dangerouslySetInnerHTML={{ __html: formatText(part.content) }} />
|
<span key={i} dangerouslySetInnerHTML={{ __html: formatText(part.content) }} />
|
||||||
)
|
)
|
||||||
@@ -245,6 +313,7 @@ function StreamingItem({ content, thinking, toolCalls }) {
|
|||||||
const rank = RANKS.general
|
const rank = RANKS.general
|
||||||
const cleanContent = content.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '')
|
const cleanContent = content.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '')
|
||||||
const hasToolCalls = toolCalls && toolCalls.length > 0
|
const hasToolCalls = toolCalls && toolCalls.length > 0
|
||||||
|
const [copiedIdx, setCopiedIdx] = useState(null)
|
||||||
|
|
||||||
const renderedContent = useMemo(() => {
|
const renderedContent = useMemo(() => {
|
||||||
if (!cleanContent) return []
|
if (!cleanContent) return []
|
||||||
@@ -281,10 +350,7 @@ function StreamingItem({ content, thinking, toolCalls }) {
|
|||||||
<div className="feed-content">
|
<div className="feed-content">
|
||||||
{renderedContent.map((part, i) =>
|
{renderedContent.map((part, i) =>
|
||||||
part.type === 'code' ? (
|
part.type === 'code' ? (
|
||||||
<div key={i} className="studio-code-block">
|
<CodeBlockWithCopy key={i} part={part} index={i} copiedIdx={copiedIdx} setCopiedIdx={setCopiedIdx} />
|
||||||
{part.lang && <div className="studio-code-lang">{part.lang}</div>}
|
|
||||||
<pre><code>{part.content}</code></pre>
|
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<span key={i} dangerouslySetInnerHTML={{ __html: formatText(part.content) }} />
|
<span key={i} dangerouslySetInnerHTML={{ __html: formatText(part.content) }} />
|
||||||
)
|
)
|
||||||
@@ -309,6 +375,7 @@ export default function Studio({ api }) {
|
|||||||
const [tokenInfo, setTokenInfo] = useState({ used: 0, max: 100000, summarizeAt: 80000 })
|
const [tokenInfo, setTokenInfo] = useState({ used: 0, max: 100000, summarizeAt: 80000 })
|
||||||
const [contextCollapsed, setContextCollapsed] = useState(false)
|
const [contextCollapsed, setContextCollapsed] = useState(false)
|
||||||
const [messagesCollapsed, setMessagesCollapsed] = useState(false)
|
const [messagesCollapsed, setMessagesCollapsed] = useState(false)
|
||||||
|
const [sudoModal, setSudoModal] = useState(null)
|
||||||
const messagesEnd = useRef(null)
|
const messagesEnd = useRef(null)
|
||||||
const feedRef = useRef(null)
|
const feedRef = useRef(null)
|
||||||
const textareaRef = useRef(null)
|
const textareaRef = useRef(null)
|
||||||
@@ -404,7 +471,7 @@ export default function Studio({ api }) {
|
|||||||
const text = input.trim()
|
const text = input.trim()
|
||||||
setInput('')
|
setInput('')
|
||||||
|
|
||||||
const isSlashCommand = (t) => /^\/(clear|help|summarize|export|model(?:\s+\S+)?|plan\s+.+)$/.test(t)
|
const isSlashCommand = (t) => /^\/(clear|help|summarize|model(?:\s+\S+)?)$/.test(t)
|
||||||
|
|
||||||
if (text.startsWith('/') && !isSlashCommand(text)) {
|
if (text.startsWith('/') && !isSlashCommand(text)) {
|
||||||
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'user', content: text, time: new Date().toISOString() }])
|
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'user', content: text, time: new Date().toISOString() }])
|
||||||
@@ -424,19 +491,8 @@ export default function Studio({ api }) {
|
|||||||
'- `/clear` - Effacer la conversation',
|
'- `/clear` - Effacer la conversation',
|
||||||
'- `/summarize` - Résumer la conversation précédente',
|
'- `/summarize` - Résumer la conversation précédente',
|
||||||
'- `/help` - Afficher cette aide',
|
'- `/help` - Afficher cette aide',
|
||||||
'- `/plan <objectif>` - Demander un plan structuré',
|
|
||||||
'- `/export` - Exporter la conversation en Markdown',
|
|
||||||
'- `/model` - Afficher le provider et modèle actifs',
|
'- `/model` - Afficher le provider et modèle actifs',
|
||||||
'- `/model change` - Basculer entre MiniMax et ZAI',
|
'- `/model change` - Basculer entre MiniMax et MiMo',
|
||||||
'',
|
|
||||||
'## Tools disponibles',
|
|
||||||
'- Terminal - Exécuter des commandes',
|
|
||||||
'- read_file - Lire des fichiers',
|
|
||||||
'- list_files - Lister des fichiers',
|
|
||||||
'- search_files - Rechercher des fichiers',
|
|
||||||
'- grep_content - Rechercher dans le contenu',
|
|
||||||
'- get_config - Lire la configuration',
|
|
||||||
'- web_fetch - Récupérer une page web',
|
|
||||||
].join('\n')
|
].join('\n')
|
||||||
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'assistant', content: helpMsg, time: new Date().toISOString() }])
|
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'assistant', content: helpMsg, time: new Date().toISOString() }])
|
||||||
return
|
return
|
||||||
@@ -481,31 +537,6 @@ export default function Studio({ api }) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (text.startsWith('/plan ')) {
|
|
||||||
const objective = text.slice(6).trim()
|
|
||||||
if (!objective) {
|
|
||||||
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'assistant', content: 'Usage: `/plan <objectif>`\nEx: `/plan créer un fichier de test`', time: new Date().toISOString() }])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setInput(`Crée un plan structuré en étapes numérotées pour: ${objective}. Chaque étape devrait avoir une estimation de complexité et de temps.`)
|
|
||||||
handleSend()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text === '/export') {
|
|
||||||
api.getChatHistory().then(data => {
|
|
||||||
let markdown = '# Conversation Export\n\n'
|
|
||||||
data.messages?.forEach((msg, i) => {
|
|
||||||
const roleLabel = msg.role === 'user' ? '👤' : (msg.role === 'assistant' ? '🤖' : '⚙️')
|
|
||||||
markdown += `## [${i + 1}] ${roleLabel} ${msg.role}\n${msg.content}\n\n---\n\n`
|
|
||||||
})
|
|
||||||
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'assistant', content: 'Conversation exportée:\n```markdown\n' + markdown + '```', time: new Date().toISOString() }])
|
|
||||||
}).catch(() => {
|
|
||||||
setMessages(prev => [...prev, { id: Date.now().toString(), role: 'assistant', content: 'Erreur: impossible d\'exporter la conversation', time: new Date().toISOString() }])
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const userMsg = { id: Date.now().toString(), role: 'user', content: text, time: new Date().toISOString() }
|
const userMsg = { id: Date.now().toString(), role: 'user', content: text, time: new Date().toISOString() }
|
||||||
setMessages(prev => [...prev, userMsg])
|
setMessages(prev => [...prev, userMsg])
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
@@ -537,6 +568,9 @@ export default function Studio({ api }) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (event && event.tool_result) {
|
if (event && event.tool_result) {
|
||||||
|
if (event.tool_result.sudo_blocked) {
|
||||||
|
setSudoModal({ command: event.tool_result.command || event.tool_result.content })
|
||||||
|
}
|
||||||
const idx = toolCalls.findIndex(tc => tc.call && tc.call.tool_call_id === event.tool_result.tool_call_id)
|
const idx = toolCalls.findIndex(tc => tc.call && tc.call.tool_call_id === event.tool_result.tool_call_id)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
toolCalls[idx] = { ...toolCalls[idx], result: event.tool_result }
|
toolCalls[idx] = { ...toolCalls[idx], result: event.tool_result }
|
||||||
@@ -602,7 +636,7 @@ export default function Studio({ api }) {
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const COMMANDS = ['/clear', '/summarize', '/help', '/plan', '/export', '/model', '/model change']
|
const COMMANDS = ['/clear', '/summarize', '/help', '/model', '/model change']
|
||||||
|
|
||||||
const handleKeyDown = (e) => {
|
const handleKeyDown = (e) => {
|
||||||
if (e.key === 'Enter' && !e.shiftKey) {
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
@@ -744,9 +778,25 @@ export default function Studio({ api }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="studio-input-hint">
|
<div className="studio-input-hint">
|
||||||
{t('studio.inputHint')} · /clear /summarize /help /plan /export /model /model change
|
{t('studio.inputHint')} · /clear /summarize /help /model
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{sudoModal && (
|
||||||
|
<div className="shell-modal-overlay" onClick={() => setSudoModal(null)}>
|
||||||
|
<div className="shell-modal" onClick={e => e.stopPropagation()}>
|
||||||
|
<div className="shell-modal-header">Commande bloquée</div>
|
||||||
|
<div className="shell-modal-body">
|
||||||
|
<p style={{ color: 'var(--accent-bright)', fontWeight: 600, marginBottom: 8 }}>L'IA a tenté d'exécuter une commande nécessitant des privilèges administrateur :</p>
|
||||||
|
<pre style={{ background: 'var(--bg)', padding: '10px 12px', borderRadius: 'var(--radius)', fontSize: 12, overflow: 'auto', fontFamily: 'var(--font-mono)' }}>{sudoModal.command}</pre>
|
||||||
|
<p style={{ color: 'var(--text-secondary)', fontSize: 12, marginTop: 12 }}>La commande a été bloquée. L'IA en a été informée et cherchera une alternative.</p>
|
||||||
|
</div>
|
||||||
|
<div className="shell-modal-footer">
|
||||||
|
<button className="primary" onClick={() => setSudoModal(null)}>Compris</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -458,6 +458,8 @@ input::placeholder { color: var(--text-disabled); }
|
|||||||
.shell-ai-token-text { font-size: 10px; font-family: var(--font-mono); color: var(--text-tertiary); white-space: nowrap; }
|
.shell-ai-token-text { font-size: 10px; font-family: var(--font-mono); color: var(--text-tertiary); white-space: nowrap; }
|
||||||
.ai-panel-messages { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
.ai-panel-messages { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||||
.ai-message { padding: 8px 12px; border-radius: var(--radius); font-size: 13px; line-height: 1.5; word-break: break-word; }
|
.ai-message { padding: 8px 12px; border-radius: var(--radius); font-size: 13px; line-height: 1.5; word-break: break-word; }
|
||||||
|
.ai-message.user { background: var(--bg-elevated); border-left: 3px solid var(--accent-bright); color: var(--text-primary); }
|
||||||
|
.ai-message.user.analysis { border-left-color: var(--info); background: color-mix(in srgb, var(--info) 8%, var(--bg-elevated)); }
|
||||||
.ai-message.assistant { background: var(--bg-card); border-left: 3px solid var(--accent); }
|
.ai-message.assistant { background: var(--bg-card); border-left: 3px solid var(--accent); }
|
||||||
.ai-message.system { background: var(--bg-elevated); border-left: 3px solid var(--info); font-style: italic; color: var(--text-tertiary); font-size: 12px; }
|
.ai-message.system { background: var(--bg-elevated); border-left: 3px solid var(--info); font-style: italic; color: var(--text-tertiary); font-size: 12px; }
|
||||||
.ai-message.assistant { background: var(--bg-card); border-left: 3px solid var(--accent); }
|
.ai-message.assistant { background: var(--bg-card); border-left: 3px solid var(--accent); }
|
||||||
@@ -492,6 +494,23 @@ input::placeholder { color: var(--text-disabled); }
|
|||||||
}
|
}
|
||||||
.shell-code-actions button:last-child { border-right: none; }
|
.shell-code-actions button:last-child { border-right: none; }
|
||||||
.shell-code-actions button:hover { background: var(--accent-bg); color: var(--accent); }
|
.shell-code-actions button:hover { background: var(--accent-bg); color: var(--accent); }
|
||||||
|
.shell-code-actions button.copied { background: var(--accent-bg); color: var(--accent); animation: copy-flash 0.3s ease; }
|
||||||
|
|
||||||
|
.shell-mermaid-container { padding: 12px; background: var(--bg); overflow-x: auto; display: flex; justify-content: center; }
|
||||||
|
.shell-mermaid-container svg { max-width: 100%; height: auto; }
|
||||||
|
.shell-mermaid-loading { padding: 16px; text-align: center; color: var(--text-tertiary); font-size: 12px; }
|
||||||
|
.shell-mermaid-error { padding: 10px 12px; color: var(--accent-bright); font-family: var(--font-mono); font-size: 12px; white-space: pre-wrap; }
|
||||||
|
|
||||||
|
.ai-message table { width: 100%; border-collapse: collapse; margin: 6px 0; font-size: 12px; }
|
||||||
|
.ai-message th { background: var(--bg-surface); padding: 6px 10px; text-align: left; font-weight: 600; border: 1px solid var(--border); color: var(--text-secondary); }
|
||||||
|
.ai-message td { padding: 5px 10px; border: 1px solid var(--border); color: var(--text-primary); }
|
||||||
|
.ai-message tr:nth-child(even) td { background: var(--bg-surface); }
|
||||||
|
|
||||||
|
@keyframes copy-flash {
|
||||||
|
0% { transform: scale(1); }
|
||||||
|
50% { transform: scale(1.05); background: color-mix(in srgb, var(--accent) 20%, transparent); }
|
||||||
|
100% { transform: scale(1); }
|
||||||
|
}
|
||||||
|
|
||||||
.shell-analysis-modal {
|
.shell-analysis-modal {
|
||||||
background: var(--bg-elevated); border: 1px solid var(--border);
|
background: var(--bg-elevated); border: 1px solid var(--border);
|
||||||
@@ -720,6 +739,25 @@ input::placeholder { color: var(--text-disabled); }
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Consumption */
|
||||||
|
.dash-consumption-list { display: flex; flex-direction: column; gap: 10px; max-height: 270px; overflow-y: auto; }
|
||||||
|
.dash-consumption-provider { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.dash-consumption-head { display: flex; align-items: center; justify-content: space-between; }
|
||||||
|
.dash-consumption-name {
|
||||||
|
font-size: 11px; font-weight: 700; letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
.dash-consumption-total {
|
||||||
|
font-size: 10px; font-family: var(--font-mono); color: var(--text-tertiary);
|
||||||
|
}
|
||||||
|
.dash-consumption-days {
|
||||||
|
display: flex; gap: 4px; flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.dash-consumption-day {
|
||||||
|
font-size: 9px; font-family: var(--font-mono); color: var(--text-tertiary);
|
||||||
|
background: var(--bg-input); padding: 1px 5px; border-radius: 4px;
|
||||||
|
}
|
||||||
|
.dash-consumption-day strong { color: var(--text-secondary); }
|
||||||
|
|
||||||
/* Processes */
|
/* Processes */
|
||||||
.dash-proc-list { display: flex; flex-direction: column; gap: 4px; max-height: 270px; overflow-y: auto; }
|
.dash-proc-list { display: flex; flex-direction: column; gap: 4px; max-height: 270px; overflow-y: auto; }
|
||||||
.dash-proc-row {
|
.dash-proc-row {
|
||||||
@@ -933,11 +971,33 @@ input::placeholder { color: var(--text-disabled); }
|
|||||||
background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius);
|
background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius);
|
||||||
overflow: hidden; margin: 8px 0;
|
overflow: hidden; margin: 8px 0;
|
||||||
}
|
}
|
||||||
|
.studio-code-header {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
background: var(--bg-surface); border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
.studio-code-block pre { padding: 12px 16px; font-family: var(--font-mono); font-size: 13px; line-height: 1.5; overflow-x: auto; color: var(--text-primary); margin: 0; }
|
.studio-code-block pre { padding: 12px 16px; font-family: var(--font-mono); font-size: 13px; line-height: 1.5; overflow-x: auto; color: var(--text-primary); margin: 0; }
|
||||||
.studio-code-lang {
|
.studio-code-lang {
|
||||||
padding: 4px 12px; font-size: 11px; font-weight: 600; color: var(--text-tertiary);
|
padding: 4px 12px; font-size: 11px; font-weight: 600; color: var(--text-tertiary);
|
||||||
background: var(--bg-surface); border-bottom: 1px solid var(--border); text-transform: uppercase; letter-spacing: 0.5px;
|
background: var(--bg-surface); text-transform: uppercase; letter-spacing: 0.5px;
|
||||||
}
|
}
|
||||||
|
.studio-copy-btn {
|
||||||
|
padding: 3px 10px; font-size: 10px; font-weight: 600; color: var(--text-tertiary);
|
||||||
|
background: transparent; border: none; border-left: 1px solid var(--border);
|
||||||
|
cursor: pointer; transition: all 0.15s; font-family: var(--font-sans);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.studio-copy-btn:hover { background: var(--accent-bg); color: var(--accent); }
|
||||||
|
.studio-copy-btn.copied { background: var(--accent-bg); color: var(--accent); }
|
||||||
|
|
||||||
|
.studio-mermaid-container { padding: 12px; background: var(--bg); overflow-x: auto; display: flex; justify-content: center; }
|
||||||
|
.studio-mermaid-container svg { max-width: 100%; height: auto; }
|
||||||
|
.studio-mermaid-loading { padding: 12px; text-align: center; color: var(--text-tertiary); font-size: 12px; }
|
||||||
|
.studio-mermaid-error { padding: 10px 12px; color: var(--accent-bright); font-family: var(--font-mono); font-size: 12px; white-space: pre-wrap; }
|
||||||
|
|
||||||
|
.feed-content table { width: 100%; border-collapse: collapse; margin: 8px 0; font-size: 13px; }
|
||||||
|
.feed-content th { background: var(--bg-surface); padding: 6px 12px; text-align: left; font-weight: 600; border: 1px solid var(--border); color: var(--text-secondary); }
|
||||||
|
.feed-content td { padding: 5px 12px; border: 1px solid var(--border); color: var(--text-primary); }
|
||||||
|
.feed-content tr:nth-child(even) td { background: var(--bg-surface); }
|
||||||
.inline-code { background: var(--bg-input); padding: 2px 6px; border-radius: 4px; font-family: var(--font-mono); font-size: 13px; color: var(--accent-muted); }
|
.inline-code { background: var(--bg-input); padding: 2px 6px; border-radius: 4px; font-family: var(--font-mono); font-size: 13px; color: var(--accent-muted); }
|
||||||
.msg-h3 { font-size: 16px; font-weight: 700; color: var(--text-primary); margin: 10px 0 4px; display: block; }
|
.msg-h3 { font-size: 16px; font-weight: 700; color: var(--text-primary); margin: 10px 0 4px; display: block; }
|
||||||
.msg-h4 { font-size: 14px; font-weight: 700; color: var(--text-secondary); margin: 8px 0 3px; display: block; }
|
.msg-h4 { font-size: 14px; font-weight: 700; color: var(--text-secondary); margin: 8px 0 3px; display: block; }
|
||||||
|
|||||||
Reference in New Issue
Block a user