File size: 5,445 Bytes
84aa3bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {
  getCheckpointInfoList,
  getToolCallDataSchema,
  isNodeError,
  performRestore,
} from '@google/gemini-cli-core';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import type {
  Command,
  CommandContext,
  CommandExecutionResponse,
} from './types.js';

export class RestoreCommand implements Command {
  readonly name = 'restore';
  readonly description =
    'Restore to a previous checkpoint, or list available checkpoints to restore. This will reset the conversation and file history to the state it was in when the checkpoint was created';
  readonly requiresWorkspace = true;
  readonly subCommands = [new ListCheckpointsCommand()];

  async execute(
    context: CommandContext,
    args: string[],
  ): Promise<CommandExecutionResponse> {
    const { agentContext: agentContext, git: gitService } = context;
    const { config } = agentContext;
    const argsStr = args.join(' ');

    try {
      if (!argsStr) {
        return await new ListCheckpointsCommand().execute(context);
      }

      if (!config.getCheckpointingEnabled()) {
        return {
          name: this.name,
          data: 'Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore.',
        };
      }

      const selectedFile = argsStr.endsWith('.json')
        ? argsStr
        : `${argsStr}.json`;

      const checkpointDir = config.storage.getProjectTempCheckpointsDir();
      const filePath = path.join(checkpointDir, selectedFile);

      let data: string;
      try {
        data = await fs.readFile(filePath, 'utf-8');
      } catch (error) {
        if (isNodeError(error) && error.code === 'ENOENT') {
          return {
            name: this.name,
            data: `File not found: ${selectedFile}`,
          };
        }
        throw error;
      }

      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      const toolCallData = JSON.parse(data);
      const ToolCallDataSchema = getToolCallDataSchema();
      const parseResult = ToolCallDataSchema.safeParse(toolCallData);

      if (!parseResult.success) {
        return {
          name: this.name,
          data: 'Checkpoint file is invalid or corrupted.',
        };
      }

      const restoreResultGenerator = performRestore(
        parseResult.data,
        gitService,
      );

      const restoreResult = [];
      for await (const result of restoreResultGenerator) {
        restoreResult.push(result);
      }

      // Format the result nicely since Zed just dumps data
      const formattedResult = restoreResult
        .map((r) => {
          if (r.type === 'message') {
            return `[${r.messageType.toUpperCase()}] ${r.content}`;
          } else if (r.type === 'load_history') {
            return `Loaded history with ${r.clientHistory.length} messages.`;
          }
          return `Restored: ${JSON.stringify(r)}`;
        })
        .join('\n');

      return {
        name: this.name,
        data: formattedResult,
      };
    } catch (error) {
      return {
        name: this.name,
        data: `An unexpected error occurred during restore: ${error}`,
      };
    }
  }
}

export class ListCheckpointsCommand implements Command {
  readonly name = 'restore list';
  readonly description = 'Lists all available checkpoints.';

  async execute(context: CommandContext): Promise<CommandExecutionResponse> {
    const { config } = context.agentContext;

    try {
      if (!config.getCheckpointingEnabled()) {
        return {
          name: this.name,
          data: 'Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore.',
        };
      }

      const checkpointDir = config.storage.getProjectTempCheckpointsDir();
      try {
        await fs.mkdir(checkpointDir, { recursive: true });
      } catch {
        // Ignore
      }

      const files = await fs.readdir(checkpointDir);
      const jsonFiles = files.filter((file) => file.endsWith('.json'));

      if (jsonFiles.length === 0) {
        return { name: this.name, data: 'No checkpoints found.' };
      }

      const checkpointFiles = new Map<string, string>();
      for (const file of jsonFiles) {
        const filePath = path.join(checkpointDir, file);
        const data = await fs.readFile(filePath, 'utf-8');
        checkpointFiles.set(file, data);
      }

      const checkpointInfoList = getCheckpointInfoList(checkpointFiles);

      const formatted = checkpointInfoList
        .map((info) => {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const i = info as Record<string, any>;
          const fileName = String(i['fileName'] || 'Unknown');
          const toolName = String(i['toolName'] || 'Unknown');
          const status = String(i['status'] || 'Unknown');
          const timestamp = new Date(
            Number(i['timestamp']) || 0,
          ).toLocaleString();

          return `- **${fileName}**: ${toolName} (Status: ${status}) [${timestamp}]`;
        })
        .join('\n');

      return {
        name: this.name,
        data: `Available Checkpoints:\n${formatted}`,
      };
    } catch {
      return {
        name: this.name,
        data: 'An unexpected error occurred while listing checkpoints.',
      };
    }
  }
}