@@ -22,6 +22,7 @@ import { MAIN_TOKENS } from "../../di/tokens";
2222import { logger } from "../../utils/logger" ;
2323import { TypedEventEmitter } from "../../utils/typed-event-emitter" ;
2424import { deriveWorktreePath } from "../../utils/worktree-helpers" ;
25+ import { AgentServiceEvent } from "../agent/schemas" ;
2526import type { AgentService } from "../agent/service" ;
2627import { FileWatcherEvent } from "../file-watcher/schemas" ;
2728import type { FileWatcherService } from "../file-watcher/service" ;
@@ -237,6 +238,11 @@ export class WorkspaceService extends TypedEventEmitter<WorkspaceServiceEvents>
237238 this . handleFocusBranchRenamed . bind ( this ) ,
238239 ) ;
239240
241+ this . agentService . on (
242+ AgentServiceEvent . AgentFileActivity ,
243+ this . handleAgentFileActivity . bind ( this ) ,
244+ ) ;
245+
240246 log . info ( "Branch watcher initialized" ) ;
241247 }
242248
@@ -310,6 +316,35 @@ export class WorkspaceService extends TypedEventEmitter<WorkspaceServiceEvents>
310316 }
311317 }
312318
319+ private async handleAgentFileActivity ( {
320+ taskId,
321+ branchName,
322+ } : {
323+ taskId : string ;
324+ branchName : string | null ;
325+ } ) : Promise < void > {
326+ if ( ! branchName ) return ;
327+
328+ const dbRow = this . workspaceRepo . findByTaskId ( taskId ) ;
329+ if ( ! dbRow || dbRow . mode !== "local" ) return ;
330+ if ( ! dbRow . repositoryId ) return ;
331+
332+ const folderPath = this . getFolderPath ( dbRow . repositoryId ) ;
333+ if ( ! folderPath ) return ;
334+
335+ try {
336+ const defaultBranch = await getDefaultBranch ( folderPath ) ;
337+ if ( branchName === defaultBranch ) return ;
338+ } catch {
339+ // If we can't determine the default branch, still allow linking
340+ }
341+
342+ const currentLinked = dbRow . linkedBranch ?? null ;
343+ if ( currentLinked === branchName ) return ;
344+
345+ this . linkBranch ( taskId , branchName ) ;
346+ }
347+
313348 private updateAssociationBranchName (
314349 _taskId : string ,
315350 _branchName : string ,
0 commit comments