Skip to content

Commit

Permalink
work
Browse files Browse the repository at this point in the history
  • Loading branch information
StoneT2000 committed Jan 22, 2022
1 parent 3b6acfc commit 6c96c71
Show file tree
Hide file tree
Showing 14 changed files with 177 additions and 25 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,10 @@ make sure to update version before publishing!

windows wsl2 electron dev stuff:
https://gist.github.com/caseywatts/9700b402b6b51d1d6af9f0b206739770

## how to add new IPC actions

1. add it to ipc/{namespace}/actions/{name}.ts
2. add it preload.ts
3. add it to ipc/{namespace}/actions/index.ts
4. add it to ipc/{namespace}/index.ts
2 changes: 1 addition & 1 deletion src/main/envs/rps/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ <h2 id="score-title">Score: 0, 0</h2>
window.addEventListener('message', (event) => {
console.log('data', event.data);
const scoreTitle = document.getElementById('score-title');
scoreTitle.textContent = `Score: ${event.data.info['player_0'].score} ${event.data.info['player_1'].score}`;
scoreTitle.textContent = `Score: ${event.data['player_0'].info.score} ${event.data['player_1'].info.score}`;
//TODO. do something with observations
});
</script>
Expand Down
30 changes: 30 additions & 0 deletions src/main/ipc/dimensions/actions/createEpisode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Context } from 'main/ipc/dimensions/context';
import type { Action } from 'main/ipc/types';
import { getEnv } from '../envScheduler';

interface Data {
env: string;
agents: string[];
}

type Result = {
episodeId: string;
env: string;
metaData: $TSFIXME;
name: string;
};

export const createEpisode: Action<Data, Result, Context> =
(ctx) => async (_event, data) => {
const env = await getEnv(data.env, ctx);
const { episodes } = ctx.data;
const episode = await ctx.dim.createEpisode(env, data.agents);
await episode.initialize();
episodes.set(episode.id, episode);
return {
episodeId: episode.id,
env: data.env,
metaData: env.metaData,
name: env.configs.name ?? '',
};
};
22 changes: 22 additions & 0 deletions src/main/ipc/dimensions/actions/envStep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { EpisodeResult } from 'dimensions-ai-temp/lib/main/Episode';
import { Context } from 'main/ipc/dimensions/context';
import type { Action } from 'main/ipc/types';

interface Data {
episodeId: string;
}

type Result = { results: EpisodeResult; done: boolean };

export const envStep: Action<Data, Result, Context> =
(ctx) => async (_event, data) => {
const { episodes } = ctx.data;
const episode = episodes.get(data.episodeId);
console.log('HERE');
if (episode) {
console.log('HERE2');
const done = await episode.stepParallel();
return { results: episode.results, done };
}
throw Error(`Episode with id ${data.episodeId} not found!`);
};
2 changes: 2 additions & 0 deletions src/main/ipc/dimensions/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export { runEpisode } from './runEpisode';
export { runSingleEpisode } from './runSingleEpisode';
export { initializeAgents } from './initializeAgents';
export { envRegisterAgents } from './envRegisterAgents';
export { envStep } from './envStep';
export { createEpisode } from './createEpisode';
14 changes: 3 additions & 11 deletions src/main/ipc/dimensions/actions/makeEnv.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Context } from 'main/ipc/dimensions/context';
import type { Action } from 'main/ipc/types';
import { getEnv } from '../envScheduler';

interface Data {
env: string;
Expand All @@ -8,22 +9,13 @@ interface Data {
type Result = {
name: string;
id: string;
metaData: any;
metaData: $TSFIXME;
};

export const makeEnv: Action<Data, Result, Context> =
(ctx) => async (_event, data) => {
// TODO, maybe some clustering / scheduling to determine whihc env to give back
const { envs } = ctx.data;
// console.log({ ctx });
let env = envs.get(data.env);
if (env) {
console.log('FREE ENV EXISTS ALREADY, REUSUING', env.id);
} else {
console.log('CREATING ENV', data.env);
env = await ctx.dim.makeEnv(data.env);
ctx.data.envs.set(data.env, env);
}
const env = await getEnv(data.env, ctx);
const out = {
name: env.configs.name ?? '',
id: env.id,
Expand Down
2 changes: 2 additions & 0 deletions src/main/ipc/dimensions/context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Environment } from 'dimensions-ai-temp/lib/main/Environment';
import { Episode } from 'dimensions-ai-temp/lib/main/Episode';
import { Dimension } from 'dimensions-ai-temp/lib/main/Dimension';

export interface Context {
Expand All @@ -9,5 +10,6 @@ export interface Context {
// TODO: map env name as well to the same stuff
envs: Map<string, Environment>;
envNameToEnvs: Map<string, Environment>;
episodes: Map<string, Episode>;
};
}
19 changes: 19 additions & 0 deletions src/main/ipc/dimensions/envScheduler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Context } from 'main/ipc/dimensions/context';

/**
* Finds an available environment process to use. If none available, a new one is created
* @param envstr
* @param ctx
* @returns
*/
export const getEnv = async (envstr: string, ctx: Context) => {
let env = ctx.data.envs.get(envstr);
if (env) {
console.log('FREE ENV EXISTS ALREADY, REUSUING', env.id);
} else {
console.log('CREATING ENV', envstr);
env = await ctx.dim.makeEnv(envstr);
ctx.data.envs.set(envstr, env);
}
return env;
};
5 changes: 4 additions & 1 deletion src/main/ipc/dimensions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import DimensionsApi from './dimensions';
export const setupDimensions = (store: Store) => {
const dim = new Dimension();
// pipeline.setup(dim, store);
// context lives in memory only
const ctx: Context = {
dim,
data: { envs: new Map(), envNameToEnvs: new Map() },
data: { envs: new Map(), envNameToEnvs: new Map(), episodes: new Map() },
store,
};
handleFunc(DimensionsApi, 'makeEnv', ctx);
handleFunc(DimensionsApi, 'closeEnv');
handleFunc(DimensionsApi, 'runEpisode', ctx);
handleFunc(DimensionsApi, 'initializeAgents', ctx);
handleFunc(DimensionsApi, 'envRegisterAgents');
handleFunc(DimensionsApi, 'envStep', ctx);
handleFunc(DimensionsApi, 'createEpisode', ctx);
};
6 changes: 6 additions & 0 deletions src/main/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ const handlers: Window['electron'] = {
data
);
},
envStep(data) {
return invokeFunc<Dimensions, 'envStep'>('dim_envStep', data);
},
createEpisode(data) {
return invokeFunc<Dimensions, 'createEpisode'>('dim_createEpisode', data);
},
},
user: {
getPreferences(data) {
Expand Down
16 changes: 13 additions & 3 deletions src/renderer/components/Control/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,22 @@ import styles from './control.scss';

const Control = () => {
const { userPreferences, setUserPreferences } = useContext(UserContext);
const { env, runEpisode } = useContext(EnvContext);
const { env, runEpisode, createEpisode, envStep } = useContext(EnvContext);
const setEnv = (filepath: string) => {
setUserPreferences({ env: filepath });
};
const [episodeId, setEpisodeId] = useState('');
const [matchResult, setMatchResult] = useState<
Awaited<ReturnType<ReturnType<Dimensions['actions']['runSingleEpisode']>>> // TODO: maybe extract some of these input/ouput types to somewhere else?
>({
final: 'abc',
});

const runMatch = () => {
runEpisode(env, [], true, 0);
const runMatch = async () => {
// runEpisode(env, [], true, 0);
const res = await createEpisode(env);
setEpisodeId(res.episodeId);
const { postdata } = await envStep(res.episodeId);
// runSingleEpisode(env, [], 0)
// .then((res) => {
// console.log({ res });
Expand All @@ -39,6 +43,9 @@ const Control = () => {
// console.error(err);
// });
};
const stepForward = async () => {
const { postdata } = await envStep(episodeId);
};
// TODO move this out of this component
const selectEnvironment = async () => {
// window.electron.store.get(STORE.ENV).then(console.log)
Expand Down Expand Up @@ -70,6 +77,9 @@ const Control = () => {
<Button onClick={runMatch} variant="contained" color="primary">
Run Match
</Button>
<Button onClick={stepForward} variant="contained" color="primary">
Step
</Button>
{matchResult && (
<div className={styles['result-box']}>
<ReactJson src={matchResult} />
Expand Down
11 changes: 9 additions & 2 deletions src/renderer/components/section/viewer/Viewer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect } from 'react';
import React, { useContext, useEffect } from 'react';
import EnvContext from 'renderer/contexts/env';
import Base from '../base';
import type { GridSectionProps } from '../groups';
import styles from './styles.scss';
Expand All @@ -14,8 +15,14 @@ const Viewer: React.FC<ViewerProps> = ({
vStart,
vEnd,
}) => {
const { setIframe } = useContext(EnvContext);
console.log('GOT', html);
useEffect(() => {}, []);
useEffect(() => {
const iframe = document.getElementById('FileFrame') as HTMLIFrameElement;
setIframe(iframe);
console.log('SET IFRAME');
}, [html, setIframe]);

return (
<Base
className={styles.viewer}
Expand Down
17 changes: 11 additions & 6 deletions src/renderer/contexts/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import React from 'react';
// set UserContext and add type
const EnvContext = React.createContext(
{} as {
iframe?: HTMLIFrameElement;
setIframe: React.Dispatch<
React.SetStateAction<HTMLIFrameElement | undefined>
>;
env: string;
setEnv: (env: string) => $TSFIXME;
runEpisode: (
Expand All @@ -14,12 +18,13 @@ const EnvContext = React.createContext(
html?: string;
postdata: string;
}>;
// createEpisode: (env: string) => Promise<{
// episodeId: string;
// }>;
// envStep: (env: string) => Promise<{
// postdata: string;
// }>;
createEpisode: (env: string) => Promise<{
html?: string;
episodeId: string;
}>;
envStep: (episodeId: string) => Promise<{
postdata: string;
}>;
}
);

Expand Down
49 changes: 48 additions & 1 deletion src/renderer/pages/illuminator/Illuminator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const Illuminator = () => {
setUserPreferences({ env: filepath });
};
const [html, setHtml] = useState('');
const [iframe, setIframe] = useState<HTMLIFrameElement>();
const runEpisode = async (
envFile: string, // change to env name
_agents: string[],
Expand All @@ -31,6 +32,42 @@ const Illuminator = () => {
};
// envData.id;
};

// temp storing epiode here
const [episodeId, setEpisodeId] = useState('');
const createEpisode = async (envFile: string) => {
const pyagent =
'/Users/stonetao/Desktop/Coding/Projects/aicompetitions/dimensions/tests/envs/rps/agents/agent.py';
const jsagent =
'/Users/stonetao/Desktop/Coding/Projects/aicompetitions/dimensions/tests/envs/rps/agents/paper.js';
const res = await window.electron.dimensions.createEpisode({
env: envFile,
agents: [pyagent, jsagent],
});
setEpisodeId(res.episodeId);
console.log('NEW EPISODE', res.episodeId, env);
const htmlPath = path.join(path.dirname(envFile), res.metaData.html);
const html2 = (await window.electron.system.readFile(htmlPath)) as string;
setHtml(html2);
return {
html: html2,
episodeId: res.episodeId,
};
};
// todo move this to actions or smth
const envStep = async (_episodeId: string) => {
const res = await window.electron.dimensions.envStep({
episodeId: _episodeId,
});
console.log('STEP', res.results);
iframe!.contentWindow!.postMessage(
res.results.outputs[res.results.outputs.length - 1].data
);
return {
postdata: JSON.stringify(res.results),
};
};
const updateRenderer = async (postdata: string) => {};
useEffect(() => {
// timer =
// createEpisode(envId)
Expand All @@ -41,7 +78,17 @@ const Illuminator = () => {
}, []);
return (
<div className={styles.grid}>
<EnvProvider value={{ setEnv, env, runEpisode }}>
<EnvProvider
value={{
setEnv,
env,
runEpisode,
createEpisode,
envStep,
iframe,
setIframe,
}}
>
<Base hStart={0} hEnd={1} vStart={0} vEnd={2}>
<Control />
</Base>
Expand Down

0 comments on commit 6c96c71

Please sign in to comment.