Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions _normalize_crlf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build ignore

package main

import (
"bytes"
"fmt"
"os"
)

func main() {
targets := []string{
"internal/tui/tui.go",
"internal/store/store.go",
}
for _, path := range targets {
data, err := os.ReadFile(path)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
n := bytes.Count(data, []byte("\r\n"))
normalized := bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n"))
if err := os.WriteFile(path, normalized, 0o644); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("normalized %d CRLF->LF in %s\n", n, path)
}
}
45 changes: 45 additions & 0 deletions cmd/mimicode/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ func startupChecks(errOut io.Writer) error {
}
if strings.TrimSpace(getenv("ANTHROPIC_API_KEY")) == "" {
fmt.Fprintln(errOut, "mimicode: ANTHROPIC_API_KEY is not set")
fmt.Fprintln(errOut, " set it permanently: mimicode key --set <your-key>")
fmt.Fprintln(errOut, " or for this session: export ANTHROPIC_API_KEY=<your-key>")
return fmt.Errorf("missing ANTHROPIC_API_KEY")
}
return nil
Expand Down Expand Up @@ -201,6 +203,7 @@ func runOneShot(ctx context.Context, sessionID, cwd, prompt string, in io.Reader
printAgentErr(errOut, err)
return 1
}
renameSessionOnce(ctx, sess, prompt, errOut)
if err := sess.SaveMessages(messages); err != nil {
fmt.Fprintf(errOut, "mimicode: save messages: %v\n", err)
return 1
Expand Down Expand Up @@ -313,6 +316,9 @@ func runREPL(ctx context.Context, sessionID, cwd string, in io.Reader, out, errO
}
return 1
}
if turn == 0 {
renameSessionOnce(ctx, sess, prompt, errOut)
}
if saveErr := sess.SaveMessages(messages); saveErr != nil {
fmt.Fprintf(errOut, "mimicode: save messages: %v\n", saveErr)
return 1
Expand Down Expand Up @@ -570,6 +576,45 @@ func extractLastAssistantText(messages []provider.Message) string {
return ""
}

// generateSessionName asks the model for a 3-4 word hyphenated slug relevant
// to the user's first message. Returns fallback unchanged on any error.
func generateSessionName(ctx context.Context, prompt, fallback string) string {
msgs := []provider.Message{{
Role: "user",
Content: []provider.ContentBlock{{Type: "text", Text: prompt}},
}}
sys := "Generate a session name for this conversation. Reply with ONLY a lowercase hyphen-separated slug of 3 to 4 short words (2-5 letters each) that captures the topic. No punctuation, no explanation, nothing else. Examples: fix-auth-bug, add-dark-mode, parse-csv-rows."
msg, _, err := provider.CallClaude(ctx, msgs, sys, nil, provider.ModelHaiku)
if err != nil || len(msg.Content) == 0 {
return fallback
}
name := strings.TrimSpace(msg.Content[0].Text)
name = strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || r == '-' {
return r
}
return -1
}, strings.ToLower(name))
name = strings.Trim(name, "-")
if name == "" {
return fallback
}
return name
}

// renameSessionOnce renames the session directory after the first turn using an
// AI-generated name. Falls back silently to the existing hex ID on any error.
func renameSessionOnce(ctx context.Context, sess *store.Session, prompt string, errOut io.Writer) {
name := generateSessionName(ctx, prompt, sess.ID)
if name == sess.ID {
return
}
if err := sess.Rename(name); err != nil {
return
}
fmt.Fprintf(errOut, "session: %s\n", sess.ID)
}

func rgInstallInstructions() string {
switch runtime.GOOS {
case "windows":
Expand Down
4 changes: 3 additions & 1 deletion install.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ if (-not (Get-Command rg -ErrorAction SilentlyContinue)) {
if (-not $env:ANTHROPIC_API_KEY) {
Write-Host ""
Write-Host "WARN ANTHROPIC_API_KEY not set." -ForegroundColor Yellow
Write-Host " Get a key at https://console.anthropic.com/settings/keys then set it:"
Write-Host " Get a key at https://console.anthropic.com/settings/keys then run:"
Write-Host " mimicode key --set your-key-here"
Write-Host " or set it in your environment:"
Write-Host " setx ANTHROPIC_API_KEY `"your-key-here`""
}

Expand Down
4 changes: 3 additions & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ fi
if [ -z "${ANTHROPIC_API_KEY:-}" ]; then
echo ""
echo "⚠️ ANTHROPIC_API_KEY not set."
echo " Get a key at https://console.anthropic.com/settings/keys then add:"
echo " Get a key at https://console.anthropic.com/settings/keys then run:"
echo " $BINARY_NAME key --set your-key-here"
echo " or set it in your shell:"
echo " export ANTHROPIC_API_KEY=\"your-key-here\""
fi

Expand Down
100 changes: 92 additions & 8 deletions internal/store/store.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package store

import (
"bufio"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"sync"
"time"

Expand Down Expand Up @@ -92,6 +94,81 @@ type entry struct {
Data any `json:"data"`
}

// ── Session browser ──────────────────────────────────────────────────────────

// SessionSummary is a lightweight snapshot of a session used by the browser.
type SessionSummary struct {
ID string
StartedAt time.Time
Model string
CWD string
Preview string // first user message, truncated
}

// ListSessions returns all sessions sorted newest-first.
func ListSessions() ([]SessionSummary, error) {
entries, err := os.ReadDir(sessionsDir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var out []SessionSummary
for _, e := range entries {
if !e.IsDir() {
continue
}
out = append(out, summarizeSession(filepath.Join(sessionsDir, e.Name()), e.Name()))
}
sort.Slice(out, func(i, j int) bool {
return out[i].StartedAt.After(out[j].StartedAt)
})
return out, nil
}

func summarizeSession(dir, id string) SessionSummary {
s := SessionSummary{ID: id}
if info, err := os.Stat(dir); err == nil {
s.StartedAt = info.ModTime()
}
f, err := os.Open(filepath.Join(dir, "events.jsonl"))
if err != nil {
return s
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
var e entry
if json.Unmarshal(sc.Bytes(), &e) != nil {
continue
}
m, _ := e.Data.(map[string]any)
if m == nil {
continue
}
switch e.Kind {
case "session_start":
s.Model, _ = m["model"].(string)
s.CWD, _ = m["cwd"].(string)
case "user":
if s.Preview == "" {
text, _ := m["text"].(string)
if text != "" {
runes := []rune(text)
if len(runes) > 80 {
runes = runes[:80]
s.Preview = string(runes) + "\u2026"
} else {
s.Preview = text
}
}
}
}
}
return s
}

// ── Lifecycle ─────────────────────────────────────────────────────────────────

func New(id, cwd, model string) (*Session, error) {
Expand Down Expand Up @@ -159,6 +236,21 @@ func (s *Session) Close() {
// Path returns the session directory (all session files live here).
func (s *Session) Path() string { return s.dir }

// Rename renames the session directory to newID and updates the session ID and
// dir path. The open file handle inside the directory remains valid after the
// rename on all supported platforms.
func (s *Session) Rename(newID string) error {
s.mu.Lock()
defer s.mu.Unlock()
newDir := filepath.Join(sessionsDir, newID)
if err := os.Rename(s.dir, newDir); err != nil {
return fmt.Errorf("store: rename session: %w", err)
}
s.ID = newID
s.dir = newDir
return nil
}

// ── Event logging ─────────────────────────────────────────────────────────────

// LogUser logs a user message and returns the turn number (1-based).
Expand Down Expand Up @@ -240,11 +332,3 @@ func (s *Session) LoadMessages() ([]provider.Message, error) {
}
return messages, nil
}

func (s *Session) MessagesCount() int {
msgs, err := s.LoadMessages()
if err != nil {
return 0
}
return len(msgs)
}
Loading
Loading