Skip to content

Commit

Permalink
simplify context passing
Browse files Browse the repository at this point in the history
  • Loading branch information
dlants committed Dec 15, 2024
1 parent 5100c98 commit fdccb46
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 119 deletions.
10 changes: 5 additions & 5 deletions rplugin/node/magenta/src/anthropic.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import Anthropic from "@anthropic-ai/sdk";
import { Logger } from "./logger.ts";
import { context } from "./context.ts";
import { TOOL_SPECS, ToolRequest } from "./tools/toolManager.ts";

export class AnthropicClient {
private client: Anthropic;

constructor(private logger: Logger) {
constructor() {
const apiKey = process.env.ANTHROPIC_API_KEY;

if (!apiKey) {
Expand All @@ -21,7 +21,7 @@ export class AnthropicClient {
messages: Array<Anthropic.MessageParam>,
onText: (text: string) => void,
): Promise<ToolRequest[]> {
this.logger.trace(
context.logger.trace(
`initializing stream with messages: ${JSON.stringify(messages, null, 2)}`,
);
const buf: string[] = [];
Expand Down Expand Up @@ -60,14 +60,14 @@ export class AnthropicClient {
flushBuffer();
})
.on("inputJson", (_delta, snapshot) => {
this.logger.debug(`inputJson: ${JSON.stringify(snapshot)}`);
context.logger.debug(`inputJson: ${JSON.stringify(snapshot)}`);
});

const response = await stream.finalMessage();
const toolRequests = response.content.filter(
(c): c is ToolRequest => c.type == "tool_use",
);
this.logger.debug("toolRequests: " + JSON.stringify(toolRequests));
context.logger.debug("toolRequests: " + JSON.stringify(toolRequests));
return toolRequests;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@ export type Context = {
nvim: Neovim;
logger: Logger;
};
/** Should be called first
*/
export function setContext(c: Context) {
context = c;
}

export let context: Context;
11 changes: 9 additions & 2 deletions rplugin/node/magenta/src/debug/call-anthropic.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { AnthropicClient } from "../anthropic.ts";
import { Logger } from "../logger.ts";
import { setContext } from "../context.ts";
import { Neovim } from "neovim";

const logger = new Logger(
{
Expand All @@ -12,8 +14,13 @@ const logger = new Logger(
},
);

setContext({
nvim: undefined as unknown as Neovim,
logger,
});

async function run() {
const client = new AnthropicClient(logger);
const client = new AnthropicClient();

await client.sendMessage(
[
Expand All @@ -23,7 +30,7 @@ async function run() {
},
],
(text) => {
return Promise.resolve(console.log("text: " + text));
console.log("text: " + text);
},
);
}
Expand Down
34 changes: 18 additions & 16 deletions rplugin/node/magenta/src/magenta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,32 @@ import { NvimPlugin } from "neovim";
import { Sidebar } from "./sidebar.ts";
import * as Chat from "./chat/chat.ts";
import { Logger } from "./logger.ts";
import { Context } from "./types.ts";
import { App, createApp } from "./tea/tea.ts";
import * as ToolManager from "./tools/toolManager.ts";
import { d } from "./tea/view.ts";
import { setContext, context } from "./context.ts";

class Magenta {
private anthropicClient: AnthropicClient;
private sidebar: Sidebar;
private chat: App<Chat.Msg, Chat.Model>;
private toolManager: App<ToolManager.Msg, ToolManager.Model>;

constructor(private context: Context) {
this.context.logger.debug(`Initializing plugin`);
this.anthropicClient = new AnthropicClient(this.context.logger);
this.sidebar = new Sidebar(this.context.nvim, this.context.logger);
constructor() {
context.logger.debug(`Initializing plugin`);
this.anthropicClient = new AnthropicClient();
this.sidebar = new Sidebar();

this.chat = createApp({
initialModel: { messages: [] },
update: Chat.update,
View: Chat.view,
context,
});

this.toolManager = createApp({
initialModel: ToolManager.initModel(),
update: ToolManager.update,
View: () => d``,
context,
onUpdate: (msg, model) => {
if (msg.type == "tool-msg") {
if (msg.msg.msg.type == "finish") {
Expand All @@ -53,7 +51,7 @@ class Magenta {

if (shouldRespond) {
this.sendMessage().catch((err) =>
this.context.logger.error(err as Error),
context.logger.error(err as Error),
);
}
}
Expand All @@ -64,26 +62,25 @@ class Magenta {
}

async command(args: string[]): Promise<void> {
this.context.logger.debug(`Received command ${args[0]}`);
context.logger.debug(`Received command ${args[0]}`);
switch (args[0]) {
case "toggle": {
const buffers = await this.sidebar.toggle();
if (buffers) {
await this.chat.mount({
nvim: this.context.nvim,
buffer: buffers.displayBuffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
});
this.context.logger.trace(`Chat rendered.`);
context.logger.trace(`Chat rendered.`);
}

break;
}

case "send": {
const message = await this.sidebar.getMessage();
this.context.logger.trace(`current message: ${message}`);
context.logger.trace(`current message: ${message}`);
if (!message) return;

this.chat.dispatch({
Expand All @@ -101,14 +98,14 @@ class Magenta {
break;

default:
this.context.logger.error(`Unrecognized command ${args[0]}\n`);
context.logger.error(`Unrecognized command ${args[0]}\n`);
}
}

private async sendMessage() {
const state = this.chat.getState();
if (state.status != "running") {
this.context.logger.error(`chat is not running.`);
context.logger.error(`chat is not running.`);
return;
}

Expand All @@ -117,7 +114,7 @@ class Magenta {
const toolRequests = await this.anthropicClient.sendMessage(
messages,
(text) => {
this.context.logger.trace(`stream received text ${text}`);
context.logger.trace(`stream received text ${text}`);
this.chat.dispatch({
type: "stream-response",
text,
Expand Down Expand Up @@ -148,13 +145,18 @@ module.exports = (plugin: NvimPlugin) => {

if (!init) {
const logger = new Logger(plugin.nvim, { level: "trace" });
setContext({
nvim: plugin.nvim,
logger,
});

process.on("uncaughtException", (error) => {
logger.error(error);
process.exit(1);
});

init = {
magenta: new Magenta({ nvim: plugin.nvim, logger }),
magenta: new Magenta(),
logger,
};

Expand Down
25 changes: 12 additions & 13 deletions rplugin/node/magenta/src/sidebar.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Neovim, Buffer, Window } from "neovim";
import { Logger } from "./logger.ts";
import { Buffer, Window } from "neovim";
import { context } from "./context.ts";

/** This will mostly manage the window toggle
*/
Expand All @@ -16,10 +16,7 @@ export class Sidebar {
inputWindow: Window;
};

constructor(
private nvim: Neovim,
private logger: Logger,
) {
constructor() {
this.state = { state: "hidden" };
// TODO: also probably need to set up some autocommands to detect if the user closes the scratch buffers
}
Expand All @@ -32,15 +29,15 @@ export class Sidebar {
if (this.state.state == "hidden") {
return await this.create();
} else {
await this.destroy();
this.destroy();
}
}

private async create(): Promise<{
displayBuffer: Buffer;
inputBuffer: Buffer;
}> {
const { nvim, logger } = this;
const { nvim, logger } = context;
logger.trace(`sidebar.create`);
const totalHeight = (await nvim.getOption("lines")) as number;
const cmdHeight = (await nvim.getOption("cmdheight")) as number;
Expand All @@ -50,13 +47,13 @@ export class Sidebar {

await nvim.command("leftabove vsplit");
const displayWindow = await nvim.window;
const displayBuffer = (await this.nvim.createBuffer(false, true)) as Buffer;
const displayBuffer = (await nvim.createBuffer(false, true)) as Buffer;
displayWindow.width = width;
await nvim.lua(
`vim.api.nvim_win_set_buf(${displayWindow.id}, ${displayBuffer.id})`,
);

const inputBuffer = (await this.nvim.createBuffer(false, true)) as Buffer;
const inputBuffer = (await nvim.createBuffer(false, true)) as Buffer;

await nvim.command("below split");
const inputWindow = await nvim.window;
Expand Down Expand Up @@ -105,7 +102,7 @@ export class Sidebar {
return { displayBuffer, inputBuffer };
}

async destroy() {
destroy() {
this.state = {
state: "hidden",
};
Expand Down Expand Up @@ -146,7 +143,9 @@ export class Sidebar {

async getMessage(): Promise<string> {
if (this.state.state != "visible") {
this.logger.trace(`sidebar state is ${this.state.state} in getMessage`);
context.logger.trace(
`sidebar state is ${this.state.state} in getMessage`,
);
return "";
}

Expand All @@ -158,7 +157,7 @@ export class Sidebar {
strictIndexing: false,
});

this.logger.trace(
context.logger.trace(
`sidebar got lines ${JSON.stringify(lines)} from inputBuffer`,
);
const message = lines.join("\n");
Expand Down
6 changes: 0 additions & 6 deletions rplugin/node/magenta/src/tea/render.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ await test.describe("tea/render.spec.ts", async () => {
view,
props: {},
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down Expand Up @@ -107,7 +106,6 @@ third line`;
view,
props: {},
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down Expand Up @@ -191,7 +189,6 @@ third line`;
view,
props: {},
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down Expand Up @@ -273,7 +270,6 @@ third line`;
view,
props: {},
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down Expand Up @@ -361,7 +357,6 @@ third line`;
view,
props: { arr: [] },
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down Expand Up @@ -412,7 +407,6 @@ third line`;
view,
props: { arr: ["1", "\n", "2"] },
mount: {
nvim,
buffer,
startPos: { row: 0, col: 0 },
endPos: { row: 0, col: 0 },
Expand Down
Loading

0 comments on commit fdccb46

Please sign in to comment.