Skip to content

feat(history): each subagent gets its own history file - #711

Merged
edenreich merged 4 commits into
mainfrom
feat/per-subagent-history-files
Jul 2, 2026
Merged

edenreich merged 4 commits into
mainfrom
feat/per-subagent-history-files

Conversation

@edenreich

@edenreich edenreich commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #699 — each interactive subagent now gets its own history file in a dedicated history/ subdirectory, so subagent prompts no longer pollute the main agent's history when navigating with arrow keys.

Scope: this applies to interactive (tmux) subagents, which run an infer chat TUI with input history. Headless subagents have no TUI input history, so they are intentionally unaffected.

Changes

  • Main agent: <configDir>/history/history
  • Labeled subagents: <configDir>/history/history-<name> (e.g. history-refactor, history-research). The label is slugified (lowercased, dashcased, path-safe) before it is used as a filename.
  • Unlabeled subagents: in-memory history only (no file), so we don't create a new single-use history file on every spawn.

Files

File Change
internal/ui/history/shell_history.go Added NewShellHistoryWithName(configDir, name) — creates history/history (main) or history/history-<name> (subagent). Removed legacy NewShellHistoryWithDir.
internal/ui/history/history_manager.go Added NewHistoryManagerWithName(maxInMemory, configDir, name). Removed legacy NewHistoryManagerWithDir.
internal/ui/components/input_view.go Added NewInputViewWithName(modelService, configDir, name); the :memory: sentinel selects in-memory history. Removed legacy NewInputViewWithConfigDir.
internal/ui/components/factory/factory.go Added CreateInputViewWithName(modelService, configDir, name). Removed legacy CreateInputViewWithConfigDir.
internal/app/chat.go Updated caller to use CreateInputViewWithName.
internal/agent/tools/agent.go Slugify spec.Label (via sanitizeSlug) before using it as the history name; unlabeled subagents get the memory-only sentinel instead of the per-spawn session id.
internal/domain/subagent.go Added the SubagentHistoryMemoryOnly sentinel value for INFER_SUBAGENT_HISTORY_NAME.
internal/ui/history/shell_history_test.go Updated expected paths to .infer/history/history; added TestNewShellHistoryWithName.
internal/ui/history/history_manager_test.go Updated test setup to create history/ subdirectory.
internal/agent/tools/agent_test.go Added TestBuildChatPaneCommand_SlugifiesHistoryName.
internal/ui/components/input_view_test.go Added TestNewInputViewWithName_HistorySelection.

Acceptance Criteria

  • Each subagent gets their own history file
  • History gets a dedicated directory so multiple history files could be stored
  • The main agent is reading from <userspace config dir>/history/history
  • The subagents are reading from <userspace config dir>/history/history-<subagent name dashcase>
  • Tests are adjusted / added (if applicable)
  • Documentation are adjusted / added (if applicable)

Each subagent now gets its own history file in a dedicated history/
subdirectory, so subagent prompts no longer pollute the main agent's
history when navigating with arrow keys.

- Main agent: <configDir>/history/history
- Subagents:  <configDir>/history/history-<name>

Adds NewShellHistoryWithName, NewHistoryManagerWithName,
NewInputViewWithName, and CreateInputViewWithName — all accepting
an optional name parameter. Legacy WithDir variants removed.

Closes #699
@edenreich
edenreich requested a review from a team as a code owner July 1, 2026 22:26
When interactive subagents are launched via the Agent tool, they run
`infer chat` in a tmux pane. Previously, the spawned `infer chat`
created its input view with an empty name, causing the subagent's
prompts (task descriptions typed into the subagent's TUI) to be
written to the main agent's history file at <configDir>/history/history.

This fix:

1. Adds INFER_SUBAGENT_HISTORY_NAME env var constant (subagent.go)
2. Sets this env var in buildChatPaneCommand (agent.go) using the
   subagent's label or session ID
3. Reads this env var in NewChatApplication (chat.go) and passes it
   to CreateInputViewWithName

Now interactive subagents write to their own history files at:
  <configDir>/history/history-<label>
  <configDir>/history/history-<sessionID>

Fixes #699
@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Can you review this?

@edenreich edenreich added this to 2026 Jul 1, 2026
@edenreich edenreich moved this to QA in 2026 Jul 1, 2026
@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 4m 14s —— View job


Review: per-subagent history files

  • Read the changed files and understand the diff
  • Check history file path logic (main vs subagent)
  • Check naming / dashcase handling for subagent names
  • Check callers are wired correctly
  • Review tests
  • Post review feedback

Nice, focused change - the constructor refactor is clean, the legacy WithDir constructors are fully replaced, and backward-compat defaults (configDir==""→.infer, name==""→main history) are handled correctly. Reading INFER_SUBAGENT_HISTORY_NAME in chat.go (the TUI entry) is the right layer, since only interactive subagents run a chat TUI with an input history. Tests pass locally (go test ./internal/ui/history/...).

A few things worth addressing before merge:


🔴 1. The subagent label is used raw as a filename - not slugified (internal/agent/tools/agent.go:440)

The acceptance criteria says subagents read from history/history-<subagent name **dashcase**>, but the implementation uses spec.Label verbatim:

historyName := spec.Label
if historyName == "" {
    historyName = sessionID
}
parts = append(parts, domain.EnvSubagentHistoryName+"="+shellQuote(historyName))

spec.Label comes straight from the LLM tool call (optionalString(m, "label")) with no normalization. It flows through the env var into NewShellHistoryWithName → filepath.Join(historyDir, "history-"+name), where it becomes a path component. Consequences:

  • A label like Refactor Auth → file history-Refactor Auth (space in the name, not dashcase - contradicts the stated criteria).
  • A label containing / → history/history-foo/bar creates a nested directory.
  • A crafted label with embedded .. (e.g. a/../../../tmp/pwned) escapes the history/ dir - filepath.Join(".infer/history", "history-a/../../../tmp/pwned") cleans to tmp/pwned, and SaveToHistory does os.MkdirAll(filepath.Dir(...)), so it'll happily write there. (The leading-.. case is defused by the history- prefix, but embedded .. after a / is not.) Same-user, so not a privilege issue, but history should never land outside history/.

shellQuote protects the tmux command from shell injection, but it does not sanitize the value as a path - the receiving side gets the raw label.

The repo already has two slugifiers to reuse: sanitizeSlug (internal/agent/tools/memory.go:366) and slugifyTitle (internal/agent/tools/request_plan_approval.go:301). Running the label through one of these gives you the intended history-refactor-auth and eliminates the traversal/whitespace cases in one line.

Fix this →


🟡 2. Unlabeled subagents create a new single-use history file on every spawn (internal/agent/tools/agent.go:441-443)

When spec.Label == "", the fallback is historyName = sessionID, and sessionID is subagent-<parent>-<uuid> with a fresh UUID per spawn (newSubagentSessionID). So every unlabeled interactive subagent writes to a brand-new history/history-subagent-…-<uuid> file that is never reused and never cleaned up. Over time the history/ directory fills with orphaned single-use files (and the filenames are unwieldy).

An unlabeled subagent arguably doesn't need persistent history at all. Consider falling back to NewMemoryOnlyHistoryManager (which the input view already uses on error) or a single shared history-subagent file rather than a per-session file.

Fix this →


🟢 3. Only interactive subagents are wired (clarification, not a bug)

EnvSubagentHistoryName is set only in buildChatPaneCommand (interactive/tmux path); subagentExtraEnv (headless) does not set it. That's correct - headless infer agent subagents have no TUI input history to pollute - but the PR title "each subagent gets its own history file" slightly overstates the scope. A one-line note in the PR body that this applies to interactive subagents would avoid confusion.


🟢 4. No test covers the new name branch

The updated tests only exercise the main path (history/history). There's no test asserting NewShellHistoryWithName(dir, "refactor") → history/history-refactor, nor one for the buildChatPaneCommand env wiring. Both are cheap and would lock in the (soon-to-be-slugified) behavior.

Fix this →


Nit

  • shell_history_test.go Save/Load subtests still build paths like tempDir/.infer/history (a file directly under .infer). Harmless since they inject historyFile directly, but the names no longer mirror the real history/history layout - could be renamed for clarity.

Verdict: Solid refactor; the wiring and defaults are right. The main thing to fix is #1 (slugify the label - it's both a correctness gap vs. the stated criteria and a path-safety issue), with #2 worth a quick decision. Everything else is minor.
· feat/per-subagent-history-files

Run the LLM-supplied subagent label through sanitizeSlug before using it as a history filename, so labels like "Refactor Auth" become dashcase and crafted labels (embedded ../) can no longer create malformed or directory-traversing files. Unlabeled subagents now use in-memory history (via the :memory: sentinel) instead of a per-spawn session-id file that left orphans in history/.
@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Is it ready for merge now? are all the issues addressed?

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 4m 47s —— View job


PR readiness check

Verified the current branch state against the earlier review. All previously-raised items are addressed, tests pass (go test ./internal/ui/history/... ./internal/ui/components/... ./internal/agent/tools/... → ok), and go build ./... is clean.

Are the review issues addressed? Yes - all of them

# Issue Status
🔴 1 Slugify the label ✅ agent.go:440 now uses sanitizeSlug(spec.Label). Refactor Auth → refactor-auth, a/../../../tmp/pwned → a-tmp-pwned. No separators/dots/traversal reach the path. Covered by TestBuildChatPaneCommand_SlugifiesHistoryName.
🟡 2 Per-spawn history files for unlabeled subagents ✅ Empty/unusable label → domain.SubagentHistoryMemoryOnly (:memory:) → NewMemoryOnlyHistoryManager (no file). Sentinel can't collide with a slug (contains :). Covered by the same test + TestNewInputViewWithName_HistorySelection.
🟢 3 Scope clarification ✅ PR body now carries the "interactive (tmux) subagents" scope note.
🟢 4 No test for the name branch ✅ Added TestNewShellHistoryWithName, TestNewInputViewWithName_HistorySelection, TestBuildChatPaneCommand_SlugifiesHistoryName.
Nit Test path naming ✅ Save/Load subtests now use history/history, history/history-append, history/history-empty - mirror the real layout.

The legacy WithDir/WithConfigDir constructors are fully removed with no stale callers, and the env var is read at the right layer (chat.go:226, the TUI entry).

One thing to decide before merge (new - not in the earlier review)

🟡 Existing users lose their history and silently stop persisting it. The main history file moved from <configDir>/history (a file) to <configDir>/history/history (a file inside a new history/ directory). There's no migration. For anyone who has run infer chat before this change (they have a .infer/history file on disk):

  1. Old history is orphaned - LoadHistory() opens the new history/history path, doesn't find it, returns empty. Up-arrow shows nothing.
  2. New history won't save - SaveToHistory() calls os.MkdirAll(<configDir>/history), which fails with ENOTDIR because <configDir>/history already exists as a file. The error is logged as a warning (history_manager.go:90) and swallowed, so history silently stops persisting until the user manually rm ~/.infer/history.

It's not data loss (the old file is preserved) and it doesn't crash, but it's a backward-compat regression for existing users. Options: a small one-time migration in NewShellHistoryWithName (if <configDir>/history is a regular file, move it to <configDir>/history/history before creating the dir), or at minimum a changelog/upgrade note.

Fix this →

Verdict

The three review issues (and the nit) that were flagged are all correctly resolved - the slugify fix in particular closes both the dashcase-criteria gap and the path-traversal concern. Functionally the PR is solid and merge-ready on its own terms.

The only thing I'd weigh is the migration edge case above. If the maintainer considers the personal history file low-stakes (degrades to a logged warning, easy manual fix), this can merge as-is with an upgrade note. If existing-user continuity matters, a ~10-line migration would close it cleanly. Your call.

--- · feat/per-subagent-history-files

@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Is it ready for merge now?

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 4m 2s —— View job


Merge readiness check

Yes - it's ready to merge. ✅

The last open item from the previous review (the backward-compat migration) has since been addressed by commit a81c9e7, and it's done well. Everything checks out:

Area Status
🔴 #1 Slugify label ✅ agent.go:440 uses sanitizeSlug(spec.Label). sanitizeSlug collapses non-alphanumerics to -, so spaces///.. can't reach the path.
🟡 #2 Per-spawn history files ✅ Empty/unusable label → SubagentHistoryMemoryOnly (:memory:) → NewMemoryOnlyHistoryManager (no file). sanitizeSlug strips :, so it can never collide with the sentinel.
🟢 #3 Scope note ✅ PR body carries the interactive/tmux scope note.
🟢 #4 Tests for name branch ✅ TestNewShellHistoryWithName, TestNewInputViewWithName_HistorySelection, TestBuildChatPaneCommand_SlugifiesHistoryName.
🟡 Migration (2nd review) ✅ New in a81c9e7 - see below.
Build ✅ go build ./... clean
Tests ✅ history, components, factory, agent/tools, domain all pass
Vet ✅ clean

The migration (a81c9e7) is correct

migrateLegacyMainHistory (shell_history.go:63) does a stage-then-swap with rollback, which is the right shape:

  1. os.Stat(<configDir>/history) - no-op if absent (fresh install) or already a directory (already migrated).
  2. If it's a regular file (legacy layout): rename it aside to history.migrating, MkdirAll the history/ dir (rolling the rename back on failure), then rename the staged file into history/history.

Old history is preserved, and the ENOTDIR failure the second review flagged is gone. Test coverage is thorough: migration happens + content preserved + Load/Save work afterward + staged temp file is cleaned up (TestNewShellHistoryWithName_MigratesLegacyMainHistory), no-op when the dir already exists (..._NoMigrationWhenDirExists), and a subagent spawn still migrates the main file (..._MigrationIsNameAgnostic). Since the migration is transparent and the commit is feat(history):, semantic-release will surface it in the changelog on its own - no separate upgrade note needed.

One non-blocking nit (your call, not a blocker)

There's a narrow first-run concurrency window in migrateLegacyMainHistory: if two infer chat processes start in the same instant on a not-yet-migrated install, one migrates and the other logs a harmless could not migrate legacy history file warning; in the worst case a line or two of brand-new history written in that millisecond could be overwritten by the (more valuable) legacy content. For a personal shell-history file this is entirely acceptable - I'd merge as-is. If you ever want to close it, guarding the stage-rename with os.OpenFile(..., O_CREATE|O_EXCL) as a lock would do it, but it's not worth holding the PR.

Verdict: merge-ready. All four original review items and the migration edge case are resolved, with tests locking in each one; build/test/vet are green.
· feat/per-subagent-history-files

@edenreich
edenreich merged commit 16c8fa1 into main Jul 2, 2026
1 check passed
@edenreich
edenreich deleted the feat/per-subagent-history-files branch July 2, 2026 08:54
inference-gateway-releaser Bot added a commit that referenced this pull request Jul 2, 2026
## [0.127.0](v0.126.0...v0.127.0) (2026-07-02)

### 🚀 Features

* **plan:** compact context and start a fresh session when a plan is approved ([#705](#705)) ([28ddba7](28ddba7))
* **memory:** configurable git sync backend ([#707](#707)) ([6a68c3d](6a68c3d)), closes [#670](#670) [#670](#670)
* **history:** each subagent gets its own history file ([#711](#711)) ([16c8fa1](16c8fa1)), closes [#699](#699)

### 🐛 Bug Fixes

* **plan:** accepting a plan switches to auto-accept mode by default ([#714](#714)) ([7b0befc](7b0befc)), closes [#710](#710)
* **tools:** guard concurrent gitignore and screenshot caches ([#713](#713)) ([0ff4276](0ff4276)), closes [#712](#712)
* **tools:** guard Registry.tools with RWMutex against concurrent MCP registration ([#709](#709)) ([8a70871](8a70871)), closes [#708](#708)
* **ui:** update dim color from [#565f89](https://github.com/inference-gateway/cli/issues/565f89) to [#7a7f9a](https://github.com/inference-gateway/cli/issues/7a7f9a) for improved contrast ([#706](#706)) ([b2ee67e](b2ee67e))

### 🔧 Build System

* **deps:** bump github.com/go-telegram/bot from 1.21.0 to 1.22.0 in the gomod group ([#703](#703)) ([3de5136](3de5136))
* **deps:** bump the github-actions group with 5 updates ([#704](#704)) ([80221f7](80221f7))
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.127.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jul 2, 2026
@edenreich edenreich moved this from QA to Done in 2026 Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

[FEATURE] Each subagent gets its own history file

1 participant