Skip to content

Commit fdccb46

Browse files
committed
simplify context passing
1 parent 5100c98 commit fdccb46

16 files changed

+119
-119
lines changed

rplugin/node/magenta/src/anthropic.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import Anthropic from "@anthropic-ai/sdk";
2-
import { Logger } from "./logger.ts";
2+
import { context } from "./context.ts";
33
import { TOOL_SPECS, ToolRequest } from "./tools/toolManager.ts";
44

55
export class AnthropicClient {
66
private client: Anthropic;
77

8-
constructor(private logger: Logger) {
8+
constructor() {
99
const apiKey = process.env.ANTHROPIC_API_KEY;
1010

1111
if (!apiKey) {
@@ -21,7 +21,7 @@ export class AnthropicClient {
2121
messages: Array<Anthropic.MessageParam>,
2222
onText: (text: string) => void,
2323
): Promise<ToolRequest[]> {
24-
this.logger.trace(
24+
context.logger.trace(
2525
`initializing stream with messages: ${JSON.stringify(messages, null, 2)}`,
2626
);
2727
const buf: string[] = [];
@@ -60,14 +60,14 @@ export class AnthropicClient {
6060
flushBuffer();
6161
})
6262
.on("inputJson", (_delta, snapshot) => {
63-
this.logger.debug(`inputJson: ${JSON.stringify(snapshot)}`);
63+
context.logger.debug(`inputJson: ${JSON.stringify(snapshot)}`);
6464
});
6565

6666
const response = await stream.finalMessage();
6767
const toolRequests = response.content.filter(
6868
(c): c is ToolRequest => c.type == "tool_use",
6969
);
70-
this.logger.debug("toolRequests: " + JSON.stringify(toolRequests));
70+
context.logger.debug("toolRequests: " + JSON.stringify(toolRequests));
7171
return toolRequests;
7272
}
7373
}

rplugin/node/magenta/src/types.ts rplugin/node/magenta/src/context.ts

+7
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,10 @@ export type Context = {
55
nvim: Neovim;
66
logger: Logger;
77
};
8+
/** Should be called first
9+
*/
10+
export function setContext(c: Context) {
11+
context = c;
12+
}
13+
14+
export let context: Context;

rplugin/node/magenta/src/debug/call-anthropic.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { AnthropicClient } from "../anthropic.ts";
22
import { Logger } from "../logger.ts";
3+
import { setContext } from "../context.ts";
4+
import { Neovim } from "neovim";
35

46
const logger = new Logger(
57
{
@@ -12,8 +14,13 @@ const logger = new Logger(
1214
},
1315
);
1416

17+
setContext({
18+
nvim: undefined as unknown as Neovim,
19+
logger,
20+
});
21+
1522
async function run() {
16-
const client = new AnthropicClient(logger);
23+
const client = new AnthropicClient();
1724

1825
await client.sendMessage(
1926
[
@@ -23,7 +30,7 @@ async function run() {
2330
},
2431
],
2532
(text) => {
26-
return Promise.resolve(console.log("text: " + text));
33+
console.log("text: " + text);
2734
},
2835
);
2936
}

rplugin/node/magenta/src/magenta.ts

+18-16
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,32 @@ import { NvimPlugin } from "neovim";
33
import { Sidebar } from "./sidebar.ts";
44
import * as Chat from "./chat/chat.ts";
55
import { Logger } from "./logger.ts";
6-
import { Context } from "./types.ts";
76
import { App, createApp } from "./tea/tea.ts";
87
import * as ToolManager from "./tools/toolManager.ts";
98
import { d } from "./tea/view.ts";
9+
import { setContext, context } from "./context.ts";
1010

1111
class Magenta {
1212
private anthropicClient: AnthropicClient;
1313
private sidebar: Sidebar;
1414
private chat: App<Chat.Msg, Chat.Model>;
1515
private toolManager: App<ToolManager.Msg, ToolManager.Model>;
1616

17-
constructor(private context: Context) {
18-
this.context.logger.debug(`Initializing plugin`);
19-
this.anthropicClient = new AnthropicClient(this.context.logger);
20-
this.sidebar = new Sidebar(this.context.nvim, this.context.logger);
17+
constructor() {
18+
context.logger.debug(`Initializing plugin`);
19+
this.anthropicClient = new AnthropicClient();
20+
this.sidebar = new Sidebar();
2121

2222
this.chat = createApp({
2323
initialModel: { messages: [] },
2424
update: Chat.update,
2525
View: Chat.view,
26-
context,
2726
});
2827

2928
this.toolManager = createApp({
3029
initialModel: ToolManager.initModel(),
3130
update: ToolManager.update,
3231
View: () => d``,
33-
context,
3432
onUpdate: (msg, model) => {
3533
if (msg.type == "tool-msg") {
3634
if (msg.msg.msg.type == "finish") {
@@ -53,7 +51,7 @@ class Magenta {
5351

5452
if (shouldRespond) {
5553
this.sendMessage().catch((err) =>
56-
this.context.logger.error(err as Error),
54+
context.logger.error(err as Error),
5755
);
5856
}
5957
}
@@ -64,26 +62,25 @@ class Magenta {
6462
}
6563

6664
async command(args: string[]): Promise<void> {
67-
this.context.logger.debug(`Received command ${args[0]}`);
65+
context.logger.debug(`Received command ${args[0]}`);
6866
switch (args[0]) {
6967
case "toggle": {
7068
const buffers = await this.sidebar.toggle();
7169
if (buffers) {
7270
await this.chat.mount({
73-
nvim: this.context.nvim,
7471
buffer: buffers.displayBuffer,
7572
startPos: { row: 0, col: 0 },
7673
endPos: { row: 0, col: 0 },
7774
});
78-
this.context.logger.trace(`Chat rendered.`);
75+
context.logger.trace(`Chat rendered.`);
7976
}
8077

8178
break;
8279
}
8380

8481
case "send": {
8582
const message = await this.sidebar.getMessage();
86-
this.context.logger.trace(`current message: ${message}`);
83+
context.logger.trace(`current message: ${message}`);
8784
if (!message) return;
8885

8986
this.chat.dispatch({
@@ -101,14 +98,14 @@ class Magenta {
10198
break;
10299

103100
default:
104-
this.context.logger.error(`Unrecognized command ${args[0]}\n`);
101+
context.logger.error(`Unrecognized command ${args[0]}\n`);
105102
}
106103
}
107104

108105
private async sendMessage() {
109106
const state = this.chat.getState();
110107
if (state.status != "running") {
111-
this.context.logger.error(`chat is not running.`);
108+
context.logger.error(`chat is not running.`);
112109
return;
113110
}
114111

@@ -117,7 +114,7 @@ class Magenta {
117114
const toolRequests = await this.anthropicClient.sendMessage(
118115
messages,
119116
(text) => {
120-
this.context.logger.trace(`stream received text ${text}`);
117+
context.logger.trace(`stream received text ${text}`);
121118
this.chat.dispatch({
122119
type: "stream-response",
123120
text,
@@ -148,13 +145,18 @@ module.exports = (plugin: NvimPlugin) => {
148145

149146
if (!init) {
150147
const logger = new Logger(plugin.nvim, { level: "trace" });
148+
setContext({
149+
nvim: plugin.nvim,
150+
logger,
151+
});
152+
151153
process.on("uncaughtException", (error) => {
152154
logger.error(error);
153155
process.exit(1);
154156
});
155157

156158
init = {
157-
magenta: new Magenta({ nvim: plugin.nvim, logger }),
159+
magenta: new Magenta(),
158160
logger,
159161
};
160162

rplugin/node/magenta/src/sidebar.ts

+12-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { Neovim, Buffer, Window } from "neovim";
2-
import { Logger } from "./logger.ts";
1+
import { Buffer, Window } from "neovim";
2+
import { context } from "./context.ts";
33

44
/** This will mostly manage the window toggle
55
*/
@@ -16,10 +16,7 @@ export class Sidebar {
1616
inputWindow: Window;
1717
};
1818

19-
constructor(
20-
private nvim: Neovim,
21-
private logger: Logger,
22-
) {
19+
constructor() {
2320
this.state = { state: "hidden" };
2421
// TODO: also probably need to set up some autocommands to detect if the user closes the scratch buffers
2522
}
@@ -32,15 +29,15 @@ export class Sidebar {
3229
if (this.state.state == "hidden") {
3330
return await this.create();
3431
} else {
35-
await this.destroy();
32+
this.destroy();
3633
}
3734
}
3835

3936
private async create(): Promise<{
4037
displayBuffer: Buffer;
4138
inputBuffer: Buffer;
4239
}> {
43-
const { nvim, logger } = this;
40+
const { nvim, logger } = context;
4441
logger.trace(`sidebar.create`);
4542
const totalHeight = (await nvim.getOption("lines")) as number;
4643
const cmdHeight = (await nvim.getOption("cmdheight")) as number;
@@ -50,13 +47,13 @@ export class Sidebar {
5047

5148
await nvim.command("leftabove vsplit");
5249
const displayWindow = await nvim.window;
53-
const displayBuffer = (await this.nvim.createBuffer(false, true)) as Buffer;
50+
const displayBuffer = (await nvim.createBuffer(false, true)) as Buffer;
5451
displayWindow.width = width;
5552
await nvim.lua(
5653
`vim.api.nvim_win_set_buf(${displayWindow.id}, ${displayBuffer.id})`,
5754
);
5855

59-
const inputBuffer = (await this.nvim.createBuffer(false, true)) as Buffer;
56+
const inputBuffer = (await nvim.createBuffer(false, true)) as Buffer;
6057

6158
await nvim.command("below split");
6259
const inputWindow = await nvim.window;
@@ -105,7 +102,7 @@ export class Sidebar {
105102
return { displayBuffer, inputBuffer };
106103
}
107104

108-
async destroy() {
105+
destroy() {
109106
this.state = {
110107
state: "hidden",
111108
};
@@ -146,7 +143,9 @@ export class Sidebar {
146143

147144
async getMessage(): Promise<string> {
148145
if (this.state.state != "visible") {
149-
this.logger.trace(`sidebar state is ${this.state.state} in getMessage`);
146+
context.logger.trace(
147+
`sidebar state is ${this.state.state} in getMessage`,
148+
);
150149
return "";
151150
}
152151

@@ -158,7 +157,7 @@ export class Sidebar {
158157
strictIndexing: false,
159158
});
160159

161-
this.logger.trace(
160+
context.logger.trace(
162161
`sidebar got lines ${JSON.stringify(lines)} from inputBuffer`,
163162
);
164163
const message = lines.join("\n");

rplugin/node/magenta/src/tea/render.spec.ts

-6
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ await test.describe("tea/render.spec.ts", async () => {
2929
view,
3030
props: {},
3131
mount: {
32-
nvim,
3332
buffer,
3433
startPos: { row: 0, col: 0 },
3534
endPos: { row: 0, col: 0 },
@@ -107,7 +106,6 @@ third line`;
107106
view,
108107
props: {},
109108
mount: {
110-
nvim,
111109
buffer,
112110
startPos: { row: 0, col: 0 },
113111
endPos: { row: 0, col: 0 },
@@ -191,7 +189,6 @@ third line`;
191189
view,
192190
props: {},
193191
mount: {
194-
nvim,
195192
buffer,
196193
startPos: { row: 0, col: 0 },
197194
endPos: { row: 0, col: 0 },
@@ -273,7 +270,6 @@ third line`;
273270
view,
274271
props: {},
275272
mount: {
276-
nvim,
277273
buffer,
278274
startPos: { row: 0, col: 0 },
279275
endPos: { row: 0, col: 0 },
@@ -361,7 +357,6 @@ third line`;
361357
view,
362358
props: { arr: [] },
363359
mount: {
364-
nvim,
365360
buffer,
366361
startPos: { row: 0, col: 0 },
367362
endPos: { row: 0, col: 0 },
@@ -412,7 +407,6 @@ third line`;
412407
view,
413408
props: { arr: ["1", "\n", "2"] },
414409
mount: {
415-
nvim,
416410
buffer,
417411
startPos: { row: 0, col: 0 },
418412
endPos: { row: 0, col: 0 },

0 commit comments

Comments
 (0)